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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchActionsUtil.kt | 3 | 6281 | // 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 git4idea.ui.branch
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.dvcs.branch.isGroupingEnabled
import com.intellij.dvcs.branch.setGrouping
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import git4idea.GitLocalBranch
import git4idea.GitNotificationIdsHolder.Companion.BRANCHES_UPDATE_SUCCESSFUL
import git4idea.GitReference
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.branch.GitBranchPair
import git4idea.branch.GitBranchUtil
import git4idea.branch.GitNewBranchDialog
import git4idea.config.GitVcsSettings
import git4idea.fetch.GitFetchSupport
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.update.GitUpdateExecutionProcess
import org.jetbrains.annotations.Nls
import javax.swing.Icon
@JvmOverloads
internal fun createOrCheckoutNewBranch(project: Project,
repositories: List<GitRepository>,
startPoint: String,
@Nls(capitalization = Nls.Capitalization.Title)
title: String = GitBundle.message("branches.create.new.branch.dialog.title"),
initialName: String? = null) {
val options = GitNewBranchDialog(project, repositories, title, initialName, true, true, false, true).showAndGetOptions() ?: return
GitBranchCheckoutOperation(project, repositories).perform(startPoint, options)
}
internal fun updateBranches(project: Project, repositories: List<GitRepository>, localBranchNames: List<String>) {
val repoToTrackingInfos =
repositories.associateWith { it.branchTrackInfos.filter { info -> localBranchNames.contains(info.localBranch.name) } }
if (repoToTrackingInfos.isEmpty()) return
GitVcs.runInBackground(object : Task.Backgroundable(project, GitBundle.message("branches.updating.process"), true) {
private val successfullyUpdated = arrayListOf<String>()
override fun run(indicator: ProgressIndicator) {
val fetchSupport = GitFetchSupport.fetchSupport(project)
val currentBranchesMap: MutableMap<GitRepository, GitBranchPair> = HashMap()
for ((repo, trackingInfos) in repoToTrackingInfos) {
val currentBranch = repo.currentBranch
for (trackingInfo in trackingInfos) {
val localBranch = trackingInfo.localBranch
val remoteBranch = trackingInfo.remoteBranch
if (localBranch == currentBranch) {
currentBranchesMap[repo] = GitBranchPair(currentBranch, remoteBranch)
}
else {
// Fast-forward all non-current branches in the selection
val localBranchName = localBranch.name
val remoteBranchName = remoteBranch.nameForRemoteOperations
val fetchResult = fetchSupport.fetch(repo, trackingInfo.remote, "$remoteBranchName:$localBranchName")
try {
fetchResult.throwExceptionIfFailed()
successfullyUpdated.add(localBranchName)
}
catch (ignored: VcsException) {
fetchResult.showNotificationIfFailed(GitBundle.message("branches.update.failed"))
}
}
}
}
// Update all current branches in the selection
if (currentBranchesMap.isNotEmpty()) {
GitUpdateExecutionProcess(project,
repositories,
currentBranchesMap,
GitVcsSettings.getInstance(project).updateMethod,
false).execute()
}
}
override fun onSuccess() {
if (successfullyUpdated.isNotEmpty()) {
VcsNotifier.getInstance(project).notifySuccess(BRANCHES_UPDATE_SUCCESSFUL, "",
GitBundle.message("branches.selected.branches.updated.title",
successfullyUpdated.size,
successfullyUpdated.joinToString("\n")))
}
}
})
}
internal fun isTrackingInfosExist(branchNames: List<String>, repositories: List<GitRepository>) =
repositories
.flatMap(GitRepository::getBranchTrackInfos)
.any { trackingBranchInfo -> branchNames.any { branchName -> branchName == trackingBranchInfo.localBranch.name } }
internal fun hasRemotes(project: Project): Boolean {
return GitUtil.getRepositories(project).any { repository -> !repository.remotes.isEmpty() }
}
internal fun hasTrackingConflicts(conflictingLocalBranches: Map<GitRepository, GitLocalBranch>,
remoteBranchName: String): Boolean =
conflictingLocalBranches.any { (repo, branch) ->
val trackInfo = GitBranchUtil.getTrackInfoForBranch(repo, branch)
trackInfo != null && !GitReference.BRANCH_NAME_HASHING_STRATEGY.equals(remoteBranchName, trackInfo.remoteBranch.name)
}
internal abstract class BranchGroupingAction(private val key: GroupingKey,
icon: Icon? = null) : ToggleAction(key.text, key.description, icon), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
abstract fun setSelected(e: AnActionEvent, key: GroupingKey, state: Boolean)
override fun isSelected(e: AnActionEvent) =
e.project?.let { GitVcsSettings.getInstance(it).branchSettings.isGroupingEnabled(key) } ?: false
override fun setSelected(e: AnActionEvent, state: Boolean) {
val project = e.project ?: return
val branchSettings = GitVcsSettings.getInstance(project).branchSettings
branchSettings.setGrouping(key, state)
setSelected(e, key, state)
}
}
| apache-2.0 | 7c4c898eccc8811d8f3084a20dd0588b | 46.583333 | 140 | 0.690973 | 5.169547 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/KotlinDfaAssistTest.kt | 5 | 6854 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.test
import com.intellij.debugger.engine.dfaassist.DfaAssistTest
import com.intellij.debugger.mockJDI.MockLocalVariable
import com.intellij.debugger.mockJDI.MockStackFrame
import com.intellij.debugger.mockJDI.MockVirtualMachine
import com.intellij.debugger.mockJDI.values.MockBooleanValue
import com.intellij.debugger.mockJDI.values.MockIntegerValue
import com.intellij.debugger.mockJDI.values.MockObjectReference
import com.intellij.debugger.mockJDI.values.MockValue
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.ProjectDescriptorWithStdlibSources
import java.lang.annotation.ElementType
import java.util.function.BiConsumer
class KotlinDfaAssistTest : DfaAssistTest() {
override fun getProjectDescriptor(): LightProjectDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE
fun testSimple() {
doTest("""fun test(x: Int) {
<caret>if (x > 0/*TRUE*/) {
}
if (x in 1..6/*TRUE*/) {
}
if (1 in x..10/*FALSE*/) {
}
}
fun main() {
test(5)
}""") { vm, frame -> frame.addVariable("x", MockIntegerValue(vm, 5)) }
}
fun testSuppression() {
doTest("""fun test(x: Boolean, y: Boolean) {
<caret>if(!x/*FALSE*/) {}
if (x/*TRUE*/ || y) {}
if (y || x/*TRUE*/) {}
var z: Boolean
z = x/*TRUE*/
var b = true
}""") { vm, frame -> frame.addVariable("x", MockBooleanValue(vm, true)) }
}
fun testWhen() {
doTest("""fun obj(x: Any) {
<caret>when(x) {
is String/*FALSE*/ -> {}
is Int/*TRUE*/ -> {}
}
}
fun main() {
obj(5)
}""") { vm, frame -> frame.addVariable("x", MockValue.createValue(1, Integer::class.java, vm)) }
}
fun testWrapped() {
doTest("""fun test(x: Int) {
var y = x
val fn = { y++ }
fn()
<caret>if (y > 0/*TRUE*/) {
}
if (y == 0/*FALSE*/) {}
if (y < 0/*FALSE*/) {}
}
fun main() {
test(5)
}""") { vm, frame ->
val cls = Class.forName("kotlin.jvm.internal.Ref\$IntRef")
val box = cls.getConstructor().newInstance()
cls.getDeclaredField("element").set(box, 6)
frame.addVariable("y", MockValue.createValue(box, cls, vm))
}
}
class Nested(@Suppress("unused") val x:Int)
fun testThis() {
doTest("""package org.jetbrains.kotlin.idea.debugger.test
class KotlinDfaAssistTest {
class Nested(val x:Int) {
fun test() {
<caret>if (x == 5/*TRUE*/) {}
}
}
}
""") { vm, frame ->
frame.setThisValue(MockObjectReference.createObjectReference(Nested(5), Nested::class.java, vm))
}
}
fun testQualified() {
doTest("""package org.jetbrains.kotlin.idea.debugger.test
class KotlinDfaAssistTest {
class Nested(val x:Int)
}
fun use(n : KotlinDfaAssistTest.Nested) {
<caret>if (n.x > 5/*TRUE*/) {}
}
""") { vm, frame ->
frame.addVariable("n", MockValue.createValue(Nested(6), Nested::class.java, vm))
}
}
fun testExtensionMethod() {
doTest("""fun String.isLong(): Boolean {
<caret>return this.length > 5/*FALSE*/
}
fun main() {
"xyz".isLong()
}""") { vm, frame ->
frame.addVariable("\$this\$isLong", MockValue.createValue("xyz", String::class.java, vm))
}
}
fun testDeconstruction() {
doTest("""fun test(x: Pair<Int, Int>) {
val (a, b) = x
<caret>if (a > b/*FALSE*/) {}
}
fun main() {
test(3 to 5)
}""") { vm, frame ->
frame.addVariable("a", MockIntegerValue(vm, 3))
frame.addVariable("b", MockIntegerValue(vm, 5))
}
}
fun testNPE() {
doTest("""
fun test(x: String?) {
<caret>println(x/*NPE*/!!)
}
""".trimIndent()) { vm, frame ->
frame.addVariable(MockLocalVariable(vm, "x", vm.createReferenceType(String::class.java), null))
}
}
fun testAsNull() {
doTest("""
fun test(x: Any?) {
<caret>println(x as String?)
println(x as/*NPE*/ String)
}
""".trimIndent()) { vm, frame ->
frame.addVariable(MockLocalVariable(vm, "x", vm.createReferenceType(String::class.java), null))
}
}
fun testAs() {
doTest("""
fun test(x: Any?) {
<caret>println(x as/*CCE*/ Int)
}
""".trimIndent()) { vm, frame ->
frame.addVariable("x", MockValue.createValue("", vm))
}
}
fun testNull() {
doTest("""
fun main() {
test("hello", null)
}
fun test(x: Any, y: String?) {
<caret>println(x as? Int/*NULL*/)
println(y/*NULL*/ ?: "oops")
}
""".trimIndent()) { vm, frame ->
frame.addVariable("x", MockValue.createValue("xyz", vm))
frame.addVariable(MockLocalVariable(vm, "y", vm.createReferenceType(String::class.java), null))
}
}
fun testEnum() {
val text = """import java.lang.annotation.ElementType
class Test {
fun test(t : ElementType) {
<caret>if (t == ElementType.PARAMETER/*FALSE*/) {}
if (t == ElementType.METHOD/*TRUE*/) {}
}
}"""
doTest(text) { vm, frame ->
frame.addVariable("t", MockValue.createValue(ElementType.METHOD, ElementType::class.java, vm))
}
}
private fun doTest(text: String, mockValues: BiConsumer<MockVirtualMachine, MockStackFrame>) {
doTest(text, mockValues, "Test.kt")
}
} | apache-2.0 | f63a5c4da45aea167af6f95010f90fd4 | 32.602941 | 120 | 0.476364 | 4.527081 | false | true | false | false |
square/okhttp | samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt | 2 | 1921 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.recipes.kt
import java.io.IOException
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okio.BufferedSink
class PostStreaming {
private val client = OkHttpClient()
fun run() {
val requestBody = object : RequestBody() {
override fun contentType() = MEDIA_TYPE_MARKDOWN
override fun writeTo(sink: BufferedSink) {
sink.writeUtf8("Numbers\n")
sink.writeUtf8("-------\n")
for (i in 2..997) {
sink.writeUtf8(String.format(" * $i = ${factor(i)}\n"))
}
}
private fun factor(n: Int): String {
for (i in 2 until n) {
val x = n / i
if (x * i == n) return "${factor(x)} × $i"
}
return n.toString()
}
}
val request = Request(
url = "https://api.github.com/markdown/raw".toHttpUrl(),
body = requestBody,
)
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
}
fun main() {
PostStreaming().run()
}
| apache-2.0 | 108b39fed8f5978d1b41afc38ee230f4 | 26.826087 | 80 | 0.655208 | 3.975155 | false | false | false | false |
dmcg/konsent | src/main/java/com/oneeyedmen/konsent/webdriver/web-matchers.kt | 1 | 1372 | package com.oneeyedmen.konsent.webdriver
import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import com.oneeyedmen.konsent.matcherOf
import org.openqa.selenium.WebElement
import org.openqa.selenium.remote.RemoteWebElement
import java.net.URI
fun <T: WebElement?> elementMatcher(description: String, predicate: (T) -> Boolean) = object: Matcher.Primitive<T>() {
override val description = description
override fun invoke(actual: T): MatchResult = if (predicate(actual)) MatchResult.Match
else MatchResult.Mismatch("was ${describeWebElement(actual)}")
private fun describeWebElement(actual: T): String {
if (actual == null)
return "[No such element]"
else
return "<${actual.tagName}>${actual.text}</>"
}
}
fun containsALink(text: String, href: String) = elementMatcher<RemoteWebElement?>("contains a link [$text]($href)") { element ->
element != null && element.findElementsByXPath("//a[@href='$href'][text()='$text']").isNotEmpty()
}
val isntThere = elementMatcher<RemoteWebElement?>("isn't there") { it == null }
val hasSomeContent = elementMatcher<RemoteWebElement?>("has some content") {
it != null && it.isDisplayed
}
fun pathContains(pathElement: String) = matcherOf<URI>(""""location contains "$pathElement"""") { uri ->
uri.toString().contains(pathElement)
}
| apache-2.0 | 7e143978ce28203689182ffaa08b3f0d | 37.111111 | 128 | 0.709184 | 3.988372 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/remote/notification/NotificationRemoteDataSourceImpl.kt | 1 | 2286 | package org.stepik.android.remote.notification
import io.reactivex.Completable
import io.reactivex.Single
import org.stepic.droid.model.NotificationCategory
import org.stepic.droid.notifications.model.Notification
import org.stepic.droid.notifications.model.NotificationStatuses
import ru.nobird.app.core.model.PagedList
import org.stepik.android.data.notification.source.NotificationRemoteDataSource
import org.stepik.android.remote.base.mapper.toPagedList
import org.stepik.android.remote.notification.model.NotificationRequest
import org.stepik.android.remote.notification.model.NotificationResponse
import org.stepik.android.remote.notification.model.NotificationStatusesResponse
import org.stepik.android.remote.notification.service.NotificationService
import javax.inject.Inject
class NotificationRemoteDataSourceImpl
@Inject
constructor(
private val notificationService: NotificationService
) : NotificationRemoteDataSource {
override fun putNotifications(vararg notificationIds: Long, isRead: Boolean): Completable =
Completable.concat(notificationIds.map { id ->
val notification = Notification()
notification.isUnread = !isRead
notificationService.putNotification(id, NotificationRequest(notification))
})
override fun getNotifications(notificationCategory: NotificationCategory, page: Int): Single<PagedList<Notification>> =
notificationService
.getNotifications(page, type = getNotificationCategoryString(notificationCategory))
.map { it.toPagedList(NotificationResponse::notifications) }
override fun markNotificationAsRead(notificationCategory: NotificationCategory): Completable =
notificationService
.markNotificationAsRead(getNotificationCategoryString(notificationCategory))
override fun getNotificationStatuses(): Single<List<NotificationStatuses>> =
notificationService
.getNotificationStatuses()
.map(NotificationStatusesResponse::notificationStatuses)
private fun getNotificationCategoryString(notificationCategory: NotificationCategory): String? =
if (notificationCategory === NotificationCategory.all) {
null
} else {
notificationCategory.name
}
} | apache-2.0 | fb961b2f0b5b452429dd9fbfcb7f0ee5 | 44.74 | 123 | 0.783027 | 5.602941 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/typedescriptor/template/TemplateHolderTypeDescriptor.kt | 1 | 1474 | package com.aemtools.analysis.htl.callchain.typedescriptor.template
import com.aemtools.analysis.htl.callchain.typedescriptor.base.BaseTypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor
import com.aemtools.completion.htl.model.ResolutionResult
import com.aemtools.index.model.TemplateDefinition
import com.aemtools.lang.htl.icons.HtlIcons
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.project.Project
/**
* Descriptor of type spawned in `data-sly-use` which included some Htl template containing file.
*
* @author Dmytro Troynikov
*/
class TemplateHolderTypeDescriptor(
val templates: List<TemplateDefinition>,
val project: Project)
: BaseTypeDescriptor() {
override fun myVariants(): List<LookupElement> {
return templates.map {
LookupElementBuilder.create(it.name)
.withTypeText("HTL Template")
.withIcon(HtlIcons.HTL_FILE_ICON)
}
}
override fun subtype(identifier: String): TypeDescriptor {
return templates.find { it.name == identifier }
.toTypeDescriptor()
}
override fun asResolutionResult(): ResolutionResult =
ResolutionResult(null, myVariants())
private fun TemplateDefinition?.toTypeDescriptor(): TypeDescriptor =
if (this != null) {
TemplateTypeDescriptor(this, project)
} else {
TypeDescriptor.empty()
}
}
| gpl-3.0 | e6b25f057e1677cf1b3065c3ee944a50 | 31.755556 | 97 | 0.753053 | 4.549383 | false | false | false | false |
DmytroTroynikov/aemtools | common/src/main/kotlin/com/aemtools/common/util/PathUtil.kt | 1 | 793 | package com.aemtools.common.util
import com.aemtools.common.constant.const.JCR_ROOT_SEPARATED
/**
* Normalize given path to *jcr_root* folder.
* e.g.:
*
* ```
* .../src/jcr_root/apps/components -> /apps/components
* ```
* @receiver [String]
* @return path normalized to jcr_root
*/
fun String.normalizeToJcrRoot(): String =
"/${substringAfter(JCR_ROOT_SEPARATED)}"
/**
* Given:
* Current string is a path to file, input string is path to file
* within current directory.
*
* ```
* this = /some/path
* path = /some/path/under/file.html
* result = under/file.html
* ```
*
* @receiver [String]
* @return new relative path
*/
fun String.relativeTo(path: String): String =
if (startsWith("$path/")) {
substring(path.length + 1)
} else {
this
}
| gpl-3.0 | 68e231a21e792e33789f14ff3f1f708d | 20.432432 | 65 | 0.636822 | 3.290456 | false | false | false | false |
spring-projects/spring-framework | spring-test/src/main/kotlin/org/springframework/test/web/servlet/MockMvcExtensions.kt | 1 | 8612 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet
import org.springframework.http.HttpMethod
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import java.net.URI
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.get
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.get(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.get(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.get
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.get(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.get(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.post
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.post(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.post(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.post
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.post(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.post(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.put
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.put(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.put(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.put
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.put(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.put(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.patch
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.patch(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.patch(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.patch
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.patch(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.patch(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.delete
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.delete(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.delete(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.delete
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.delete(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.delete(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.options
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.options(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.options(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.options
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.options(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.options(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.head
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.head(urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.head(urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.head
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.head(uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.head(uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.request
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.request(method: HttpMethod, urlTemplate: String, vararg vars: Any?, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.request(method, urlTemplate, *vars)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.request
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.request(method: HttpMethod, uri: URI, dsl: MockHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.request(method, uri)
return MockHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockMultipartHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.multipart
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.multipart(urlTemplate: String, vararg vars: Any?, dsl: MockMultipartHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.multipart(urlTemplate, *vars)
return MockMultipartHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
/**
* [MockMvc] extension providing access to [MockMultipartHttpServletRequestDsl] Kotlin DSL.
*
* @see MockMvcRequestBuilders.multipart
* @author Sebastien Deleuze
* @since 5.2
*/
fun MockMvc.multipart(uri: URI, dsl: MockMultipartHttpServletRequestDsl.() -> Unit = {}): ResultActionsDsl {
val requestBuilder = MockMvcRequestBuilders.multipart(uri)
return MockMultipartHttpServletRequestDsl(requestBuilder).apply(dsl).perform(this)
}
| apache-2.0 | b878c539e1a5c7a83260068a139a906e | 35.337553 | 147 | 0.762657 | 4.174503 | false | false | false | false |
HTWDD/HTWDresden | app/src/main/java/de/htwdd/htwdresden/utils/holders/CryptoSharedPreferencesHolder.kt | 1 | 3816 | package de.htwdd.htwdresden.utils.holders
import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import de.htwdd.htwdresden.utils.extensions.guard
import io.reactivex.subjects.BehaviorSubject
import java.nio.charset.Charset
class CryptoSharedPreferencesHolder private constructor() {
private object Holder { val INSTANCE = CryptoSharedPreferencesHolder() }
private lateinit var masterKeyAlias: String
private lateinit var sharedPreferences: SharedPreferences
sealed class SubscribeType {
object StudyToken: SubscribeType()
object AuthToken: SubscribeType()
object Crashlytics: SubscribeType()
}
companion object {
private val subject = BehaviorSubject.create<SubscribeType>()
val instance: CryptoSharedPreferencesHolder by lazy { Holder.INSTANCE }
fun init(context: Context) {
instance.masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
instance.sharedPreferences = EncryptedSharedPreferences.create(
"htw_encrypted_shared_prefs",
instance.masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM)
}
private const val STUDY_TOKEN = "STUDY_TOKEN"
private const val AUTH_TOKEN = "AUTH_TOKEN"
private const val IS_FIRST_RUN = "IS_FIRST_RUN"
private const val HAS_CRASHLYTICS = "HAS_CRASHLYTICS"
}
fun putStudyToken(studyToken: String) {
sharedPreferences.edit {
subject.onNext(SubscribeType.StudyToken)
putString(STUDY_TOKEN, studyToken)
}
}
fun getStudyToken() = sharedPreferences.getString(STUDY_TOKEN, "")
fun getStudyAuth() = readAuthToken(getStudyToken())
fun putAuthToken(authToken: String) {
sharedPreferences.edit {
subject.onNext(SubscribeType.AuthToken)
putString(AUTH_TOKEN, authToken)
}
}
fun getAuthToken() = sharedPreferences.getString(AUTH_TOKEN, "")
fun setOnboarding(isNeeded: Boolean) = sharedPreferences.edit { putBoolean(IS_FIRST_RUN, isNeeded) }
fun needsOnboarding() = sharedPreferences.getBoolean(IS_FIRST_RUN, true)
fun hasCrashlytics() = sharedPreferences.getBoolean(HAS_CRASHLYTICS, false)
fun setCrashlytics(active: Boolean) {
sharedPreferences.edit {
subject.onNext(SubscribeType.Crashlytics)
putBoolean(HAS_CRASHLYTICS, active)
}
}
fun onChanged() = subject
fun clear() {
sharedPreferences.edit {
remove(STUDY_TOKEN)
subject.onNext(SubscribeType.StudyToken)
remove(AUTH_TOKEN)
subject.onNext(SubscribeType.AuthToken)
remove(HAS_CRASHLYTICS)
subject.onNext(SubscribeType.Crashlytics)
remove(IS_FIRST_RUN)
}
}
private fun readAuthToken(token: String?): StudyAuth? {
token.guard { return null }
val rawToken = String(Base64.decode(token, Base64.DEFAULT), Charset.forName("UTF-8"))
val chunks = rawToken.split(":")
if (chunks.size < 4) { return null }
return StudyAuth(
chunks[0],
chunks[1],
chunks[2],
chunks[3].first().toString()
)
}
//---------------------------------------------------------------------------------------------- Data Class
data class StudyAuth(val studyYear: String, val major: String, val group: String, val graduation: String)
} | mit | a1bdbf595ed5548b54f6e2eed38cac76 | 35.009434 | 111 | 0.652516 | 4.824273 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/IrDescriptorSerializer.kt | 2 | 6789 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.serialization.KonanDescriptorSerializer
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.ir.descriptors.IrTemporaryVariableDescriptor
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.inference.CapturedType
import org.jetbrains.kotlin.resolve.calls.inference.isCaptured
import org.jetbrains.kotlin.serialization.KonanIr
import org.jetbrains.kotlin.types.KotlinType
val DeclarationDescriptor.classOrPackage: DeclarationDescriptor?
get() {
return if (this.containingDeclaration!! is ClassOrPackageFragmentDescriptor)
containingDeclaration
else null
}
internal class IrDescriptorSerializer(
val context: Context,
val descriptorTable: DescriptorTable,
val stringTable: KonanStringTable,
val localDeclarationSerializer: LocalDeclarationSerializer,
var rootFunction: FunctionDescriptor) {
fun serializeKotlinType(type: KotlinType): KonanIr.KotlinType {
val isCaptured = type.isCaptured()
val typeToSerialize = if (isCaptured) {
packCapturedType(type as CapturedType)
} else {
type
}
val index = localDeclarationSerializer.typeSerializer(typeToSerialize)
val proto = KonanIr.KotlinType.newBuilder()
.setIndex(index)
.setDebugText(type.toString())
.setIsCaptured(isCaptured)
.build()
return proto
}
fun kotlinDescriptorKind(descriptor: DeclarationDescriptor) =
when (descriptor) {
is ConstructorDescriptor
-> KonanIr.KotlinDescriptor.Kind.CONSTRUCTOR
is PropertyAccessorDescriptor
-> KonanIr.KotlinDescriptor.Kind.ACCESSOR
is FunctionDescriptor
-> KonanIr.KotlinDescriptor.Kind.FUNCTION
is ClassDescriptor
-> KonanIr.KotlinDescriptor.Kind.CLASS
is ValueParameterDescriptor
-> KonanIr.KotlinDescriptor.Kind.VALUE_PARAMETER
is LocalVariableDescriptor,
is IrTemporaryVariableDescriptor
-> KonanIr.KotlinDescriptor.Kind.VARIABLE
is TypeParameterDescriptor
-> KonanIr.KotlinDescriptor.Kind.TYPE_PARAMETER
is ReceiverParameterDescriptor
-> KonanIr.KotlinDescriptor.Kind.RECEIVER
is PropertyDescriptor
-> KonanIr.KotlinDescriptor.Kind.PROPERTY
else -> TODO("Unexpected local descriptor: $descriptor")
}
fun functionDescriptorSpecifics(descriptor: FunctionDescriptor, proto: KonanIr.KotlinDescriptor.Builder) {
val typeParameters = descriptor.propertyIfAccessor.typeParameters
typeParameters.forEach {
proto.addTypeParameter(serializeDescriptor(it))
// We explicitly serialize type parameters as types here so that
// they are interned in the natural order of declaration.
// Otherwise they appear in the order of appearence in the body
// of the function, and get wrong indices.
localDeclarationSerializer.typeSerializer(it.defaultType)
}
descriptor.valueParameters.forEach {
proto.addValueParameter(serializeDescriptor(it))
}
// Allocate two indicies for the receivers. They are not deserialized
// from protobuf, just recreated together with their function.
val dispatchReceiver = descriptor.dispatchReceiverParameter
if (dispatchReceiver != null)
proto.setDispatchReceiverIndex(
descriptorTable.indexByValue(dispatchReceiver))
val extensionReceiver = descriptor.extensionReceiverParameter
if (extensionReceiver != null) {
proto.setExtensionReceiverIndex(
descriptorTable.indexByValue(extensionReceiver))
proto.setExtensionReceiverType(
serializeKotlinType(extensionReceiver.type))
}
proto.setType(serializeKotlinType(
descriptor.returnType!!))
}
fun variableDescriptorSpecifics(descriptor: VariableDescriptor, proto: KonanIr.KotlinDescriptor.Builder) {
proto.setType(serializeKotlinType(descriptor.type))
}
fun serializeDescriptor(descriptor: DeclarationDescriptor): KonanIr.KotlinDescriptor {
if (descriptor is CallableMemberDescriptor &&
descriptor.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
// TODO: It seems rather braindead.
// Do we need to do anything more than that?
return serializeDescriptor(DescriptorUtils.unwrapFakeOverride(descriptor))
}
val classOrPackage = descriptor.classOrPackage
val parentFqNameIndex = if (classOrPackage is ClassOrPackageFragmentDescriptor) {
stringTable.getClassOrPackageFqNameIndex(classOrPackage)
} else null
val index = descriptorTable.indexByValue(descriptor)
// For getters and setters we use the *property* original index.
val originalIndex = descriptorTable.indexByValue(descriptor.propertyIfAccessor.original)
context.log{"index = $index"}
context.log{"originalIndex = $originalIndex"}
context.log{""}
val proto = KonanIr.KotlinDescriptor.newBuilder()
.setName(descriptor.name.asString())
.setKind(kotlinDescriptorKind(descriptor))
.setIndex(index)
.setOriginalIndex(originalIndex)
if (parentFqNameIndex != null)
proto.setClassOrPackage(parentFqNameIndex)
when (descriptor) {
is FunctionDescriptor ->
functionDescriptorSpecifics(descriptor, proto)
is VariableDescriptor ->
variableDescriptorSpecifics(descriptor, proto)
}
return proto.build()
}
}
| apache-2.0 | 04c9baa652a02c10db0060e9e68ad3cb | 39.171598 | 110 | 0.688614 | 5.546569 | false | false | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/ModuleOperationExecutor.kt | 1 | 8966 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations
import com.intellij.buildsystem.model.OperationFailure
import com.intellij.buildsystem.model.unified.UnifiedCoordinates
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.application.readAction
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.logWarn
import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal class ModuleOperationExecutor {
/** This **MUST** run on EDT */
suspend fun doOperation(operation: PackageSearchOperation<*>) = try {
when (operation) {
is PackageSearchOperation.Package.Install -> installPackage(operation)
is PackageSearchOperation.Package.Remove -> removePackage(operation)
is PackageSearchOperation.Package.ChangeInstalled -> changePackage(operation)
is PackageSearchOperation.Repository.Install -> installRepository(operation)
is PackageSearchOperation.Repository.Remove -> removeRepository(operation)
}
null
} catch (e: OperationException) {
logWarn("ModuleOperationExecutor#doOperation()", e) { "Failure while performing operation $operation" }
PackageSearchOperationFailure(operation, e)
}
private suspend fun installPackage(operation: PackageSearchOperation.Package.Install) {
val projectModule = operation.projectModule
val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType)
?: throw OperationException.unsupportedBuildSystem(projectModule)
logDebug("ModuleOperationExecutor#installPackage()") { "Installing package ${operation.model.displayName} in ${projectModule.name}" }
val operationMetadata = dependencyOperationMetadataFrom(
projectModule = projectModule,
dependency = operation.model,
newVersion = operation.newVersion,
newScope = operation.newScope
)
withEDT { operationProvider.addDependencyToModule(operationMetadata, projectModule).throwIfAnyFailures() }
PackageSearchEventsLogger.logPackageInstalled(
packageIdentifier = operation.model.coordinates.toIdentifier(),
packageVersion = operation.newVersion,
targetModule = operation.projectModule
)
logTrace("ModuleOperationExecutor#installPackage()") { "Package ${operation.model.displayName} installed in ${projectModule.name}" }
}
private fun UnifiedCoordinates.toIdentifier() = PackageIdentifier("$groupId:$artifactId")
private suspend fun removePackage(operation: PackageSearchOperation.Package.Remove) {
val projectModule = operation.projectModule
val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType)
?: throw OperationException.unsupportedBuildSystem(projectModule)
logDebug("ModuleOperationExecutor#removePackage()") { "Removing package ${operation.model.displayName} from ${projectModule.name}" }
val operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model)
withEDT { operationProvider.removeDependencyFromModule(operationMetadata, projectModule).throwIfAnyFailures() }
PackageSearchEventsLogger.logPackageRemoved(
packageIdentifier = operation.model.coordinates.toIdentifier(),
packageVersion = operation.currentVersion,
targetModule = operation.projectModule
)
logTrace("ModuleOperationExecutor#removePackage()") { "Package ${operation.model.displayName} removed from ${projectModule.name}" }
}
private suspend fun changePackage(operation: PackageSearchOperation.Package.ChangeInstalled) {
val projectModule = operation.projectModule
val operationProvider = readAction {
ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType)
?: throw OperationException.unsupportedBuildSystem(projectModule)
}
logDebug("ModuleOperationExecutor#changePackage()") { "Changing package ${operation.model.displayName} in ${projectModule.name}" }
val operationMetadata = dependencyOperationMetadataFrom(
projectModule = projectModule,
dependency = operation.model,
newVersion = operation.newVersion,
newScope = operation.newScope
)
withEDT { operationProvider.updateDependencyInModule(operationMetadata, projectModule).throwIfAnyFailures() }
PackageSearchEventsLogger.logPackageUpdated(
packageIdentifier = operation.model.coordinates.toIdentifier(),
packageFromVersion = operation.currentVersion,
packageVersion = operation.newVersion,
targetModule = operation.projectModule
)
logTrace("ModuleOperationExecutor#changePackage()") { "Package ${operation.model.displayName} changed in ${projectModule.name}" }
}
private fun dependencyOperationMetadataFrom(
projectModule: ProjectModule,
dependency: UnifiedDependency,
newVersion: PackageVersion? = null,
newScope: PackageScope? = null
) = DependencyOperationMetadata(
module = projectModule,
groupId = dependency.coordinates.groupId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency),
artifactId = dependency.coordinates.artifactId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency),
currentVersion = dependency.coordinates.version.nullIfBlank(),
currentScope = dependency.scope.nullIfBlank(),
newVersion = newVersion?.versionName.nullIfBlank() ?: dependency.coordinates.version.nullIfBlank(),
newScope = newScope?.scopeName.nullIfBlank() ?: dependency.scope.nullIfBlank()
)
private suspend fun installRepository(operation: PackageSearchOperation.Repository.Install) {
val projectModule = operation.projectModule
val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType)
?: throw OperationException.unsupportedBuildSystem(projectModule)
logDebug("ModuleOperationExecutor#installRepository()") { "Installing repository ${operation.model.displayName} in ${projectModule.name}" }
withEDT { operationProvider.addRepositoryToModule(operation.model, projectModule).throwIfAnyFailures() }
PackageSearchEventsLogger.logRepositoryAdded(operation.model)
logTrace("ModuleOperationExecutor#installRepository()") { "Repository ${operation.model.displayName} installed in ${projectModule.name}" }
}
private suspend fun removeRepository(operation: PackageSearchOperation.Repository.Remove) {
val projectModule = operation.projectModule
val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType)
?: throw OperationException.unsupportedBuildSystem(projectModule)
logDebug("ModuleOperationExecutor#removeRepository()") { "Removing repository ${operation.model.displayName} from ${projectModule.name}" }
withEDT { operationProvider.removeRepositoryFromModule(operation.model, projectModule).throwIfAnyFailures() }
PackageSearchEventsLogger.logRepositoryRemoved(operation.model)
logTrace("ModuleOperationExecutor#removeRepository()") { "Repository ${operation.model.displayName} removed from ${projectModule.name}" }
}
private fun List<OperationFailure<*>>.throwIfAnyFailures() {
when {
isEmpty() -> return
size > 1 -> error("A single operation resulted in multiple failures")
}
}
private suspend inline fun <T> withEDT(noinline action: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.EDT + ModalityState.defaultModalityState().asContextElement(), action)
}
| apache-2.0 | c8be1b824fbc4c0250d8f14ef22aaf7f | 53.670732 | 147 | 0.75619 | 6.187716 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleStateService.kt | 13 | 2366 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.console
import com.intellij.openapi.components.*
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModulePointer
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.plugins.groovy.console.GroovyConsoleStateService.MyState
import java.util.*
@State(name = "GroovyConsoleState", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
internal class GroovyConsoleStateService(private val project: Project) : PersistentStateComponent<MyState> {
private val fileModuleMap: MutableMap<VirtualFile, ModulePointer?> = Collections.synchronizedMap(HashMap())
class Entry {
var url: String? = null
var moduleName: String? = null
}
class MyState {
var list: MutableCollection<Entry> = ArrayList()
}
override fun getState(): MyState {
synchronized(fileModuleMap) {
val result = MyState()
for ((file, pointer) in fileModuleMap) {
val e = Entry()
e.url = file.url
e.moduleName = pointer?.moduleName
result.list.add(e)
}
return result
}
}
override fun loadState(state: MyState) {
val virtualFileManager = VirtualFileManager.getInstance()
val modulePointerManager = ModulePointerManager.getInstance(project)
synchronized(fileModuleMap) {
fileModuleMap.clear()
for (entry in state.list) {
val url = entry.url ?: continue
val file = virtualFileManager.findFileByUrl(url) ?: continue
val pointer = entry.moduleName?.let(modulePointerManager::create)
fileModuleMap[file] = pointer
}
}
}
fun isProjectConsole(file: VirtualFile): Boolean {
return fileModuleMap.containsKey(file)
}
fun getSelectedModule(file: VirtualFile): Module? = fileModuleMap[file]?.module
fun setFileModule(file: VirtualFile, module: Module?) {
fileModuleMap[file] = module?.let(ModulePointerManager.getInstance(project)::create)
}
companion object {
@JvmStatic
fun getInstance(project: Project): GroovyConsoleStateService = project.service()
}
}
| apache-2.0 | 54f6a876f18a0eab0f424c3ce24b47db | 33.794118 | 140 | 0.733728 | 4.405959 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/ACTIONS_DOWNLOAD_META_MODEL.kt | 2 | 2735 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object ACTIONS_DOWNLOAD_META_MODEL : Response() {
override val url = "http://localhost:8080/restful/services/causewayApplib.LayoutServiceMenu/actions/downloadLayouts"
override val str = """{
"id" : "downloadMetaModel",
"memberType" : "action",
"links" : [ {
"rel" : "self",
"href" : "http://localhost:8080/restful/services/causewayApplib.MetaModelServicesMenu/actions/downloadMetaModel",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
}, {
"rel" : "up",
"href" : "http://localhost:8080/restful/services/causewayApplib.MetaModelServicesMenu",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object\"",
"title" : "Prototyping"
}, {
"rel" : "urn:org.restfulobjects:rels/invoke;action=\"downloadMetaModel\"",
"href" : "http://localhost:8080/restful/services/causewayApplib.MetaModelServicesMenu/actions/downloadMetaModel/invoke",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"",
"arguments" : {
"" : {
"csvFileName" : {
"value" : null
}
}
}
}, {
"rel" : "describedby",
"href" : "http://localhost:8080/restful/domain-types/causewayApplib.MetaModelServicesMenu/actions/downloadMetaModel",
"method" : "GET",
"type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
} ],
"extensions" : {
"actionType" : "prototype",
"actionSemantics" : "safe"
},
"parameters" : {
".csvFileName" : {
"num" : 0,
"id" : ".csvFileName",
"name" : ".csv file name",
"description" : "",
"default" : "metamodel.csv"
}
}
}"""
}
| apache-2.0 | 71de6f72dd6aaa512c4734d60046983c | 37.521127 | 124 | 0.670567 | 3.736339 | false | false | false | false |
boxtape/boxtape-cli | boxtape-cli/src/main/java/io/boxtape/cli/commands/VagrantUpCommand.kt | 1 | 1940 | package io.boxtape.cli.commands
import io.boxtape.cli.core.Project
import org.apache.commons.exec.CommandLine
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
/**
* Starts and provisions a vagrant box.
* Defers to the Ansible command to build the playbooks,
* then installs requirements.yaml, and finally provisions the vagrant box.
*/
Component
public class VagrantUpCommand @Autowired constructor(
private val ansible: AnsibleCommand
) : ShellCommand {
override fun name(): String = "up"
override fun run(project: Project) {
writeVagrantFile(project)
// The ansible task may change the vagrant settings,
// so needs to run first
ansible.run(project)
project.writeVagrantSettings()
project.writeConfigurationFile()
project.run("ansible-galaxy install -f -r .boxtape/requirements.yml")
val result = project.run("vagrant up")
if (result.containedMessage("VirtualBox VM is already running.")) {
project.console.info("Vagrant box is already running, provisioning instead")
project.run("vagrant provision")
}
}
private fun discoverGuestIp(project: Project): String {
// http://stackoverflow.com/questions/14870900/how-to-find-vagrant-ip
val sshString = "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\\/.*$//'"
// todo : write an error log
val cmd = CommandLine("vagrant").addArgument("ssh").addArgument("-c").addArgument(sshString,false)
val result = project.run(cmd)
result.assertSuccessful("Unable to determine ip address of guest -- check error log for more details")
val ip = result.stdOut().last()
return ip;
}
private fun writeVagrantFile(project: Project) {
project.write("Vagrantfile", project.settings.getDefaultVagrantFile())
}
}
| apache-2.0 | 6530af6de9b7d1916806c8f08a542965 | 35.603774 | 110 | 0.684021 | 4.199134 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/toolbars/SearchToolbar.kt | 1 | 1606 | package com.kickstarter.ui.toolbars
import android.content.Context
import android.util.AttributeSet
import android.widget.EditText
import com.jakewharton.rxbinding.widget.RxTextView
import com.kickstarter.R
import com.kickstarter.ui.activities.SearchActivity
import com.kickstarter.ui.views.IconButton
import rx.android.schedulers.AndroidSchedulers
class SearchToolbar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : KSToolbar(context, attrs, defStyleAttr) {
private val clearButton by lazy { findViewById<IconButton>(R.id.clear_button) }
private val searchEditText by lazy { findViewById<EditText>(R.id.search_edit_text) }
override fun onFinishInflate() {
super.onFinishInflate()
if (isInEditMode) {
return
}
clearButton.setOnClickListener {
clearButtonClick()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val text = RxTextView.textChanges(searchEditText)
val clearable = text.map { it.isNotEmpty() }
addSubscription(
clearable
.observeOn(AndroidSchedulers.mainThread())
.subscribe { clearButton.visibility = if (it) VISIBLE else INVISIBLE }
)
addSubscription(
text
.observeOn(AndroidSchedulers.mainThread())
.subscribe { (context as SearchActivity).viewModel().inputs.search(it.toString()) }
)
}
private fun clearButtonClick() {
searchEditText.text = null
}
}
| apache-2.0 | 0cc9ba7be98bf941b7444cdee19ff75c | 28.740741 | 99 | 0.669988 | 5.034483 | false | false | false | false |
MilosKozak/AndroidAPS | app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt | 3 | 4843 | package info.nightscout.androidaps
import android.os.SystemClock
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.rule.GrantPermissionRule
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.PumpInterface
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin
import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.source.RandomBgPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.isRunningTest
import org.json.JSONObject
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.slf4j.LoggerFactory
@LargeTest
@RunWith(AndroidJUnit4::class)
class RealPumpTest {
private val log = LoggerFactory.getLogger(L.CORE)
companion object {
val pump: PumpInterface = DanaRv2Plugin.getPlugin()
const val R_PASSWORD = 1234
const val R_SERIAL = "PBB00013LR_P"
}
private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}"
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Rule
@JvmField
var mGrantPermissionRule: GrantPermissionRule =
GrantPermissionRule.grant(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
)
@Before
fun clear() {
SP.clear()
SP.putBoolean(R.string.key_setupwizard_processed, true)
SP.putString(R.string.key_aps_mode, "closed")
MainApp.getDbHelper().resetDatabases()
MainApp.devBranch = false
}
private fun preparePlugins() {
// Source
RandomBgPlugin.performPluginSwitch(true, PluginType.BGSOURCE)
// Profile
LocalProfilePlugin.performPluginSwitch(true, PluginType.PROFILE)
val profile = Profile(JSONObject(validProfile), Constants.MGDL)
Assert.assertTrue(profile.isValid("Test"))
LocalProfilePlugin.profiles.clear()
LocalProfilePlugin.numOfProfiles = 0
val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(profile, "TestProfile")
LocalProfilePlugin.addProfile(singleProfile)
ProfileFunctions.doProfileSwitch(LocalProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, DateUtil.now())
// Insulin
InsulinOrefUltraRapidActingPlugin.getPlugin().performPluginSwitch(true, PluginType.INSULIN)
// Pump
SP.putInt(R.string.key_danar_password, R_PASSWORD)
SP.putString(R.string.key_danar_bt_name, R_SERIAL)
(pump as PluginBase).performPluginSwitch(true, PluginType.PUMP)
// Sensitivity
SensitivityOref1Plugin.getPlugin().performPluginSwitch(true, PluginType.SENSITIVITY)
// APS
OpenAPSSMBPlugin.getPlugin().performPluginSwitch(true, PluginType.APS)
LoopPlugin.getPlugin().performPluginSwitch(true, PluginType.LOOP)
// Enable common
ActionsPlugin.performPluginSwitch(true, PluginType.GENERAL)
// Disable unneeded
MainApp.getPluginsList().remove(ObjectivesPlugin)
}
@Test
fun doTest() {
Assert.assertTrue(isRunningTest())
preparePlugins()
while (!pump.isInitialized) {
log.debug("Waiting for initialization")
SystemClock.sleep(1000)
}
while (true) {
log.debug("Tick")
SystemClock.sleep(1000)
}
}
} | agpl-3.0 | 6496b068a92b305ce67cd7ae92082212 | 40.758621 | 468 | 0.717117 | 4.382805 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/CoroutineNoLibraryProxy.kt | 1 | 4226 | // 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.debugger.coroutine.proxy
import com.intellij.openapi.util.registry.Registry
import com.sun.jdi.Field
import com.sun.jdi.ObjectReference
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.CancellableContinuationImpl
import org.jetbrains.kotlin.idea.debugger.coroutine.util.findCancellableContinuationImplReferenceType
import org.jetbrains.kotlin.idea.debugger.coroutine.util.findCoroutineMetadataType
import org.jetbrains.kotlin.idea.debugger.coroutine.util.findDispatchedContinuationReferenceType
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext
class CoroutineNoLibraryProxy(private val executionContext: DefaultExecutionContext) : CoroutineInfoProvider {
private val log by logger
private val debugMetadataKtType = executionContext.findCoroutineMetadataType()
private val holder = ContinuationHolder.instance(executionContext)
override fun dumpCoroutinesInfo(): List<CoroutineInfoData> {
val vm = executionContext.vm
val resultList = mutableListOf<CoroutineInfoData>()
if (vm.virtualMachine.canGetInstanceInfo()) {
when (coroutineSwitch()) {
"DISPATCHED_CONTINUATION" -> dispatchedContinuation(resultList)
"CANCELLABLE_CONTINUATION" -> cancellableContinuation(resultList)
else -> dispatchedContinuation(resultList)
}
} else
log.warn("Remote JVM doesn't support canGetInstanceInfo capability (perhaps JDK-8197943).")
return resultList
}
private fun cancellableContinuation(resultList: MutableList<CoroutineInfoData>): Boolean {
val dcClassTypeList = executionContext.findCancellableContinuationImplReferenceType()
if (dcClassTypeList?.size == 1) {
val dcClassType = dcClassTypeList.first()
val cci = CancellableContinuationImpl(executionContext)
val continuationList = dcClassType.instances(maxCoroutines())
for (cancellableContinuation in continuationList) {
val coroutineInfo = extractCancellableContinuation(cancellableContinuation, cci) ?: continue
resultList.add(coroutineInfo)
}
}
return false
}
private fun extractCancellableContinuation(
dispatchedContinuation: ObjectReference,
ccMirrorProvider: CancellableContinuationImpl
): CoroutineInfoData? {
val mirror = ccMirrorProvider.mirror(dispatchedContinuation, executionContext) ?: return null
val continuation = mirror.delegate?.continuation ?: return null
return holder.extractCoroutineInfoData(continuation)
}
private fun dispatchedContinuation(resultList: MutableList<CoroutineInfoData>): Boolean {
val dcClassTypeList = executionContext.findDispatchedContinuationReferenceType()
if (dcClassTypeList?.size == 1) {
val dcClassType = dcClassTypeList.first()
val continuationField = dcClassType.fieldByName("continuation") ?: return true
val continuationList = dcClassType.instances(maxCoroutines())
for (dispatchedContinuation in continuationList) {
val coroutineInfo = extractDispatchedContinuation(dispatchedContinuation, continuationField) ?: continue
resultList.add(coroutineInfo)
}
}
return false
}
private fun extractDispatchedContinuation(dispatchedContinuation: ObjectReference, continuation: Field): CoroutineInfoData? {
debugMetadataKtType ?: return null
val initialContinuation = dispatchedContinuation.getValue(continuation) as ObjectReference
return holder.extractCoroutineInfoData(initialContinuation)
}
}
fun maxCoroutines() = Registry.intValue("kotlin.debugger.coroutines.max", 1000).toLong()
fun coroutineSwitch() = Registry.stringValue("kotlin.debugger.coroutines.switch")
| apache-2.0 | 41d01f6d7f1d4efe537bd371584dffbf | 50.536585 | 158 | 0.744439 | 5.495449 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameUnresolvedReferenceFix.kt | 3 | 6534 | // 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.quickfix
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper
import org.jetbrains.kotlin.idea.core.NotPropertiesService
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.guessTypes
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.psi.patternMatching.match
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.utils.ifEmpty
import java.util.*
import kotlin.math.min
object RenameUnresolvedReferenceActionFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val ref = diagnostic.psiElement as? KtNameReferenceExpression ?: return null
return RenameUnresolvedReferenceFix(ref)
}
}
class RenameUnresolvedReferenceFix(element: KtNameReferenceExpression) : KotlinQuickFixAction<KtNameReferenceExpression>(element) {
companion object {
private val INPUT_VARIABLE_NAME = "INPUT_VAR"
private val OTHER_VARIABLE_NAME = "OTHER_VAR"
}
private class ReferenceNameExpression(
private val items: Array<out LookupElement>,
private val originalReferenceName: String
) : Expression() {
init {
Arrays.sort(items, HammingComparator(originalReferenceName) { lookupString })
}
override fun calculateResult(context: ExpressionContext) = TextResult(items.firstOrNull()?.lookupString ?: originalReferenceName)
override fun calculateQuickResult(context: ExpressionContext) = null
override fun calculateLookupItems(context: ExpressionContext) = if (items.size <= 1) null else items
}
override fun getText() = QuickFixBundle.message("rename.wrong.reference.text")
override fun getFamilyName() = QuickFixBundle.message("rename.wrong.reference.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = element ?: return false
return editor != null && element.getStrictParentOfType<KtTypeReference>() == null
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
if (editor == null) return
val patternExpression = element.getQualifiedElement() as? KtExpression ?: return
val originalName = element.getReferencedName()
val container = element.parents.firstOrNull { it is KtDeclarationWithBody || it is KtClassOrObject || it is KtFile } ?: return
val isCallee = element.isCallee()
val occurrences = patternExpression.toRange()
.match(container, KotlinPsiUnifier.DEFAULT)
.mapNotNull {
val candidate = (it.range.elements.first() as? KtExpression)?.getQualifiedElementSelector() as? KtNameReferenceExpression
if (candidate != null && candidate.isCallee() == isCallee) candidate else null
}
val resolutionFacade = element.getResolutionFacade()
val context = resolutionFacade.analyze(element, BodyResolveMode.PARTIAL_WITH_CFA)
val moduleDescriptor = resolutionFacade.moduleDescriptor
val variantsHelper = ReferenceVariantsHelper(context, resolutionFacade, moduleDescriptor, {
it !is DeclarationDescriptorWithVisibility || it.isVisible(element, null, context, resolutionFacade)
}, NotPropertiesService.getNotProperties(element))
val expectedTypes = patternExpression.guessTypes(context, moduleDescriptor)
.ifEmpty { arrayOf(moduleDescriptor.builtIns.nullableAnyType) }
val descriptorKindFilter = if (isCallee) DescriptorKindFilter.FUNCTIONS else DescriptorKindFilter.VARIABLES
val lookupItems = variantsHelper.getReferenceVariants(element, descriptorKindFilter, { true })
.filter { candidate ->
candidate is CallableDescriptor && (expectedTypes.any { candidate.returnType?.isSubtypeOf(it) ?: false })
}
.mapTo(if (isUnitTestMode()) linkedSetOf() else linkedSetOf(originalName)) {
it.name.asString()
}
.map { LookupElementBuilder.create(it) }
.toTypedArray()
val nameExpression = ReferenceNameExpression(lookupItems, originalName)
val builder = TemplateBuilderImpl(container)
occurrences.forEach {
if (it != element) {
builder.replaceElement(it.getReferencedNameElement(), OTHER_VARIABLE_NAME, INPUT_VARIABLE_NAME, false)
} else {
builder.replaceElement(it.getReferencedNameElement(), INPUT_VARIABLE_NAME, nameExpression, true)
}
}
editor.caretModel.moveToOffset(container.startOffset)
if (file.isPhysical) {
TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate())
}
}
}
private class HammingComparator<T>(private val referenceString: String, private val asString: T.() -> String) : Comparator<T> {
private fun countDifference(s1: String): Int {
return (0..min(s1.lastIndex, referenceString.lastIndex)).count { s1[it] != referenceString[it] }
}
override fun compare(lookupItem1: T, lookupItem2: T): Int {
return countDifference(lookupItem1.asString()) - countDifference(lookupItem2.asString())
}
}
| apache-2.0 | d12a491193e63eb8ac1b8b98b7b90dd3 | 49.651163 | 158 | 0.736609 | 5.092751 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/search/LocalStorageSessionsSearchSource.kt | 1 | 953 | package de.droidcon.berlin2018.search
import de.droidcon.berlin2018.schedule.repository.SessionsRepository
import de.droidcon.berlin2018.ui.sessions.shortTime
import de.droidcon.berlin2018.ui.sessions.speakerNames
import io.reactivex.Observable
import org.threeten.bp.ZoneId
/**
* Searches the local database for Sessions
*
* @author Hannes Dorfmann
*/
class LocalStorageSessionsSearchSource(
private val sessionsRepository: SessionsRepository,
private val zoneConferenceTakesPlace: ZoneId) : SearchSource {
override fun search(
query: String): Observable<List<SearchableItem>> =
sessionsRepository.findSessionsWith(query)
.map { it.map { SessionSearchableItem(
session = it,
speakers = it.speakers().speakerNames(),
time = it.shortTime(zoneConferenceTakesPlace, true),
location = it.locationName(),
favorite = it.favorite()
) } }
}
| apache-2.0 | 54d5af58e0f937fc08d35ccf140378ff | 31.862069 | 68 | 0.709339 | 4.581731 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardInteractions.kt | 2 | 2759 | // 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.ide.customize
import com.intellij.ide.ApplicationInitializedListener
import com.intellij.internal.statistic.FeaturedPluginsInfoProvider
import com.intellij.internal.statistic.utils.getPluginInfoByDescriptorWithFeaturedPlugins
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.atomic.AtomicReference
object CustomizeIDEWizardInteractions {
/**
* Featured plugins group which are suggested in IDE Customization Wizard.
*/
val featuredPluginGroups = AtomicReference<Set<PluginId>>()
var skippedOnPage = -1
val interactions = mutableListOf<CustomizeIDEWizardInteraction>()
@JvmOverloads
fun record(type: CustomizeIDEWizardInteractionType, pluginDescriptor: PluginDescriptor? = null, groupId: String? = null) {
interactions.add(CustomizeIDEWizardInteraction(type, System.currentTimeMillis(), pluginDescriptor, groupId))
}
}
enum class CustomizeIDEWizardInteractionType {
WizardDisplayed,
UIThemeChanged,
DesktopEntryCreated,
LauncherScriptCreated,
BundledPluginGroupDisabled,
BundledPluginGroupEnabled,
BundledPluginGroupCustomized,
FeaturedPluginInstalled
}
data class CustomizeIDEWizardInteraction(
val type: CustomizeIDEWizardInteractionType,
val timestamp: Long,
val pluginDescriptor: PluginDescriptor?,
val groupId: String?
)
internal class CustomizeIDEWizardCollectorActivity : ApplicationInitializedListener {
override fun componentsInitialized() {
if (CustomizeIDEWizardInteractions.interactions.isEmpty()) {
return
}
ForkJoinPool.commonPool().execute {
if (CustomizeIDEWizardInteractions.skippedOnPage != -1) {
CustomizeWizardCollector.logRemainingPagesSkipped(CustomizeIDEWizardInteractions.skippedOnPage)
}
val featuredPluginsProvider = CustomizeIDEWizardFeaturedPluginsProvider(CustomizeIDEWizardInteractions.featuredPluginGroups.get())
for (interaction in CustomizeIDEWizardInteractions.interactions) {
val pluginInfo = if (interaction.pluginDescriptor != null)
getPluginInfoByDescriptorWithFeaturedPlugins(interaction.pluginDescriptor, featuredPluginsProvider)
else
null
CustomizeWizardCollector.logEvent(interaction.type, interaction.timestamp, pluginInfo, interaction.groupId)
}
}
}
}
private class CustomizeIDEWizardFeaturedPluginsProvider(private val pluginGroups: Set<PluginId>) : FeaturedPluginsInfoProvider {
override fun getFeaturedPluginsFromMarketplace(): Set<PluginId> = pluginGroups
} | apache-2.0 | b378786ebb3ea3628fd5672c3092d438 | 37.873239 | 140 | 0.805364 | 5.053114 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt | 4 | 1847 | // 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.resolve.scopes
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class ExplicitImportsScope(private val descriptors: Collection<DeclarationDescriptor>) : BaseImportingScope(null) {
override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? {
return descriptors.filter { it.name == name }.firstIsInstanceOrNull<ClassifierDescriptor>()
}
override fun getContributedPackage(name: Name): PackageViewDescriptor? {
return descriptors.filter { it.name == name }.firstIsInstanceOrNull<PackageViewDescriptor>()
}
override fun getContributedVariables(name: Name, location: LookupLocation): List<VariableDescriptor> {
return descriptors.filter { it.name == name }.filterIsInstance<VariableDescriptor>()
}
override fun getContributedFunctions(name: Name, location: LookupLocation): List<FunctionDescriptor> {
return descriptors.filter { it.name == name }.filterIsInstance<FunctionDescriptor>()
}
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
changeNamesForAliased: Boolean
): Collection<DeclarationDescriptor> {
return descriptors
}
override fun computeImportedNames(): HashSet<Name> {
return descriptors.mapTo(hashSetOf()) { it.name }
}
override fun printStructure(p: Printer) {
p.println(this::class.java.name)
}
}
| apache-2.0 | 9a73e0a9902b670b595ab18e2c99299c | 41.953488 | 158 | 0.749323 | 5.088154 | false | false | false | false |
jwren/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/importing/MavenImportFlow.kt | 1 | 17580 | // 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.idea.maven.project.importing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.ExternalStorageConfigurationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.exists
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.idea.maven.execution.BTWMavenConsole
import org.jetbrains.idea.maven.importing.MavenProjectImporter
import org.jetbrains.idea.maven.importing.MavenProjectImporterBase
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenExplicitProfiles
import org.jetbrains.idea.maven.model.MavenPlugin
import org.jetbrains.idea.maven.project.*
import org.jetbrains.idea.maven.project.actions.LookForNestedToggleAction
import org.jetbrains.idea.maven.server.MavenWrapperDownloader
import org.jetbrains.idea.maven.server.MavenWrapperSupport
import org.jetbrains.idea.maven.server.NativeMavenProjectHolder
import org.jetbrains.idea.maven.utils.FileFinder
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenProgressIndicator
import org.jetbrains.idea.maven.utils.MavenUtil
import java.io.IOException
import java.util.*
@IntellijInternalApi
@ApiStatus.Internal
@ApiStatus.Experimental
class MavenImportFlow {
val dispatcher = AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher()
fun prepareNewImport(project: Project,
importPaths: ImportPaths,
generalSettings: MavenGeneralSettings,
importingSettings: MavenImportingSettings,
enabledProfiles: Collection<String>,
disabledProfiles: Collection<String>): MavenInitialImportContext {
val isVeryNewProject = project.getUserData<Boolean>(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == true
&& ModuleManager.getInstance(project).modules.size == 0;
if (isVeryNewProject) {
ExternalStorageConfigurationManager.getInstance(project).isEnabled = true
}
val dummyModule = if (isVeryNewProject) createDummyModule(importPaths, project) else null
val manager = MavenProjectsManager.getInstance(project)
val profiles = MavenExplicitProfiles(enabledProfiles, disabledProfiles)
val ignorePaths = manager.ignoredFilesPaths
val ignorePatterns = manager.ignoredFilesPatterns
return MavenInitialImportContext(project, importPaths, profiles, generalSettings, importingSettings, ignorePaths, ignorePatterns,
dummyModule)
}
private fun createDummyModule(importPaths: ImportPaths, project: Project): Module? {
if (Registry.`is`("maven.create.dummy.module.on.first.import")) {
val contentRoot = when (importPaths) {
is FilesList -> ContainerUtil.getFirstItem(importPaths.poms).parent
is RootPath -> importPaths.path
}
return MavenImportUtil.createDummyModule(project, contentRoot)
}
return null
}
fun readMavenFiles(context: MavenInitialImportContext, indicator: MavenProgressIndicator): MavenReadContext {
val projectManager = MavenProjectsManager.getInstance(context.project)
ApplicationManager.getApplication().assertIsNonDispatchThread()
val ignorePaths: List<String> = context.ignorePaths
val ignorePatterns: List<String> = context.ignorePatterns
val projectsTree = loadOrCreateProjectTree(projectManager)
MavenProjectsManager.applyStateToTree(projectsTree, projectManager)
val rootFiles = MavenProjectsManager.getInstance(context.project).projectsTree?.rootProjectsFiles
val pomFiles = LinkedHashSet<VirtualFile>()
rootFiles?.let { pomFiles.addAll(it.filterNotNull()) }
val newPomFiles = when (context.paths) {
is FilesList -> context.paths.poms
is RootPath -> searchForMavenFiles(context.paths.path, context.indicator)
}
pomFiles.addAll(newPomFiles.filterNotNull())
projectsTree.addManagedFilesWithProfiles(pomFiles.toList(), context.profiles)
val toResolve = LinkedHashSet<MavenProject>()
val errorsSet = LinkedHashSet<MavenProject>()
val d = Disposer.newDisposable("MavenImportFlow:readMavenFiles:treeListener")
Disposer.register(projectManager, d)
projectsTree.addListener(object : MavenProjectsTree.Listener {
override fun projectsUpdated(updated: MutableList<Pair<MavenProject, MavenProjectChanges>>, deleted: MutableList<MavenProject>) {
val allUpdated = MavenUtil.collectFirsts(
updated) // import only updated projects and dependents of them (we need to update faced-deps, packaging etc);
toResolve.addAll(allUpdated)
for (eachDependent in projectsTree.getDependentProjects(allUpdated)) {
toResolve.add(eachDependent)
}
// resolve updated, theirs dependents, and dependents of deleted
toResolve.addAll(projectsTree.getDependentProjects(ContainerUtil.concat(allUpdated, deleted)))
errorsSet.addAll(toResolve.filter { it.hasReadingProblems() })
toResolve.removeIf { it.hasReadingProblems() }
}
}, d)
if (ignorePaths.isNotEmpty()) {
projectsTree.ignoredFilesPaths = ignorePaths
}
if (ignorePatterns.isNotEmpty()) {
projectsTree.ignoredFilesPatterns = ignorePatterns
}
projectsTree.updateAll(true, context.generalSettings, indicator)
Disposer.dispose(d)
val baseDir = context.project.guessProjectDir()
val wrapperData = MavenWrapperSupport.getWrapperDistributionUrl(baseDir)?.let { WrapperData(it, baseDir!!) }
return MavenReadContext(context.project, projectsTree, toResolve, errorsSet, context, wrapperData, indicator)
}
fun setupMavenWrapper(readContext: MavenReadContext, indicator: MavenProgressIndicator): MavenReadContext {
if (readContext.wrapperData == null) return readContext;
MavenWrapperDownloader.checkOrInstallForSync(readContext.project, readContext.wrapperData.baseDir.path);
return readContext;
}
private fun searchForMavenFiles(path: VirtualFile, indicator: MavenProgressIndicator): MutableList<VirtualFile> {
indicator.setText(MavenProjectBundle.message("maven.locating.files"));
return FileFinder.findPomFiles(path.getChildren(), LookForNestedToggleAction.isSelected(), indicator)
}
private fun loadOrCreateProjectTree(projectManager: MavenProjectsManager): MavenProjectsTree {
val file = projectManager.projectsTreeFile
try {
if (file.exists()) {
return MavenProjectsTree.read(projectManager.project, file) ?: MavenProjectsTree(projectManager.project)
}
}
catch (e: IOException) {
MavenLog.LOG.info(e)
}
return MavenProjectsTree(projectManager.project)
}
fun resolveDependencies(context: MavenReadContext): MavenResolvedContext {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
val resolveContext = ResolveContext()
val d = Disposer.newDisposable("MavenImportFlow:resolveDependencies:treeListener")
Disposer.register(projectManager, d)
val projectsToImport = ArrayList<MavenProject>()
val nativeProjectStorage = ArrayList<kotlin.Pair<MavenProject, NativeMavenProjectHolder>>()
context.projectsTree.addListener(object : MavenProjectsTree.Listener {
override fun projectResolved(projectWithChanges: Pair<MavenProject, MavenProjectChanges>,
nativeMavenProject: NativeMavenProjectHolder?) {
if (nativeMavenProject != null) {
if (shouldScheduleProject(projectWithChanges.first, projectWithChanges.second)) {
projectsToImport.add(projectWithChanges.first)
}
nativeProjectStorage.add(projectWithChanges.first to nativeMavenProject)
}
}
}, d);
resolver.resolve(context.project, context.toResolve, context.initialContext.generalSettings, embeddersManager, consoleToBeRemoved,
resolveContext, context.initialContext.indicator)
Disposer.dispose(d)
return MavenResolvedContext(context.project, resolveContext.getUserData(MavenProjectResolver.UNRESOLVED_ARTIFACTS) ?: emptySet(),
projectsToImport, nativeProjectStorage, context)
}
fun resolvePlugins(context: MavenResolvedContext): MavenPluginResolvedContext {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.readContext.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
val unresolvedPlugins = Collections.synchronizedSet(LinkedHashSet<MavenPlugin>())
context.nativeProjectHolder.foreachParallel {
unresolvedPlugins.addAll(
resolver.resolvePlugins(it.first, it.second, embeddersManager, consoleToBeRemoved, context.initialContext.indicator, false,
projectManager.forceUpdateSnapshots))
}
return MavenPluginResolvedContext(context.project, unresolvedPlugins, context)
}
fun downloadArtifacts(context: MavenResolvedContext, sources: Boolean, javadocs: Boolean): MavenArtifactDownloader.DownloadResult {
assertNonDispatchThread()
if (!(sources || javadocs)) return MavenArtifactDownloader.DownloadResult()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.readContext.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
return resolver.downloadSourcesAndJavadocs(context.project, context.projectsToImport, null, sources, javadocs, embeddersManager,
consoleToBeRemoved, context.initialContext.indicator)
}
fun downloadSpecificArtifacts(project: Project,
mavenProjects: Collection<MavenProject>,
mavenArtifacts: Collection<MavenArtifact>?,
sources: Boolean,
javadocs: Boolean,
indicator: MavenProgressIndicator): MavenArtifactDownloader.DownloadResult {
assertNonDispatchThread()
if (!(sources || javadocs)) return MavenArtifactDownloader.DownloadResult()
val projectManager = MavenProjectsManager.getInstance(project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(projectManager.projectsTree)
val settings = MavenWorkspaceSettingsComponent.getInstance(project).settings.getGeneralSettings()
val consoleToBeRemoved = BTWMavenConsole(project, settings.outputLevel, settings.isPrintErrorStackTraces)
return resolver.downloadSourcesAndJavadocs(project, mavenProjects, mavenArtifacts, sources, javadocs, embeddersManager,
consoleToBeRemoved, indicator)
}
fun resolveFolders(context: MavenResolvedContext): MavenSourcesGeneratedContext {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val resolver = MavenProjectResolver(context.readContext.projectsTree)
val consoleToBeRemoved = BTWMavenConsole(context.project, context.initialContext.generalSettings.outputLevel,
context.initialContext.generalSettings.isPrintErrorStackTraces)
val d = Disposer.newDisposable("MavenImportFlow:resolveFolders:treeListener")
val projectsToImport = Collections.synchronizedSet(LinkedHashSet<MavenProject>(context.projectsToImport))
val projectsFoldersResolved = Collections.synchronizedList(ArrayList<MavenProject>())
Disposer.register(projectManager, d)
context.readContext.projectsTree.addListener(object : MavenProjectsTree.Listener {
override fun foldersResolved(projectWithChanges: Pair<MavenProject, MavenProjectChanges>) {
if (shouldScheduleProject(projectWithChanges.first, projectWithChanges.second)) {
projectsToImport.add(projectWithChanges.first)
}
if (projectWithChanges.second.hasChanges()) {
projectsFoldersResolved.add(projectWithChanges.first)
}
}
}, d)
context.projectsToImport.foreachParallel {
resolver.resolveFolders(it, context.initialContext.importingSettings, embeddersManager, consoleToBeRemoved,
context.initialContext.indicator)
}
Disposer.dispose(d)
return MavenSourcesGeneratedContext(context, projectsFoldersResolved);
}
fun commitToWorkspaceModel(context: MavenResolvedContext): MavenImportedContext {
val modelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(context.project)
assertNonDispatchThread()
val projectImporter = MavenProjectImporter.createImporter(context.project, context.readContext.projectsTree,
context.projectsToImport.map {
it to MavenProjectChanges.ALL
}.toMap(), false, modelsProvider, context.initialContext.importingSettings,
context.initialContext.dummyModule)
val postImportTasks = projectImporter.importProject();
val modulesCreated = projectImporter.createdModules
return MavenImportedContext(context.project, modulesCreated, postImportTasks, context.readContext, context);
}
fun configureMavenProject(context: MavenImportedContext) {
val projectsManager = MavenProjectsManager.getInstance(context.project)
val projects = context.readContext.projectsTree.projects
val moduleMap = ReadAction.compute<Map<MavenProject, Module?>, Throwable> {
projects.map {
it to projectsManager.findModule(it)
}.toMap();
}
MavenProjectImporterBase.configureMavenProjects(context.readContext.projectsTree.projects, moduleMap, context.project,
context.readContext.indicator)
}
fun updateProjectManager(context: MavenReadContext) {
val projectManager = MavenProjectsManager.getInstance(context.project)
projectManager.addManagedFilesWithProfiles(context.projectsTree.projectsFiles, context.initialContext.profiles, null)
projectManager.setProjectsTree(context.projectsTree)
}
fun runImportExtensions(context: MavenImportedContext) {
MavenImportStatusListener.EP_NAME.forEachExtensionSafe {
it.importFinished(context);
}
}
fun runPostImportTasks(context: MavenImportedContext) {
assertNonDispatchThread()
val projectManager = MavenProjectsManager.getInstance(context.project)
val embeddersManager = projectManager.embeddersManager
val consoleToBeRemoved = BTWMavenConsole(context.project, context.readContext.initialContext.generalSettings.outputLevel,
context.readContext.initialContext.generalSettings.isPrintErrorStackTraces)
context.postImportTasks?.forEach {
it.perform(context.project, embeddersManager, consoleToBeRemoved, context.readContext.indicator)
}
}
private fun shouldScheduleProject(project: MavenProject, changes: MavenProjectChanges): Boolean {
return !project.hasReadingProblems() && changes.hasChanges()
}
fun <A> List<A>.foreachParallel(f: suspend (A) -> Unit) = runBlocking {
map { async(dispatcher) { f(it) } }.forEach { it.await() }
}
}
internal fun assertNonDispatchThread() {
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode() && app.isDispatchThread()) {
throw RuntimeException("Access from event dispatch thread is not allowed");
}
ApplicationManager.getApplication().assertIsNonDispatchThread()
}
| apache-2.0 | 5c81ca04e9141dd2add9b339a412fea0 | 50.554252 | 158 | 0.747497 | 5.195035 | false | false | false | false |
JetBrains/kotlin-native | performance/ring/src/main/kotlin/org/jetbrains/ring/IntStreamBenchmark.kt | 4 | 2609 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
import org.jetbrains.benchmarksLauncher.Blackhole
open class IntStreamBenchmark {
private var _data: Iterable<Int>? = null
val data: Iterable<Int>
get() = _data!!
init {
_data = intValues(BENCHMARK_SIZE)
}
//Benchmark
fun copy(): List<Int> {
return data.asSequence().toList()
}
//Benchmark
fun copyManual(): List<Int> {
val list = ArrayList<Int>()
for (item in data.asSequence()) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.asSequence().filter { filterLoad(it) }.count()
}
//Benchmark
fun filterAndMap() {
for (item in data.asSequence().filter { filterLoad(it) }.map { mapLoad(it) })
Blackhole.consume(item)
}
//Benchmark
fun filterAndMapManual() {
for (it in data.asSequence()) {
if (filterLoad(it)) {
val item = mapLoad(it)
Blackhole.consume(item)
}
}
}
//Benchmark
fun filter() {
for (item in data.asSequence().filter { filterLoad(it) })
Blackhole.consume(item)
}
//Benchmark
fun filterManual(){
for (it in data.asSequence()) {
if (filterLoad(it))
Blackhole.consume(it)
}
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data.asSequence()) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.asSequence().count { filterLoad(it) }
}
//Benchmark
fun countFilteredLocal(): Int {
return data.asSequence().cnt { filterLoad(it) }
}
//Benchmark
fun reduce(): Int {
return data.asSequence().fold(0) {acc, it -> if (filterLoad(it)) acc + 1 else acc }
}
} | apache-2.0 | 4bb4bd6541e2ef80009b55e85d530050 | 24.339806 | 91 | 0.572633 | 4.298188 | false | false | false | false |
vovagrechka/fucking-everything | vgrechka-kt/js/src/vgrechka/vgjs-tests.kt | 1 | 664 | package vgrechka
object Test1 {val __for = Debug::nextDebugId
object fucker1; object fucker2
val fuckers = listOf(fucker1, fucker2)
val numIterationsPerFucker = 100
val generatedIds = mutableSetOf<String>()
val expectedNumGeneratedUniqueIds = fuckers.size * numIterationsPerFucker
fun dance(args: Array<String>) {
for (fucker in fuckers) {
for (i in 1..numIterationsPerFucker) {
val id = Debug.nextDebugId(fucker)
generatedIds += id
clog(id)
}
}
assertEquals(expectedNumGeneratedUniqueIds, generatedIds.size)
clog("\nOK")
}
}
| apache-2.0 | fe36aa0bf0981264bba90b5b324a3a58 | 25.56 | 77 | 0.618976 | 4.202532 | false | false | false | false |
jwren/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarShowHidePopupAction.kt | 2 | 3833 | // 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.execution.runToolbar
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.project.DumbAware
import net.miginfocom.swing.MigLayout
import java.awt.Dimension
import java.awt.Point
import javax.swing.JComponent
import javax.swing.JPanel
class RunToolbarShowHidePopupAction : AnAction(
ActionsBundle.message("action.RunToolbarShowHidePopupAction.show.popup.text")), CustomComponentAction, DumbAware, RTBarAction {
override fun actionPerformed(e: AnActionEvent) {
}
override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean {
return state == RunToolbarMainSlotState.CONFIGURATION
}
override fun update(e: AnActionEvent) {
e.arrowIcon()?.let {
e.presentation.icon = it
}
if (!RunToolbarProcess.isExperimentalUpdatingEnabled) {
e.mainState()?.let {
e.presentation.isEnabledAndVisible = e.presentation.isEnabledAndVisible && checkMainSlotVisibility(it)
}
}
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val extraSlotsActionButton = ExtraSlotsActionButton(this@RunToolbarShowHidePopupAction, presentation, place)
return object : JPanel(MigLayout("ins 0, gap 0, fill")), PopupControllerComponent {
override fun addListener(listener: PopupControllerComponentListener) {
extraSlotsActionButton.addListener(listener)
}
override fun removeListener(listener: PopupControllerComponentListener) {
extraSlotsActionButton.removeListener(listener)
}
override fun updateIconImmediately(isOpened: Boolean) {
extraSlotsActionButton.updateIconImmediately(isOpened)
}
}.apply {
isOpaque = false
add(DraggablePane(), "pos 0 0")
add(extraSlotsActionButton, "grow")
}
}
private class ExtraSlotsActionButton(action: AnAction,
presentation: Presentation,
place: String) : ActionButton(action, presentation, place,
ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE), PopupControllerComponent {
override fun addNotify() {
super.addNotify()
mousePosition?.let {
val bounds = this.bounds
bounds.location = Point(0, 0)
if (bounds.contains(it)) {
myRollover = true
repaint()
}
}
}
override fun actionPerformed(event: AnActionEvent) {
val list = mutableListOf<PopupControllerComponentListener>()
list.addAll(listeners)
list.forEach { it.actionPerformedHandler() }
}
private val listeners = mutableListOf<PopupControllerComponentListener>()
override fun addListener(listener: PopupControllerComponentListener) {
listeners.add(listener)
}
override fun removeListener(listener: PopupControllerComponentListener) {
listeners.remove(listener)
}
override fun updateIconImmediately(isOpened: Boolean) {
myIcon = if (isOpened) AllIcons.Toolbar.Collapse
else AllIcons.Toolbar.Expand
}
override fun getPreferredSize(): Dimension {
val d = super.getPreferredSize()
d.width = FixWidthSegmentedActionToolbarComponent.ARROW_WIDTH
return d
}
}
} | apache-2.0 | 8e2a34a5e6e1bd4eed9f6cb1aadcdd3a | 33.854545 | 158 | 0.716671 | 5.131191 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt | 1 | 7285 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.FrameExtraVariablesProvider
import com.intellij.debugger.engine.evaluation.CodeFragmentKind
import com.intellij.debugger.engine.evaluation.EvaluationContext
import com.intellij.debugger.engine.evaluation.TextWithImports
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl
import com.intellij.debugger.settings.DebuggerSettings
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.text.CharArrayUtil
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.getLineEndOffset
import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset
import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import java.util.*
import kotlin.math.max
import kotlin.math.min
class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider {
override fun isAvailable(sourcePosition: SourcePosition, evalContext: EvaluationContext): Boolean {
if (runReadAction { sourcePosition.line } < 0) return false
return sourcePosition.file.fileType == KotlinFileType.INSTANCE && DebuggerSettings.getInstance().AUTO_VARIABLES_MODE
}
override fun collectVariables(
sourcePosition: SourcePosition, evalContext: EvaluationContext, alreadyCollected: MutableSet<String>
): Set<TextWithImports> = runReadAction { findAdditionalExpressions(sourcePosition) }
}
private fun findAdditionalExpressions(position: SourcePosition): Set<TextWithImports> {
val line = position.line
val file = position.file
val vFile = file.virtualFile
val doc = if (vFile != null) FileDocumentManager.getInstance().getDocument(vFile) else null
if (doc == null || doc.lineCount == 0 || line > (doc.lineCount - 1)) {
return emptySet()
}
val offset = file.getLineStartOffset(line)?.takeIf { it > 0 } ?: return emptySet()
val elem = file.findElementAt(offset) ?: return emptySet()
val containingElement = getContainingElement(elem) ?: elem
val limit = getLineRangeForElement(containingElement, doc)
var startLine = max(limit.startOffset, line)
while (startLine - 1 > limit.startOffset && shouldSkipLine(file, doc, startLine - 1)) {
startLine--
}
var endLine = min(limit.endOffset, line)
while (endLine + 1 < limit.endOffset && shouldSkipLine(file, doc, endLine + 1)) {
endLine++
}
val startOffset = file.getLineStartOffset(startLine) ?: return emptySet()
val endOffset = file.getLineEndOffset(endLine) ?: return emptySet()
if (startOffset >= endOffset) return emptySet()
val lineRange = TextRange(startOffset, endOffset)
if (lineRange.isEmpty) return emptySet()
val expressions = LinkedHashSet<TextWithImports>()
val variablesCollector = VariablesCollector(lineRange, expressions)
containingElement.accept(variablesCollector)
return expressions
}
private fun getContainingElement(element: PsiElement): KtElement? {
val contElement =
PsiTreeUtil.getParentOfType(element, KtDeclaration::class.java) ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java)
if (contElement is KtProperty && contElement.isLocal) {
val parent = contElement.parent
return getContainingElement(parent)
}
if (contElement is KtDeclarationWithBody) {
return contElement.bodyExpression
}
return contElement
}
private fun getLineRangeForElement(containingElement: PsiElement, doc: Document): TextRange {
val elemRange = containingElement.textRange
return TextRange(doc.getLineNumber(elemRange.startOffset), doc.getLineNumber(elemRange.endOffset))
}
private fun shouldSkipLine(file: PsiFile, doc: Document, line: Int): Boolean {
val start = CharArrayUtil.shiftForward(doc.charsSequence, doc.getLineStartOffset(line), " \n\t")
val end = doc.getLineEndOffset(line)
if (start >= end) {
return true
}
val elemAtOffset = file.findElementAt(start)
val topmostElementAtOffset = getTopmostElementAtOffset(elemAtOffset!!, start)
return topmostElementAtOffset !is KtDeclaration
}
private class VariablesCollector(
private val myLineRange: TextRange,
private val myExpressions: MutableSet<TextWithImports>
) : KtTreeVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (element.isInRange()) {
super.visitKtElement(element)
}
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
if (expression.isInRange()) {
val selector = expression.selectorExpression
if (selector is KtReferenceExpression) {
if (isRefToProperty(selector)) {
myExpressions.add(expression.createText())
return
}
}
}
super.visitQualifiedExpression(expression)
}
private fun isRefToProperty(expression: KtReferenceExpression): Boolean {
// NB: analyze() cannot be called here, because DELEGATED_PROPERTY_RESOLVED_CALL will be always null
// Looks like a bug
@Suppress("DEPRECATION")
val context = expression.analyzeWithAllCompilerChecks().bindingContext
val descriptor = context[BindingContext.REFERENCE_TARGET, expression]
if (descriptor is PropertyDescriptor) {
val getter = descriptor.getter
return (getter == null || context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getter] == null) && descriptor.compileTimeInitializer == null
}
return false
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
if (expression.isInRange()) {
if (isRefToProperty(expression)) {
myExpressions.add(expression.createText())
}
}
super.visitReferenceExpression(expression)
}
private fun KtElement.isInRange(): Boolean = myLineRange.intersects(this.textRange)
private fun KtElement.createText(): TextWithImports = TextWithImportsImpl(CodeFragmentKind.EXPRESSION, this.text)
override fun visitClass(klass: KtClass) {
// Do not show expressions used in local classes
}
override fun visitNamedFunction(function: KtNamedFunction) {
// Do not show expressions used in local functions
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
// Do not show expressions used in anonymous objects
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
// Do not show expressions used in lambdas
}
} | apache-2.0 | 81da1b057228e9b1c2c845a4427023d8 | 39.254144 | 156 | 0.735896 | 5.055517 | false | false | false | false |
miketrewartha/positional | app/src/main/kotlin/io/trewartha/positional/ui/location/LocationViewModel.kt | 1 | 17074 | package io.trewartha.positional.ui.location
import android.Manifest
import android.app.Application
import android.content.ClipData
import android.content.ClipboardManager
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.location.Location
import android.os.Looper
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.lifecycle.*
import com.google.android.gms.location.*
import com.google.firebase.perf.FirebasePerformance
import com.google.firebase.perf.metrics.Trace
import dagger.hilt.android.lifecycle.HiltViewModel
import io.trewartha.positional.PositionalApplication
import io.trewartha.positional.R
import io.trewartha.positional.domain.entities.CoordinatesFormat
import io.trewartha.positional.domain.entities.Units
import io.trewartha.positional.location.LocationFormatter
import io.trewartha.positional.ui.ViewModelEvent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import timber.log.Timber
import java.util.*
import javax.inject.Inject
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
@HiltViewModel
class LocationViewModel @Inject constructor(
private val app: Application,
private val clipboardManager: ClipboardManager,
private val fusedLocationProviderClient: FusedLocationProviderClient,
private val locationFormatter: LocationFormatter,
private val prefs: SharedPreferences
) : AndroidViewModel(app) {
val accuracyVisibility: LiveData<Int> by lazy {
callbackFlow {
if (prefs.contains(prefsKeyShowAccuracies))
offer(prefs.getBoolean(prefsKeyShowAccuracies, DEFAULT_SHOW_ACCURACIES))
prefShowAccuraciesListener = PrefShowAccuraciesListener(this)
prefs.registerOnSharedPreferenceChangeListener(prefShowAccuraciesListener)
awaitClose {
prefShowAccuraciesListener
?.let { prefs.unregisterOnSharedPreferenceChangeListener(it) }
}
}.map {
if (it) View.VISIBLE else View.GONE
}.asLiveData()
}
val bearing: LiveData<String> by lazy {
location.mapNotNull { it }
.map { locationFormatter.getBearing(it) ?: app.getString(R.string.common_dash) }
.asLiveData()
}
val bearingAccuracy: LiveData<String?> by lazy {
location.mapNotNull { it }
.map { locationFormatter.getBearingAccuracy(it) }
.asLiveData()
}
val coordinates: LiveData<Coordinates> by lazy {
_coordinates.mapNotNull { it }.asLiveData()
}
val coordinatesAccuracy: LiveData<String> by lazy {
combine(location.mapNotNull { it }, units) { location, units ->
locationFormatter.getCoordinatesAccuracy(location, units)
}.asLiveData()
}
val elevation: LiveData<String> by lazy {
combine(location.mapNotNull { it }, units) { location, units ->
locationFormatter.getElevation(location, units) ?: app.getString(R.string.common_dash)
}.asLiveData()
}
val elevationAccuracy: LiveData<String?> by lazy {
combine(location.mapNotNull { it }, units) { location, units ->
locationFormatter.getElevationAccuracy(location, units)
}.asLiveData()
}
val events: LiveData<Event>
get() = _events
val screenLockState: LiveData<ScreenLockState> by lazy {
callbackFlow {
if (prefs.contains(prefsKeyScreenLock))
offer(prefs.getBoolean(prefsKeyScreenLock, DEFAULT_SCREEN_LOCK))
prefScreenLockListener = PrefScreenLockListener(this)
prefs.registerOnSharedPreferenceChangeListener(prefScreenLockListener)
awaitClose {
prefScreenLockListener?.let { prefs.unregisterOnSharedPreferenceChangeListener(it) }
}
}.map {
val icon = ContextCompat.getDrawable(
app,
if (it) R.drawable.ic_twotone_smartphone_24px
else R.drawable.ic_twotone_screen_lock_portrait_24px
)!!
val contentDescription = app.getString(
if (it) R.string.location_screen_lock_button_content_description_on
else R.string.location_screen_lock_button_content_description_off
)
val tooltip = app.getString(
if (it) R.string.location_screen_lock_button_tooltip_on
else R.string.location_screen_lock_button_tooltip_off
)
ScreenLockState(it, icon, contentDescription, tooltip)
}.asLiveData()
}
val speed: LiveData<String> by lazy {
combine(location.mapNotNull { it }, units) { location, units ->
locationFormatter.getSpeed(location, units) ?: app.getString(R.string.common_dash)
}.asLiveData()
}
val speedAccuracy: LiveData<String?> by lazy {
combine(location.mapNotNull { it }, units) { location, units ->
locationFormatter.getSpeedAccuracy(location, units)
}.asLiveData()
}
val updatedAt: LiveData<String> by lazy {
location.mapNotNull { it }
.map { locationFormatter.getTimestamp(it) ?: app.getString(R.string.common_dash) }
.asLiveData()
}
private val _coordinates: StateFlow<Coordinates?> by lazy {
combine(
location.mapNotNull { it },
coordinatesFormat.mapNotNull { it }
) { location, format ->
location.toCoordinates(format)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)
}
private val _events = MutableLiveData<Event>()
private val coordinatesFormat: StateFlow<CoordinatesFormat?> = callbackFlow {
if (prefs.contains(prefsKeyCoordinatesFormat))
offer(prefs.getString(prefsKeyCoordinatesFormat, null))
prefCoordinatesFormatListener = PrefCoordinatesFormatListener(this)
prefs.registerOnSharedPreferenceChangeListener(prefCoordinatesFormatListener)
awaitClose {
prefCoordinatesFormatListener?.let {
prefs.unregisterOnSharedPreferenceChangeListener(it)
}
}
}.map {
CoordinatesFormat.valueOf(it!!.toUpperCase(Locale.US))
}.catch {
emit(DEFAULT_COORDINATES_FORMAT)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)
private val location: StateFlow<Location?> by lazy {
havePermissions.filter { it }.flatMapLatest {
callbackFlow<Location> {
var firstLocationUpdateTrace: Trace? =
FirebasePerformance.getInstance().newTrace("first_location")
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation ?: return
offer(location)
if (firstLocationUpdateTrace != null) {
val accuracyCounter = when (location.accuracy) {
in 0.0f.rangeTo(5.0f) -> COUNTER_ACCURACY_VERY_HIGH
in 5.0f.rangeTo(10.0f) -> COUNTER_ACCURACY_HIGH
in 10.0f.rangeTo(15.0f) -> COUNTER_ACCURACY_MEDIUM
in 15.0f.rangeTo(20.0f) -> COUNTER_ACCURACY_LOW
else -> COUNTER_ACCURACY_VERY_LOW
}
firstLocationUpdateTrace?.incrementMetric(accuracyCounter, 1L)
firstLocationUpdateTrace?.stop()
firstLocationUpdateTrace = null
}
}
override fun onLocationAvailability(locationAvailability: LocationAvailability) {
Timber.d("Location availability changed to $locationAvailability")
}
}
try {
val locationRequest = LocationRequest.create()
.setPriority(LOCATION_UPDATE_PRIORITY)
.setInterval(LOCATION_UPDATE_INTERVAL_MS)
Timber.i("Requesting location updates: $locationRequest")
if (firstLocationUpdateTrace == null) {
firstLocationUpdateTrace?.start()
}
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
} catch (e: SecurityException) {
Timber.w(
e,
"Don't have location permissions, no location updates will be received"
)
}
awaitClose {
Timber.i("Suspending location updates")
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
}
}
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)
}
private val havePermissions: MutableStateFlow<Boolean> = MutableStateFlow(checkPermissions())
private val units: SharedFlow<Units> = callbackFlow {
if (prefs.contains(prefsKeyUnits))
offer(prefs.getString(prefsKeyUnits, null))
prefUnitsListener = PrefUnitsListener(this)
prefs.registerOnSharedPreferenceChangeListener(prefUnitsListener)
awaitClose {
prefUnitsListener?.let { prefs.unregisterOnSharedPreferenceChangeListener(it) }
}
}.map {
Units.valueOf(it!!.toUpperCase(Locale.US))
}.catch {
emit(DEFAULT_UNITS)
}.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), 1)
private val prefsKeyCoordinatesFormat = app.getString(R.string.settings_coordinates_format_key)
private val prefsKeyScreenLock = app.getString(R.string.settings_screen_lock_key)
private val prefsKeyShowAccuracies = app.getString(R.string.settings_show_accuracies_key)
private val prefsKeyUnits = app.getString(R.string.settings_units_key)
private var prefCoordinatesFormatListener: PrefCoordinatesFormatListener? = null
private var prefScreenLockListener: PrefScreenLockListener? = null
private var prefShowAccuraciesListener: PrefShowAccuraciesListener? = null
private var prefUnitsListener: PrefUnitsListener? = null
init {
if (!checkPermissions()) _events.value = Event.RequestPermissions(PERMISSIONS)
}
fun handleViewEvent(event: LocationFragment.Event) {
when (event) {
is LocationFragment.Event.CopyClick -> handleCopyClick()
is LocationFragment.Event.HelpClick -> handleHelpClick()
is LocationFragment.Event.PermissionsResult -> handlePermissionsResult(event)
is LocationFragment.Event.ScreenLockClick -> handleScreenLockClick()
is LocationFragment.Event.SystemSettingsResult -> handleSystemSettingsResult()
is LocationFragment.Event.ShareClick -> handleShareClick()
}
}
private fun checkPermissions(): Boolean {
return PERMISSIONS.all {
ContextCompat.checkSelfPermission(app, it) == PackageManager.PERMISSION_GRANTED
}
}
private fun handleCopyClick() {
val location = location.value
val format = coordinatesFormat.value
_events.value = if (location == null || format == null) {
Event.CoordinatesCopy.Error()
} else {
clipboardManager.setPrimaryClip(
ClipData.newPlainText(
getApplication<PositionalApplication>()
.getString(R.string.location_copied_coordinates_label),
locationFormatter.getSharedCoordinates(location, format)
)
)
Event.CoordinatesCopy.Success()
}
}
private fun handleHelpClick() {
_events.value = Event.NavigateToLocationHelp()
}
private fun handlePermissionsResult(event: LocationFragment.Event.PermissionsResult) {
val allPermissionsGranted = event.result.all { it.value }
havePermissions.tryEmit(allPermissionsGranted)
if (!allPermissionsGranted) _events.value = Event.ShowPermissionsDeniedDialog()
}
private fun handleScreenLockClick() {
val locked = !prefs.getBoolean(prefsKeyScreenLock, false)
prefs.edit { putBoolean(prefsKeyScreenLock, locked) }
_events.value = Event.ScreenLock(locked)
}
private fun handleShareClick() {
val location = location.value
val format = coordinatesFormat.value
_events.value = if (location == null || format == null)
Event.CoordinatesShare.Error()
else
Event.CoordinatesShare.Success(locationFormatter.getSharedCoordinates(location, format))
}
private fun handleSystemSettingsResult() {
val havePermissionsNow = checkPermissions()
havePermissions.tryEmit(havePermissionsNow)
if (!havePermissionsNow) _events.value = Event.ShowPermissionsDeniedDialog()
}
private fun Location.toCoordinates(format: CoordinatesFormat): Coordinates {
val (coordinates, coordinatesLines) = locationFormatter.getCoordinates(this, format)
return Coordinates(coordinatesLines, coordinates)
}
data class Coordinates(val maxLines: Int, val text: String)
data class ScreenLockState(
val locked: Boolean,
val icon: Drawable,
val contentDescription: String,
val tooltip: String
)
sealed class Event : ViewModelEvent() {
sealed class CoordinatesCopy : Event() {
class Error : CoordinatesCopy()
class Success : CoordinatesCopy()
}
sealed class CoordinatesShare : Event() {
class Error : CoordinatesShare()
data class Success(val coordinates: String) : CoordinatesShare()
}
class NavigateToLocationHelp : Event()
class ShowPermissionsDeniedDialog : Event()
data class RequestPermissions(val permissions: List<String>) : Event()
data class ScreenLock(val locked: Boolean) : Event()
}
private inner class PrefCoordinatesFormatListener(
val producerScope: ProducerScope<String?>
) : SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPrefs: SharedPreferences, key: String) {
if (key == prefsKeyCoordinatesFormat)
producerScope.offer(sharedPrefs.getString(key, null))
}
}
private inner class PrefScreenLockListener(
val producerScope: ProducerScope<Boolean>
) : SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPrefs: SharedPreferences, key: String) {
if (key == prefsKeyScreenLock)
producerScope.offer(sharedPrefs.getBoolean(key, DEFAULT_SCREEN_LOCK))
}
}
private inner class PrefShowAccuraciesListener(
val producerScope: ProducerScope<Boolean>
) : SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPrefs: SharedPreferences, key: String) {
if (key == prefsKeyShowAccuracies)
producerScope.offer(sharedPrefs.getBoolean(key, DEFAULT_SHOW_ACCURACIES))
}
}
private inner class PrefUnitsListener(
val producerScope: ProducerScope<String?>
) : SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(sharedPrefs: SharedPreferences, key: String) {
if (key == prefsKeyUnits)
producerScope.offer(sharedPrefs.getString(key, null))
}
}
companion object {
private const val COUNTER_ACCURACY_VERY_HIGH = "accuracy_very_high"
private const val COUNTER_ACCURACY_HIGH = "accuracy_high"
private const val COUNTER_ACCURACY_MEDIUM = "accuracy_medium"
private const val COUNTER_ACCURACY_LOW = "accuracy_low"
private const val COUNTER_ACCURACY_VERY_LOW = "accuracy_very_low"
private val DEFAULT_COORDINATES_FORMAT = CoordinatesFormat.DD
private const val DEFAULT_SCREEN_LOCK = false
private const val DEFAULT_SHOW_ACCURACIES = true
private val DEFAULT_UNITS = Units.METRIC
private const val LOCATION_UPDATE_INTERVAL_MS = 1_000L
private const val LOCATION_UPDATE_PRIORITY = LocationRequest.PRIORITY_HIGH_ACCURACY
private val PERMISSIONS = listOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
}
} | mit | 17da85c9f8a32c95a72d1a5eff965642 | 41.160494 | 101 | 0.654621 | 5.148975 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/MockLibraryFacility.kt | 2 | 2678 | // 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.test
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.OrderRootType
import com.intellij.testFramework.IdeaTestUtil
import org.jetbrains.kotlin.idea.framework.JSLibraryKind
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.platform.js.JsPlatform
import org.jetbrains.kotlin.test.KotlinCompilerStandalone
import java.io.File
data class MockLibraryFacility(
val sources: List<File>,
val attachSources: Boolean = true,
val platform: KotlinCompilerStandalone.Platform = KotlinCompilerStandalone.Platform.Jvm(),
val options: List<String> = emptyList(),
val classpath: List<File> = emptyList()
) {
constructor(
source: File,
attachSources: Boolean = true,
platform: KotlinCompilerStandalone.Platform = KotlinCompilerStandalone.Platform.Jvm(),
options: List<String> = emptyList(),
classpath: List<File> = emptyList()
) : this(listOf(source), attachSources, platform, options, classpath)
companion object {
const val MOCK_LIBRARY_NAME = "kotlinMockLibrary"
fun tearDown(module: Module) {
ConfigLibraryUtil.removeLibrary(module, MOCK_LIBRARY_NAME)
}
}
fun setUp(module: Module) {
val libraryJar = KotlinCompilerStandalone(
sources,
platform = platform,
options = options,
classpath = classpath
).compile()
val kind = if (platform is JsPlatform) JSLibraryKind else null
ConfigLibraryUtil.addLibrary(module, MOCK_LIBRARY_NAME, kind) {
addRoot(libraryJar, OrderRootType.CLASSES)
if (attachSources) {
for (source in sources) {
addRoot(source, OrderRootType.SOURCES)
}
}
}
}
fun tearDown(module: Module) = Companion.tearDown(module)
val asKotlinLightProjectDescriptor: KotlinLightProjectDescriptor
get() = object : KotlinLightProjectDescriptor() {
override fun configureModule(module: Module, model: ModifiableRootModel) = [email protected](module)
override fun getSdk(): Sdk = if ([email protected] is JsPlatform)
KotlinSdkType.INSTANCE.createSdkWithUniqueName(emptyList())
else
IdeaTestUtil.getMockJdk18()
}
}
| apache-2.0 | 20c6ccf095e4d204bd49dcd43347fcf7 | 37.811594 | 158 | 0.690067 | 4.959259 | false | true | false | false |
LouisCAD/Splitties | modules/material-lists/src/androidMain/kotlin/splitties/material/lists/IconOneLineListItem.kt | 1 | 2126 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.material.lists
import android.content.Context
import android.text.TextUtils.TruncateAt.END
import android.util.AttributeSet
import android.view.Gravity
import android.widget.TextView
import androidx.appcompat.R
import splitties.dimensions.dip
import splitties.resources.styledColorSL
import splitties.views.appcompat.imgTintList
import splitties.views.dsl.core.add
import splitties.views.dsl.core.endMargin
import splitties.views.dsl.core.imageView
import splitties.views.dsl.core.lParams
import splitties.views.dsl.core.startMargin
import splitties.views.dsl.core.textView
import splitties.views.dsl.core.verticalMargin
import splitties.views.dsl.core.wrapContent
import splitties.views.selectable.SelectableLinearLayout
import splitties.views.textAppearance
class IconOneLineListItem @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
disableDefaultTint: Boolean = false
) : SelectableLinearLayout(context, attrs, defStyleAttr) {
val icon = imageView {
if (!disableDefaultTint) imgTintList = styledColorSL(android.R.attr.textColorSecondary)
isDuplicateParentStateEnabled = true
}
/**
* The one-line list item keeps the [firstLine] name for its only [TextView] to make
* switching to and from [IconTwoLinesListItem] easier.
*/
val firstLine = textView {
ellipsize = END
minLines = 1
maxLines = 1
textAppearance = R.style.TextAppearance_AppCompat_Subhead
isDuplicateParentStateEnabled = true
}
init {
val iconSize = dip(24)
add(icon, lParams(iconSize, iconSize) {
gravity = Gravity.CENTER_VERTICAL or Gravity.START
startMargin = dip(16)
})
add(firstLine, lParams(height = wrapContent) {
gravity = Gravity.CENTER_VERTICAL or Gravity.START
startMargin = dip(32)
verticalMargin = dip(16)
endMargin = dip(16)
})
}
}
| apache-2.0 | a519146647129ccacbdf036a82f99c7b | 32.21875 | 109 | 0.722484 | 4.365503 | false | false | false | false |
cy6erGn0m/kotlin-frontend-plugin | kotlin-frontend/src/test/kotlin/org/jetbrains/kotlin/gradle/frontend/SimpleFrontendProjectTest.kt | 1 | 19908 | package org.jetbrains.kotlin.gradle.frontend
import groovy.json.JsonSlurper
import org.gradle.testkit.runner.BuildTask
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.jetbrains.kotlin.gradle.frontend.util.mkdirsOrFail
import org.jetbrains.kotlin.gradle.frontend.util.toSemver
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import java.net.URL
import kotlin.test.*
@RunWith(Parameterized::class)
class SimpleFrontendProjectTest(gradleVersion: String, kotlinVersion: String) : AbstractFrontendTest(gradleVersion, kotlinVersion) {
@Test
fun testEmptyProject() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build())
val result = GradleRunner.create()
.withProjectDir(projectDir.root)
.withArguments("bundle")
.withGradleVersion(gradleVersion)
.withDebug(true)
.build()
assertNull(result.task(":webpack-bundle"))
assertNotFailed(result.task(":npm-install"))
}
@Test
fun testSimpleProjectNoBundles() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
block("compileKotlin2Js") {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
}
""")
val result = runner.withArguments("bundle").build()
assertNull(result.task(":webpack-bundle"))
assertNotFailed(result.task(":npm-install"))
assertEquals(TaskOutcome.SUCCESS, result.task(":compileKotlin2Js")?.outcome)
assertTrue { projectDir.root.resolve("build/js/script.js").isFile }
}
@Test
fun testSimpleProjectWebPackBundle() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("webpackBundle") {
line("port = $port")
line("bundleName = \"main\"")
}
}
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
}
""")
val result = runner.withArguments("bundle").build()
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-preunpack")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-install")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-bundle")?.outcome)
assertTrue { projectDir.root.resolve("build/js/script.js").isFile }
assertTrue { projectDir.root.resolve("build/bundle/main.bundle.js").isFile }
}
@Test
fun testSimpleProjectWebPackBundleWithDce() {
builder.applyDcePlugin()
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("webpackBundle") {
line("port = $port")
line("bundleName = \"main\"")
}
}
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
usedFunction2222()
}
private fun usedFunction2222() {
}
private fun unusedFunction1111() {
}
""")
val result = runner.withArguments("bundle").build()
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-preunpack")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-install")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-bundle")?.outcome)
assertTrue { projectDir.root.resolve("build/js/script.js").isFile }
assertTrue { projectDir.root.resolve("build/bundle/main.bundle.js").isFile }
assertTrue { "unusedFunction1111" in projectDir.root.resolve("build/js/script.js").readText() }
assertTrue { "unusedFunction1111" !in projectDir.root.resolve("build/bundle/main.bundle.js").readText() }
assertTrue { "usedFunction2222" in projectDir.root.resolve("build/js/script.js").readText() }
assertTrue { "usedFunction2222" in projectDir.root.resolve("build/bundle/main.bundle.js").readText() }
}
@Test
fun testSimpleProjectWebPackBundleFail() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("webpackBundle") {
line("port = $port")
line("bundleName = \"main\"")
}
}
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
}
""")
projectDir.root.resolve("webpack.config.d").mkdirsOrFail()
projectDir.root.resolve("webpack.config.d/failure.js").writeText("""
letsFailHere()
""".trimIndent())
val result = runner.withArguments("bundle").buildAndFail()
assertEquals(TaskOutcome.FAILED, result.task(":webpack-bundle")?.outcome)
assertTrue { projectDir.root.resolve("build/js/script.js").isFile }
assertFalse { projectDir.root.resolve("build/bundle/main.bundle.js").isFile }
}
@Test
fun testNpmOnly() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
line("version '1.0'")
kotlinFrontend {
block("npm") {
line("dependency \"style-loader\"")
}
}
})
val runner = runner.withArguments("npm")
val result = runner.build()
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-preunpack")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-configure")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-install")?.outcome)
assertNull(result.task(":webpack-bundle"))
assertTrue { projectDir.root.resolve("build/node_modules/style-loader").isDirectory }
val expectedProjectVersion = toSemver("1.0")
val expectedKotlinVersion = toSemver(kotlinVersion)
@Suppress("UNCHECKED_CAST")
val packageJsonKotlinVersion = projectDir.root.resolve("build/package.json")
.let { JsonSlurper().parse(it) as Map<String, Any?> }["dependencies"]
?.let { it as Map<String, String?> }
?.let { it["kotlin"] } ?: fail("No kotlin found in package.json")
assertEquals(kotlinVersion, packageJsonKotlinVersion)
@Suppress("UNCHECKED_CAST")
assertEquals(expectedKotlinVersion,
projectDir.root.resolve("build/node_modules/kotlin/package.json")
.let { JsonSlurper().parse(it) as Map<String, Any?> }["version"]
)
@Suppress("UNCHECKED_CAST")
assertEquals(expectedProjectVersion,
projectDir.root.resolve("build/package.json")
.let { JsonSlurper().parse(it) as Map<String, Any?> }["version"]
)
val rerunResult = runner.build()
assertEquals(TaskOutcome.UP_TO_DATE, rerunResult.task(":npm-preunpack")?.outcome)
assertEquals(TaskOutcome.UP_TO_DATE, rerunResult.task(":npm-configure")?.outcome)
assertEquals(TaskOutcome.UP_TO_DATE, rerunResult.task(":npm-install")?.outcome)
buildGradleFile.writeText(buildGradleFile.readText().replace("dependency", "devDependency"))
val rerunResult2 = runner.build()
assertEquals(TaskOutcome.UP_TO_DATE, rerunResult2.task(":npm-preunpack")?.outcome)
assertEquals(TaskOutcome.SUCCESS, rerunResult2.task(":npm-configure")?.outcome)
assertEquals(TaskOutcome.SUCCESS, rerunResult2.task(":npm-install")?.outcome)
}
@Test
fun testNpmFail() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("npm") {
line("dependency \"non-existing-package-here\"")
}
}
})
val result = runner.withArguments("npm").buildAndFail()
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-preunpack")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":npm-configure")?.outcome)
assertEquals(TaskOutcome.FAILED, result.task(":npm-install")?.outcome)
}
@Test
fun testBundleWithParts() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("webpackBundle") {
line("port = $port")
line("bundleName = \"main\"")
}
}
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
}
""")
val runner = runner.withArguments("bundle")
val result = runner.build()
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-bundle")?.outcome)
assertTrue { projectDir.root.resolve("build/js/script.js").isFile }
assertTrue { projectDir.root.resolve("build/bundle/main.bundle.js").isFile }
val noChangesRerunResult = runner.build()
assertEquals(TaskOutcome.UP_TO_DATE, noChangesRerunResult.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.UP_TO_DATE, noChangesRerunResult.task(":webpack-bundle")?.outcome)
projectDir.root.resolve("webpack.config.d").mkdirsOrFail()
projectDir.root.resolve("webpack.config.d/part.js").writeText("""
// this is a part
""".trimIndent())
val rerunResult = runner.build()
assertEquals(TaskOutcome.SUCCESS, rerunResult.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, rerunResult.task(":webpack-bundle")?.outcome)
assertTrue { "this is a part" in projectDir.root.resolve("build/webpack.config.js").readText() }
}
@Test
fun testWebPackRunAndStop() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("webpackBundle") {
line("port = $port")
line("bundleName = \"main\"")
}
}
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
println("my script content")
}
""")
val runner = runner.withArguments("run")
val result = runner.build()
try {
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-run")?.outcome)
assertNotExecuted(result.task(":karma-start"))
assertNull(result.task(":ktor-start"))
assertFalse { projectDir.root.resolve("build/bundle/main.bundle.js").exists() }
val bundleContent = URL("http://localhost:$port/main.bundle.js").openStream().reader().use { it.readText() }
assertTrue { "my script content" in bundleContent }
} finally {
val stopResult = runner.withArguments("stop").build()
assertEquals(TaskOutcome.SUCCESS, stopResult.task(":webpack-stop")?.outcome)
assertFails {
fail(URL("http://localhost:$port/main.bundle.js").openStream().reader().use { it.readText() })
}
}
}
@Test
fun testWebPackRunAmendConfigAndReRun() {
builder.applyFrontendPlugin()
buildGradleFile.writeText(builder.build {
kotlinFrontend {
block("webpackBundle") {
line("port = $port")
line("bundleName = \"main\"")
}
}
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/script.js\"")
}
})
srcDir.mkdirsOrFail()
srcDir.resolve("main.kt").writeText("""
fun main(args: Array<String>) {
println("my script content")
}
""")
val runner = runner.withArguments("run")
val result = runner.build()
try {
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":webpack-run")?.outcome)
URL("http://localhost:$port/main.bundle.js").openStream().reader().use { it.readText() }
buildGradleFile.writeText(buildGradleFile.readText().replace("port = $port", "port = $port + 1"))
val rerunResult = runner.build() // should detect changes and rerun
assertEquals(TaskOutcome.UP_TO_DATE, rerunResult.task(":webpack-config")?.outcome)
assertEquals(TaskOutcome.SUCCESS, rerunResult.task(":webpack-run")?.outcome)
URL("http://localhost:${port + 1}/main.bundle.js").openStream().reader().use { it.readText() }
} finally {
val stopResult = runner.withArguments("stop").build()
assertEquals(TaskOutcome.SUCCESS, stopResult.task(":webpack-stop")?.outcome)
assertFails {
fail(URL("http://localhost:$port/main.bundle.js").openStream().reader().use { it.readText() })
}
assertFails {
fail(URL("http://localhost:${port + 1}/main.bundle.js").openStream().reader().use { it.readText() })
}
}
}
@Test
fun testMultiModule() {
buildGradleFile.writeText(builder.build())
projectDir.root.resolve("settings.gradle").writeText("""
include 'module1'
include 'module2'
include 'module3'
""".trimIndent())
val module1 = projectDir.root.resolve("module1")
val module2 = projectDir.root.resolve("module2")
val module3 = projectDir.root.resolve("module3")
module1.mkdirsOrFail()
module2.mkdirsOrFail()
module3.mkdirsOrFail()
val src1 = module1.resolve("src/main/kotlin")
val src2 = module2.resolve("src/main/kotlin")
val src3 = module3.resolve("src/main/kotlin")
src1.mkdirsOrFail()
src2.mkdirsOrFail()
src3.mkdirsOrFail()
val builder1 = BuildScriptBuilder().apply {
[email protected] = [email protected]
applyKotlin2JsPlugin()
addJsDependency()
}
val builder2 = BuildScriptBuilder().apply {
[email protected] = [email protected]
applyKotlin2JsPlugin()
addJsDependency()
compileDependencies += ":module1"
}
val builder3 = BuildScriptBuilder().apply {
[email protected] = [email protected]
applyKotlin2JsPlugin()
applyFrontendPlugin()
addJsDependency()
compileDependencies += ":module2"
}
module1.resolve("build.gradle").writeText(builder1.build {
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/test-lib1.js\"")
line("kotlinOptions.moduleKind = \"commonjs\"")
}
})
module2.resolve("build.gradle").writeText(builder2.build {
compileKotlin2Js {
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/test-lib2.js\"")
line("kotlinOptions.moduleKind = \"commonjs\"")
}
})
module3.resolve("build.gradle").writeText(builder3.build {
compileKotlin2Js {
kotlinFrontend {
block("npm") {
line("dependency \"style-loader\"")
}
block("webpackBundle") {
line("bundleName = \"main\"")
}
}
line("kotlinOptions.outputFile = \"\${project.buildDir.path}/js/test-app.js\"")
line("kotlinOptions.moduleKind = \"commonjs\"")
}
})
src1.resolve("lib.kt").writeText("""
package my.test.lib1
val const1 = "my-special-const-1"
fun lib1Function() = 1
""".trimIndent())
src2.resolve("lib.kt").writeText("""
package my.test.lib2
val const2 = "my-special-const-2"
fun lib2Function() = 2
""".trimIndent())
src3.resolve("main.kt").writeText("""
package my.test.ui
import my.test.lib1.*
import my.test.lib2.*
val const3 = "my-special-const-3"
fun main(args: Array<String>) {
println(lib1Function() + lib2Function())
}
""".trimIndent())
val result = runner.withArguments("compileKotlin2Js").build()
assertEquals(TaskOutcome.SUCCESS, result.task(":module1:compileKotlin2Js")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":module2:compileKotlin2Js")?.outcome)
assertEquals(TaskOutcome.SUCCESS, result.task(":module3:compileKotlin2Js")?.outcome)
runner.withArguments("bundle").build()
assertTrue { module3.resolve("build/bundle/main.bundle.js").exists() }
val bundleContent = module3.resolve("build/bundle/main.bundle.js").readText()
assertTrue { "my-special-const-3" in bundleContent }
assertTrue { "my-special-const-2" in bundleContent }
assertTrue { "my-special-const-1" in bundleContent }
}
private fun assertNotExecuted(task: BuildTask?) {
if (task != null && task.outcome != TaskOutcome.UP_TO_DATE && task.outcome != TaskOutcome.SKIPPED) {
fail("${task.path} should be skipped or up-to-date for empty project but it is ${task.outcome}")
}
}
private fun assertNotFailed(task: BuildTask?) {
assertNotEquals(TaskOutcome.FAILED, task?.outcome, "Task ${task?.path} is failed")
}
companion object {
@JvmStatic
@Parameters(name = "gradle {0}, kotlin {1}")
fun versions() = listOf(
arrayOf("3.5", "1.1.61"),
arrayOf("4.1", "1.1.61"),
arrayOf("4.2.1", "1.1.61"),
arrayOf("4.3.1", "1.1.61"),
arrayOf("4.3.1", "1.2.31"),
arrayOf("4.4.1", "1.2.21"),
arrayOf("4.4.1", "1.2.31"),
arrayOf("4.5", "1.2.31"),
arrayOf("4.5", "1.2.41"),
arrayOf("4.6", "1.2.51"),
arrayOf("4.7", "1.2.51"),
arrayOf("4.8", "1.2.51"),
arrayOf("4.9", "1.2.51")
)
}
}
| apache-2.0 | 23bedb9c578a08f41ffd65dd4e3b487b | 35.262295 | 132 | 0.58916 | 4.557692 | false | true | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/data/default.kt | 1 | 3399 | package net.simno.dmach.data
fun defaultPatch(): Patch {
val bd = Channel(
name = "bd",
settings = listOf(
Setting(hText = "Pitch A", vText = "Gain", hIndex = 0, vIndex = 7, x = .4f, y = .49f),
Setting(hText = "Low-pass", vText = "Square", hIndex = 5, vIndex = 3, x = .7f, y = 0f),
Setting(hText = "Pitch B", vText = "Curve Time", hIndex = 1, vIndex = 2, x = .4f, y = .4f),
Setting(hText = "Decay", vText = "Noise Level", hIndex = 6, vIndex = 4, x = .49f, y = .7f)
),
selectedSetting = 0,
pan = .5f
)
val sd = Channel(
name = "sd",
settings = listOf(
Setting(hText = "Pitch", vText = "Gain", hIndex = 0, vIndex = 9, x = .49f, y = .45f),
Setting(hText = "Low-pass", vText = "Noise", hIndex = 7, vIndex = 1, x = .6f, y = .8f),
Setting(hText = "X-fade", vText = "Attack", hIndex = 8, vIndex = 6, x = .35f, y = .55f),
Setting(hText = "Decay", vText = "Body Decay", hIndex = 4, vIndex = 5, x = .55f, y = .42f),
Setting(hText = "Band-pass", vText = "Band-pass Q", hIndex = 2, vIndex = 3, x = .7f, y = .6f)
),
selectedSetting = 0,
pan = .5f
)
val cp = Channel(
name = "cp",
settings = listOf(
Setting(hText = "Pitch", vText = "Gain", hIndex = 0, vIndex = 7, x = .55f, y = .3f),
Setting(hText = "Delay 1", vText = "Delay 2", hIndex = 4, vIndex = 5, x = .3f, y = .3f),
Setting(hText = "Decay", vText = "Filter Q", hIndex = 6, vIndex = 1, x = .59f, y = .2f),
Setting(hText = "Filter 1", vText = "Filter 2", hIndex = 2, vIndex = 3, x = .9f, y = .15f)
),
selectedSetting = 0,
pan = .5f
)
val tt = Channel(
name = "tt",
settings = listOf(
Setting(hText = "Pitch", vText = "Gain", hIndex = 0, vIndex = 1, x = .49f, y = .49f)
),
selectedSetting = 0,
pan = .5f
)
val cb = Channel(
name = "cb",
settings = listOf(
Setting(hText = "Pitch", vText = "Gain", hIndex = 0, vIndex = 5, x = .3f, y = .49f),
Setting(hText = "Decay 1", vText = "Decay 2", hIndex = 1, vIndex = 2, x = .1f, y = .75f),
Setting(hText = "Vcf", vText = "Vcf Q", hIndex = 3, vIndex = 4, x = .3f, y = 0f)
),
selectedSetting = 0,
pan = .5f
)
val hh = Channel(
name = "hh",
settings = listOf(
Setting(hText = "Pitch", vText = "Gain", hIndex = 0, vIndex = 11, x = .45f, y = .4f),
Setting(hText = "Low-pass", vText = "Snap", hIndex = 10, vIndex = 5, x = .8f, y = .1f),
Setting(hText = "Noise Pitch", vText = "Noise", hIndex = 4, vIndex = 3, x = .55f, y = .6f),
Setting(hText = "Ratio B", vText = "Ratio A", hIndex = 2, vIndex = 1, x = .9f, y = 1f),
Setting(hText = "Release", vText = "Attack", hIndex = 7, vIndex = 6, x = .55f, y = .4f),
Setting(hText = "Filter", vText = "Filter Q", hIndex = 8, vIndex = 9, x = .7f, y = .6f)
),
selectedSetting = 0,
pan = .5f
)
return Patch(
title = "untitled",
sequence = Patch.EMPTY_SEQUENCE,
channels = listOf(bd, sd, cp, tt, cb, hh),
selectedChannel = Channel.NONE_ID,
tempo = 120,
swing = 0
)
}
| gpl-3.0 | 78113ae490aa6c20033b8d902c06aace | 43.142857 | 105 | 0.477788 | 2.947962 | false | false | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/patch/ViewState.kt | 1 | 226 | package net.simno.dmach.patch
data class ViewState(
val finish: Boolean = false,
val showDelete: Boolean = false,
val showOverwrite: Boolean = false,
val deleteTitle: String = "",
val title: String = ""
)
| gpl-3.0 | 6157eb1ef60ef1066ab97dad6f136250 | 24.111111 | 39 | 0.668142 | 3.964912 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/extensions/DialogExtensions.kt | 1 | 1566 | package ch.rmy.android.http_shortcuts.extensions
import android.app.Activity
import android.app.Dialog
import ch.rmy.android.framework.extensions.resume
import ch.rmy.android.framework.extensions.showIfPossible
import ch.rmy.android.framework.viewmodel.WithDialog
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.utils.DialogBuilder
import com.afollestad.materialdialogs.MaterialDialog
import kotlinx.coroutines.suspendCancellableCoroutine
fun DialogBuilder.showIfPossible(): MaterialDialog? =
build().showIfPossible()
fun DialogBuilder.showOrElse(block: () -> Unit) {
showIfPossible() ?: block()
}
suspend fun DialogBuilder.showAndAwaitDismissal() {
suspendCancellableCoroutine<Unit> { continuation ->
dismissListener {
if (continuation.isActive) {
continuation.resume()
}
}
.showOrElse {
if (continuation.isActive) {
continuation.resume()
}
}
}
}
fun createDialogState(id: String? = null, onDismiss: (() -> Unit)? = null, transform: DialogBuilder.() -> Dialog): DialogState =
object : DialogState {
override val id: String?
get() = id
override fun createDialog(activity: Activity, viewModel: WithDialog?) =
DialogBuilder(activity)
.dismissListener {
onDismiss?.invoke()
viewModel?.onDialogDismissed(this)
}
.transform()
}
| mit | d4d6d2e4de9ba39ea00e8ba4726c85ba | 32.319149 | 128 | 0.649425 | 4.987261 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/controlTransfer.kt | 3 | 6780 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.dataFlow
import com.intellij.codeInspection.dataFlow.instructions.Instruction
import com.intellij.codeInspection.dataFlow.value.DfaPsiType
import com.intellij.codeInspection.dataFlow.value.DfaValue
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import com.intellij.codeInspection.dataFlow.value.DfaVariableValue
import com.intellij.psi.*
import com.intellij.util.containers.FList
import java.util.*
/**
* @author peter
*/
class DfaControlTransferValue(factory: DfaValueFactory,
val target: TransferTarget,
val traps: FList<Trap>) : DfaValue(factory) {
override fun toString() = target.toString() + " " + traps.toString()
}
interface TransferTarget
data class ExceptionTransfer(val throwable: DfaPsiType?) : TransferTarget
data class InstructionTransfer(val offset: ControlFlow.ControlFlowOffset, val toFlush: List<DfaVariableValue>) : TransferTarget
object ReturnTransfer : TransferTarget {
override fun toString(): String = "ReturnTransfer"
}
open class ControlTransferInstruction(val transfer: DfaControlTransferValue?) : Instruction() {
override fun accept(runner: DataFlowRunner, state: DfaMemoryState, visitor: InstructionVisitor): Array<out DfaInstructionState> {
return visitor.visitControlTransfer(this, runner, state)
}
fun getPossibleTargetIndices() : List<Int> {
if (transfer == null) return emptyList()
val result = ArrayList(transfer.traps.flatMap(Trap::getPossibleTargets))
if (transfer.target is InstructionTransfer) {
result.add(transfer.target.offset.instructionOffset)
}
return result
}
fun getPossibleTargetInstructions(allInstructions: Array<Instruction>) = getPossibleTargetIndices().map { allInstructions[it] }
override fun toString() = if (transfer == null) "RET" else "TRANSFER " + transfer.toString()
}
sealed class Trap(val anchor: PsiElement) {
class TryCatch(tryStatement: PsiTryStatement, val clauses: LinkedHashMap<PsiCatchSection, ControlFlow.ControlFlowOffset>)
: Trap(tryStatement) {
override fun toString(): String = "TryCatch -> " + clauses.values
}
class TryFinally(finallyBlock: PsiCodeBlock, val jumpOffset: ControlFlow.ControlFlowOffset): Trap(finallyBlock) {
override fun toString(): String = "TryFinally -> " + jumpOffset
}
class TwrFinally(resourceList: PsiResourceList, val jumpOffset: ControlFlow.ControlFlowOffset): Trap(resourceList) {
override fun toString(): String = "TwrFinally -> " + jumpOffset
}
class InsideFinally(finallyBlock: PsiElement): Trap(finallyBlock) {
override fun toString(): String = "InsideFinally"
}
internal fun getPossibleTargets(): Collection<Int> {
return when (this) {
is TryCatch -> clauses.values.map { it.instructionOffset }
is TryFinally -> listOf(jumpOffset.instructionOffset)
is TwrFinally -> listOf(jumpOffset.instructionOffset)
else -> emptyList()
}
}
}
private class ControlTransferHandler(val state: DfaMemoryState, val runner: DataFlowRunner, val target: TransferTarget) {
var throwableState: DfaVariableState? = null
fun iteration(traps: FList<Trap>): List<DfaInstructionState> {
val (head, tail) = traps.head to traps.tail
return when (head) {
null -> transferToTarget()
is Trap.TryCatch -> if (target is ExceptionTransfer) processCatches(head, target.throwable, tail) else iteration(tail)
is Trap.TryFinally -> goToFinally(head.jumpOffset.instructionOffset, tail)
is Trap.TwrFinally -> if (target is ExceptionTransfer) iteration(tail) else goToFinally(head.jumpOffset.instructionOffset, tail)
is Trap.InsideFinally -> leaveFinally(tail)
}
}
private fun transferToTarget(): List<DfaInstructionState> {
return when (target) {
is InstructionTransfer -> {
target.toFlush.forEach { state.flushVariable(it) }
listOf(DfaInstructionState(runner.getInstruction(target.offset.instructionOffset), state))
}
else -> emptyList()
}
}
private fun goToFinally(offset: Int, traps: FList<Trap>): List<DfaInstructionState> {
state.push(runner.factory.controlTransfer(target, traps))
return listOf(DfaInstructionState(runner.getInstruction(offset), state))
}
private fun leaveFinally(traps: FList<Trap>): List<DfaInstructionState> {
state.pop() as DfaControlTransferValue
return iteration(traps)
}
private fun processCatches(tryCatch: Trap.TryCatch, thrownValue: DfaPsiType?, traps: FList<Trap>): List<DfaInstructionState> {
val result = arrayListOf<DfaInstructionState>()
for ((catchSection, jumpOffset) in tryCatch.clauses) {
val param = catchSection.parameter ?: continue
if (throwableState == null) throwableState = initVariableState(param, thrownValue)
for (caughtType in allCaughtTypes(param)) {
throwableState?.withInstanceofValue(caughtType)?.let { varState ->
result.add(DfaInstructionState(runner.getInstruction(jumpOffset.instructionOffset), stateForCatchClause(param, varState)))
}
throwableState = throwableState?.withNotInstanceofValue(caughtType) ?: return result
}
}
return result + iteration(traps)
}
private fun allCaughtTypes(param: PsiParameter): List<DfaPsiType> {
val psiTypes = param.type.let { if (it is PsiDisjunctionType) it.disjunctions else listOfNotNull(it) }
return psiTypes.map { runner.factory.createDfaType(it) }
}
private fun stateForCatchClause(param: PsiParameter, varState: DfaVariableState): DfaMemoryState {
val catchingCopy = state.createCopy() as DfaMemoryStateImpl
catchingCopy.setVariableState(catchingCopy.factory.varFactory.createVariableValue(param, false), varState)
return catchingCopy
}
private fun initVariableState(param: PsiParameter, throwable: DfaPsiType?): DfaVariableState {
val sampleVar = (state as DfaMemoryStateImpl).factory.varFactory.createVariableValue(param, false)
val varState = state.createVariableState(sampleVar).withFact(DfaFactType.CAN_BE_NULL, false)
return if (throwable != null) varState.withInstanceofValue(throwable)!! else varState
}
}
| apache-2.0 | c76a4dee4ca98afbf4ab500353c622ad | 41.911392 | 134 | 0.74528 | 4.402597 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/data/service/MarkerRequest.kt | 1 | 1111 | package com.marverenic.reader.data.service
const val ACTION_READ = "markAsRead"
const val ACTION_UNREAD = "keepUnread"
const val ACTION_SAVE = "markAsSaved"
const val ACTION_UNSAVE = "markAsUnsaved"
private val MARKER_ACTIONS = listOf(ACTION_READ, ACTION_UNREAD, ACTION_SAVE, ACTION_UNSAVE)
sealed class MarkerRequest(action: String) {
abstract val type: String
init {
require(action in MARKER_ACTIONS) { "Invalid action: $action" }
}
}
data class ArticleMarkerRequest(val entryIds: List<String>,
val action: String) : MarkerRequest(action) {
override val type = "entries"
}
data class FeedMarkerRequest(val feedIds: List<String>,
val lastReadEntryId: String,
val action: String) : MarkerRequest(action) {
override val type = "feeds"
}
data class CategoryMarkerRequest(val categoryIds: List<String>,
val lastReadEntryId: String,
val action: String) : MarkerRequest(action) {
override val type = "categories"
}
| apache-2.0 | 659c423856ea426c800364fab7e909ef | 27.487179 | 91 | 0.634563 | 4.256705 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/command/AppendFileCommandAction.kt | 1 | 3267 | // 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 mobi.hsz.idea.gitignore.command
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.psi.IgnoreEntry
import mobi.hsz.idea.gitignore.psi.IgnoreVisitor
import mobi.hsz.idea.gitignore.settings.IgnoreSettings
import mobi.hsz.idea.gitignore.util.ContentGenerator
import mobi.hsz.idea.gitignore.util.Notify
import mobi.hsz.idea.gitignore.util.Utils
/**
* Command action that appends specified file to rules list.
*/
class AppendFileCommandAction(
private val project: Project,
private val file: PsiFile,
private val content: MutableSet<String>,
private val ignoreDuplicates: Boolean = false,
private val ignoreComments: Boolean = false,
) : CommandAction<PsiFile?>(project) {
private val settings = service<IgnoreSettings>()
/**
* Adds [.content] to the given [.file]. Checks if file contains content and sends a notification.
*
* @return previously provided file
*/
@Suppress("ComplexMethod", "LongMethod", "NestedBlockDepth")
override fun compute(): PsiFile {
if (content.isEmpty()) {
return file
}
val manager = PsiDocumentManager.getInstance(project)
manager.getDocument(file)?.let { document ->
var offset = document.textLength
file.acceptChildren(
object : IgnoreVisitor() {
override fun visitEntry(entry: IgnoreEntry) {
val moduleDir = Utils.getModuleRootForFile(file.virtualFile, project)
if (content.contains(entry.text) && moduleDir != null) {
Notify.show(
project,
IgnoreBundle.message("action.appendFile.entryExists", entry.text),
IgnoreBundle.message(
"action.appendFile.entryExists.in",
Utils.getRelativePath(moduleDir, file.virtualFile)
),
NotificationType.WARNING
)
content.remove(entry.text)
}
}
}
)
if (settings.insertAtCursor) {
EditorFactory.getInstance().getEditors(document).firstOrNull()?.let { editor ->
editor.selectionModel.selectionStartPosition?.let { position ->
offset = document.getLineStartOffset(position.line)
}
}
}
val generatedContent = ContentGenerator.generate(document.text, content, ignoreDuplicates, ignoreComments)
document.insertString(offset, generatedContent)
manager.commitDocument(document)
}
return file
}
}
| mit | 441df4e20eb4e92c836f692d1420abe6 | 40.35443 | 140 | 0.610652 | 5.312195 | false | false | false | false |
h0tk3y/better-parse | src/commonTest/kotlin/OptionalTest.kt | 1 | 865 |
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import com.github.h0tk3y.betterParse.parser.*
import com.github.h0tk3y.betterParse.utils.*
import kotlin.test.*
class OptionalTest : Grammar<Nothing>() {
override val rootParser: Parser<Nothing> get() = throw NoSuchElementException()
val a by regexToken("a")
val b by regexToken("b")
@Test fun successful() {
val tokens = tokenizer.tokenize("abab")
val result = optional(a and b and a and b).tryParse(tokens,0)
assertTrue(result.toParsedOrThrow().value is Tuple4)
}
@Test fun unsuccessful() {
val tokens = tokenizer.tokenize("abab")
val result = optional(b and a and b and a).tryParse(tokens,0)
assertNull(result.toParsedOrThrow().value)
}
} | apache-2.0 | 7baa736987f7379ea3d2c3479e894843 | 32.307692 | 83 | 0.699422 | 3.728448 | false | true | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/util/UrlUtil.kt | 2 | 1481 | /*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.util
import java.net.MalformedURLException
import java.net.URL
/**
* Schemes
*/
private const val HTTP_SCHEME = "http://"
const val HTTPS_SCHEME = "https://"
/**
* Remove the http schemes from the URl passed in parameter
*
* @param aUrl URL to be parsed
* @return the URL with the scheme removed
*/
fun removeUrlScheme(aUrl: String?): String? {
var urlRetValue = aUrl
if (null != aUrl) {
// remove URL scheme
if (aUrl.startsWith(HTTP_SCHEME)) {
urlRetValue = aUrl.substring(HTTP_SCHEME.length)
} else if (aUrl.startsWith(HTTPS_SCHEME)) {
urlRetValue = aUrl.substring(HTTPS_SCHEME.length)
}
}
return urlRetValue
}
fun extractDomain(aUrl: String?): String? {
try {
return aUrl?.let { URL(it).host }
} catch (e : MalformedURLException) {
return null
}
} | apache-2.0 | 3538a9f4c1febc25ae306bff90804ce8 | 25.945455 | 75 | 0.673194 | 3.81701 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/settings/fingerprint/FingerprintSettings.kt | 1 | 2458 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 10/25/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.settings.fingerprint
import com.breadwallet.tools.util.BRConstants
import com.breadwallet.ui.navigation.NavigationEffect
import com.breadwallet.ui.navigation.NavigationTarget
object FingerprintSettings {
data class M(
val unlockApp: Boolean = false,
val sendMoney: Boolean = false,
val sendMoneyEnable: Boolean = false
)
sealed class E {
object OnBackClicked : E()
object OnFaqClicked : E()
data class OnAppUnlockChanged(val enable: Boolean) : E()
data class OnSendMoneyChanged(val enable: Boolean) : E()
data class OnSettingsLoaded(
val unlockApp: Boolean,
val sendMoney: Boolean
) : E()
}
sealed class F {
object LoadCurrentSettings : F()
data class UpdateFingerprintSetting(
val unlockApp: Boolean,
val sendMoney: Boolean
) : F()
object GoBack : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.Back
}
object GoToFaq : F(), NavigationEffect {
override val navigationTarget =
NavigationTarget.SupportPage(BRConstants.FAQ_ENABLE_FINGERPRINT)
}
}
}
| mit | 52bc8f73c582d4cd0b145557da25b9c6 | 36.815385 | 80 | 0.697722 | 4.655303 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/auth/User.kt | 2 | 1282 | package org.fossasia.openevent.general.auth
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming
import com.github.jasminb.jsonapi.IntegerIdHandler
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Type
@Type("user")
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class)
@Entity
data class User(
@Id(IntegerIdHandler::class)
@PrimaryKey
val id: Long,
val firstName: String? = null,
val lastName: String? = null,
val email: String? = null,
val contact: String? = null,
val details: String? = null,
val thumbnailImageUrl: String? = null,
val iconImageUrl: String? = null,
val smallImageUrl: String? = null,
val avatarUrl: String? = null,
val facebookUrl: String? = null,
val twitterUrl: String? = null,
val instagramUrl: String? = null,
val googlePlusUrl: String? = null,
val originalImageUrl: String? = null,
val isVerified: Boolean = false,
val isAdmin: Boolean? = false,
val isSuperAdmin: Boolean? = false,
val createdAt: String? = null,
val lastAccessedAt: String? = null,
val deletedAt: String? = null
)
| apache-2.0 | c49241829ad17ab3c745aff26a27a1a7 | 31.871795 | 60 | 0.723869 | 3.838323 | false | false | false | false |
legua25/android-course | course-calculator/app/src/main/kotlin/gg/course/calculator/CalculatorActivity.kt | 1 | 3985 | package gg.course.calculator
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import gg.course.calculator.views.query
import gg.course.calculator.views.tag
import android.support.v7.app.AppCompatActivity as Activity
class CalculatorActivity : Activity() {
// We must keep track of which numbers are we using and what operation to perform next
// The initial operation, therefore, is to select the latest number
private var operation: (Double, Double) -> Double = { a, b -> b }
private var last: Double = 0.0
override fun onCreate(saved_instance: Bundle?) {
super.onCreate(saved_instance)
this.setContentView(R.layout.main)
val result = this.findViewById(0) as TextView // TODO: Replace "0" with the ID of this component
// Give all numbers from "1" to "9" listeners (using our view query library)
val panel = this.findViewById(1) // TODO: Replace "1" with the ID of this component
panel.query(tag to "number").each({ view, position ->
// Set a click listener to update the number on screen
if (view is Button) view.setOnClickListener({
val text = result.text.toString()
// If the number is "0", we can eagerly remove it
if (text == "0") result.text = view.text
else result.text = "${text}${view.text}"
})
})
// Set listener for the "0" key
// TODO: Replace "2" with the ID of this component
(this.findViewById(2) as Button).setOnClickListener({
// Zero is a curious number - it will only be added if there is anything else than "0" as the current number
if (result.text != "0") result.text = "${result.text}0"
})
// Set the dot (".") key listener
// TODO: Replace "3" with the ID of this component
(this.findViewById(3) as Button).setOnClickListener({
// Dot may only be added if it has not been added before
if ("." !in result.text) result.text = "${result.text}."
})
// Set the clear key listener
// TODO: Replace "4" with the ID of this component
(this.findViewById(4) as Button).setOnClickListener({
// We must reset the text AND the operator
result.text = "0"
this.operation = { a, b -> b }
})
// Now, set up each operator by itself
// TODO: For each element, replace the numbers "5" to "9" with the ID of each components
(this.findViewById(5) as Button).setOnClickListener({
// Convert the current number from text to an actual number
val number = (result.text.toString()).toDouble()
// Perform first the previous operation, then specify the operation to apply next
this.last = this.operation(this.last, number)
this.operation = { a, b -> a + b }
// Reset the text to "0"
result.text = "0"
})
(this.findViewById(6) as Button).setOnClickListener({
val number = (result.text.toString()).toDouble()
this.last = this.operation(this.last, number)
this.operation = { a, b -> a - b }
result.text = "0"
})
(this.findViewById(7) as Button).setOnClickListener({
val number = (result.text.toString()).toDouble()
this.last = this.operation(this.last, number)
this.operation = { a, b -> a * b }
result.text = "0"
})
(this.findViewById(8) as Button).setOnClickListener({
val number = (result.text.toString()).toDouble()
this.last = this.operation(this.last, number)
// Remember dividing by zero causes black holes according to Internet culture, so we
// should spare the world from these
this.operation = { a, b ->
if (b.isFinite() && b != 0.0) a / b else Double.NaN
}
result.text = "0"
})
(this.findViewById(9) as Button).setOnClickListener({
// Convert the current number from text to an actual number
val number = (result.text.toString()).toDouble()
// Perform first the previous operation, then specify that the next valid value comes from this result
this.last = this.operation(this.last, number)
this.operation = { a, b -> a }
// Set the on-screen number to the result
result.text = this.last.toString()
})
}
}
| mit | 9ff247dac9dda29fb9f5821a14fd00b1 | 31.398374 | 111 | 0.679799 | 3.529672 | false | false | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/search/impact/impactinfocollection/numeric/BoolenGeneTest.kt | 1 | 2445 | package org.evomaster.core.search.impact.impactinfocollection.numeric
import org.evomaster.core.search.gene.BooleanGene
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.GeneImpactTest
import org.evomaster.core.search.impact.impactinfocollection.ImpactOptions
import org.evomaster.core.search.impact.impactinfocollection.MutatedGeneWithContext
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.BinaryGeneImpact
import org.junit.jupiter.api.Test
/**
* created by manzh on 2019-10-08
*/
class BoolenGeneTest : GeneImpactTest() {
override fun simulateMutation(original: Gene, geneToMutate: Gene, mutationTag: Int): MutatedGeneWithContext {
geneToMutate as BooleanGene
geneToMutate.value = !geneToMutate.value
return MutatedGeneWithContext(previous = original, current = geneToMutate)
}
override fun getGene(): Gene = BooleanGene("i", value= false)
override fun checkImpactType(impact: GeneImpact) {
assert(impact is BinaryGeneImpact)
}
@Test
fun testT2F(){
val gene = BooleanGene("b", value= true)
val impact = initImpact(gene)
val updatedImpact = template( gene, impact, listOf(ImpactOptions.NO_IMPACT)).second
assertImpact((impact as BinaryGeneImpact).falseValue, (updatedImpact as BinaryGeneImpact).falseValue, ImpactOptions.NO_IMPACT)
}
@Test
fun testF2T(){
val gene = BooleanGene("b", value= false)
val impact = initImpact(gene)
val updatedImpact = template( gene, impact, listOf(ImpactOptions.IMPACT_IMPROVEMENT)).second
assertImpact((impact as BinaryGeneImpact).trueValue, (updatedImpact as BinaryGeneImpact).trueValue, ImpactOptions.IMPACT_IMPROVEMENT)
}
@Test
fun testF2T2F(){
val gene = BooleanGene("b", value= false)
val impact = initImpact(gene)
val pair = template( gene, impact, listOf(ImpactOptions.IMPACT_IMPROVEMENT))
assertImpact((impact as BinaryGeneImpact).trueValue, (pair.second as BinaryGeneImpact).trueValue, ImpactOptions.IMPACT_IMPROVEMENT)
val upair = template(pair.first, pair.second, listOf(ImpactOptions.NO_IMPACT))
assertImpact((pair.second as BinaryGeneImpact).falseValue, (upair.second as BinaryGeneImpact).falseValue, ImpactOptions.NO_IMPACT)
}
} | lgpl-3.0 | 9dff698447a2a89e7d35f2e1c91d5c89 | 41.912281 | 141 | 0.745194 | 4.397482 | false | true | false | false |
jmiecz/YelpBusinessExample | app/src/main/java/net/mieczkowski/yelpbusinessexample/recyclerAdapters/searchBusiness/SearchBusinessViewHolder.kt | 1 | 2018 | package net.mieczkowski.yelpbusinessexample.recyclerAdapters.searchBusiness
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import kotlinx.android.synthetic.main.row_seach_business.view.*
import net.mieczkowski.dal.services.businessLookupService.models.YelpBusiness
import net.mieczkowski.yelpbusinessexample.R
import net.mieczkowski.yelpbusinessexample.exts.loadUrl
import net.mieczkowski.yelpbusinessexample.recyclerAdapters.base.BaseViewHolder
/**
* Created by Josh Mieczkowski on 10/22/2017.
*/
class SearchBusinessViewHolder(itemView: View) : BaseViewHolder<YelpBusiness>(itemView) {
val imgIcon: ImageView = itemView.imgIcon
val txtTitle: TextView = itemView.txtTitle
val txtRatings: TextView = itemView.txtRatings
val txtReviewCount: TextView = itemView.txtReviewCount
init {
ContextCompat.getDrawable(itemView.context, R.drawable.ic_star_rate_white_18dp)?.let {
val ratingsDrawable = DrawableCompat.wrap(it)
DrawableCompat.setTint(ratingsDrawable, Color.parseColor("#FFD700"))
txtRatings.setCompoundDrawablesWithIntrinsicBounds(ratingsDrawable, null, null, null)
}
ContextCompat.getDrawable(itemView.context, R.drawable.ic_edit_black_18dp)?.let {
val reviewCountDrawable = DrawableCompat.wrap(it)
DrawableCompat.setTint(reviewCountDrawable, Color.parseColor("#A9A9A9"))
txtReviewCount.setCompoundDrawablesWithIntrinsicBounds(reviewCountDrawable, null, null, null)
}
}
override fun onBind(item: YelpBusiness?) {
item?.let {
imgIcon.loadUrl(it.businessDetails?.imgUrl)
txtTitle.text = it.name
txtRatings.text = it.businessDetails?.rating.toString()
txtReviewCount.text = it.businessDetails?.reviewCount.toString()
}
}
}
| apache-2.0 | 8345b6083758d643b51da500f86f385b | 36.37037 | 105 | 0.747275 | 4.565611 | false | false | false | false |
42SK/TVKILL | app/src/main/java/com/redirectapps/tvkill/TransmitService.kt | 1 | 13979 | /**
* Copyright (C) 2018 Jonas Lochmann
* Copyright (C) 2018 Sebastian Kappes
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.redirectapps.tvkill
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.*
import android.preference.PreferenceManager.getDefaultSharedPreferences
import android.support.v4.app.NotificationCompat
import android.support.v4.os.CancellationSignal
import com.redirectapps.tvkill.widget.UpdateWidget
import java.io.Serializable
import java.util.concurrent.Executors
class TransmitService : Service() {
// helper method for starting
companion object {
private const val EXTRA_REQUEST = "request"
private const val NOTIFICATION_ID = 1
const val NOTIFICATION_CHANNEL = "report running in background"
private val handler = Handler(Looper.getMainLooper())
private val isAppInForeground = MutableLiveData<Boolean>()
val status = MutableLiveData<TransmitServiceStatus>()
init {
status.value = null
isAppInForeground.value = false
}
val subscribeIfRunning = object : LiveData<Void>() {
override fun onActive() {
super.onActive()
isAppInForeground.value = true
}
override fun onInactive() {
super.onInactive()
isAppInForeground.value = false
}
}
fun executeRequest(request: TransmitServiceRequest, context: Context) {
context.startService(buildIntent(request, context))
}
fun buildIntent(request: TransmitServiceRequest, context: Context): Intent {
return Intent(context, TransmitService::class.java)
.putExtra(EXTRA_REQUEST, request)
}
}
private var verboseInformation: Boolean = false
// detection if bound (used for showing/ hiding notification)
private var cancel = CancellationSignal()
private val executor = Executors.newSingleThreadExecutor()
private lateinit var wakeLock: PowerManager.WakeLock
private var isNotificationVisible = false
private lateinit var notificationBuilder: NotificationCompat.Builder
private lateinit var notificationManager: NotificationManager
private val statusObserver = Observer<TransmitServiceStatus> {
updateNotification()
UpdateWidget.updateAllWidgets(this)
}
private var stopped = false
private var pendingRequests = 0
override fun onCreate() {
super.onCreate()
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TransmitService")
val cancelIntent = buildIntent(TransmitServiceCancelRequest, this)
val pendingCancelIntent = PendingIntent.getService(this, PendingIntents.NOTIFICATION_CANCEL, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT)
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL)
.setOngoing(true)
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_power_settings_new_white_48dp)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
// this is set later (depending on the status)
// .setContentTitle(getString(R.string.mode_running))
.setOnlyAlertOnce(true)
.setProgress(100, 0, true)
.addAction(R.drawable.ic_clear_black_48dp, getString(R.string.stop), pendingCancelIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// setup notification channel (system ignores it if already registered)
val channel = NotificationChannel(
NOTIFICATION_CHANNEL,
getString(R.string.toast_transmission_initiated),
NotificationManager.IMPORTANCE_DEFAULT
)
channel.setSound(null, null)
channel.vibrationPattern = null
channel.setShowBadge(false)
channel.enableLights(false)
notificationManager.createNotificationChannel(channel)
}
status.observeForever(statusObserver)
isAppInForeground.observeForever {
updateNotification()
}
wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/)
}
override fun onDestroy() {
super.onDestroy()
wakeLock.release()
status.removeObserver(statusObserver)
cancel()
status.value = null
stopped = true
UpdateWidget.updateAllWidgets(this)
stopForeground(true)
//Dismiss the progress dialog (if present)
if (MainActivity.progressDialog != null) {
try {
MainActivity.progressDialog.dismiss()
} catch (e: IllegalArgumentException) {
//On Android 8.1, the OS apparently sometimes throws this exception due to some internal bug (this is not our fault)
e.printStackTrace()
}
MainActivity.progressDialog = null
}
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
// managing of current running things
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val request = intent!!.getSerializableExtra(EXTRA_REQUEST) as TransmitServiceRequest
val cancel = this.cancel
if (request is TransmitServiceSendRequest) {
// there is no lock because the selected executor only executes one task per time
pendingRequests++
executor.submit {
fun execute() {
if (request.brandName == null) {
if (request.action == TransmitServiceAction.Off) {
verboseInformation = getDefaultSharedPreferences(this).getBoolean("show_verbose", false)
// check if additional patterns should be transmitted
var depth = 1
if (Settings.with(this).additionalPatterns.value!!) {
depth = BrandContainer.allBrands.map { it.patterns.size }.max()!!
}
val numOfPatterns = BrandContainer.allBrands.sumBy {
Math.min(it.patterns.size, depth)
}
var transmittedPatterns = 0
// transmit all patterns
for (i in 0 until depth) {
for (brand in BrandContainer.allBrands) {
if (cancel.isCanceled) {
break
}
if (i < brand.patterns.size) {
if (!request.forever) {
status.postValue(TransmitServiceStatus(
request,
TransmitServiceProgress(transmittedPatterns++, numOfPatterns)
))
}
brand.patterns[i].send(this)
Brand.wait(this)
}
}
}
} else if (request.action == TransmitServiceAction.Mute) {
var transmittedPatterns = 0
val numOfPatterns = BrandContainer.allBrands.size
for (brand in BrandContainer.allBrands) {
if (cancel.isCanceled) {
break
}
if (!request.forever) {
status.postValue(TransmitServiceStatus(
request,
TransmitServiceProgress(transmittedPatterns++, numOfPatterns)
))
}
brand.mute(this)
}
} else {
throw IllegalStateException()
}
} else {
val brand = BrandContainer.brandByDesignation[request.brandName]
?: throw IllegalStateException()
when {
request.action == TransmitServiceAction.Off -> brand.kill(this)
request.action == TransmitServiceAction.Mute -> brand.mute(this)
else -> throw IllegalStateException()
}
}
}
try {
status.postValue(TransmitServiceStatus(request, null)) // inform about this request
if (request.forever) {
while (!cancel.isCanceled) {
execute()
}
} else {
execute()
}
} finally {
handler.post {
if (--pendingRequests == 0) {
status.value = null // nothing is running
stopSelf()
} else {
// status will be changed very soon
}
}
}
}
} else if (request is TransmitServiceCancelRequest) {
cancel()
} else {
throw IllegalStateException()
}
return START_NOT_STICKY
}
private fun cancel() {
cancel.cancel()
// create a new signal for next cancelling
cancel = CancellationSignal()
}
private fun updateNotification() {
if (stopped) {
return
}
val request = status.value
val appRunning = isAppInForeground.value
if (appRunning!!) {
if (isNotificationVisible) {
stopForeground(true)
isNotificationVisible = false
}
} else {
if (request == null)
return
if (request.request.forever) {
notificationBuilder.setContentTitle(getString(R.string.mode_running))
notificationBuilder.setProgress(100, 0, true)
} else {
notificationBuilder.setContentTitle(getString(R.string.toast_transmission_initiated))
if (request.progress != null) {
notificationBuilder.setProgress(request.progress.max, request.progress.current, false)
//Also update the progress dialog (if present)
if (MainActivity.progressDialog != null) {
MainActivity.progressDialog.max = request.progress.max
MainActivity.progressDialog.progress = request.progress.current + 1
if (verboseInformation)
try {
MainActivity.progressDialog.setProgressNumberFormat(BrandContainer.allBrands[request.progress.current].designation.capitalize() + " (%1d/%2d)")
} catch (e: ArrayIndexOutOfBoundsException) {
//There is no obvious reason why this exception should occur, but, according to crash reports from Google Play, it does happen.
e.printStackTrace()
}
}
}
}
if (isNotificationVisible) {
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
} else {
startForeground(NOTIFICATION_ID, notificationBuilder.build())
isNotificationVisible = true
}
}
}
}
sealed class TransmitServiceRequest : Serializable
class TransmitServiceSendRequest(val action: TransmitServiceAction, val forever: Boolean, val brandName: String?) : TransmitServiceRequest()
object TransmitServiceCancelRequest : TransmitServiceRequest()
enum class TransmitServiceAction {
Off, Mute
}
data class TransmitServiceProgress(val current: Int, val max: Int)
class TransmitServiceStatus(val request: TransmitServiceSendRequest, val progress: TransmitServiceProgress?) | gpl-3.0 | 89d8933f13313413701ae835331a3a96 | 38.942857 | 175 | 0.556764 | 5.868598 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/settings/presentation/SettingsPresenter.kt | 2 | 7784 | package chat.rocket.android.settings.presentation
import android.content.Context
import android.os.Build
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.dynamiclinks.DynamicLinksForFirebase
import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.main.presentation.MainNavigator
import chat.rocket.android.push.retrieveCurrentPushNotificationToken
import chat.rocket.android.server.domain.AnalyticsTrackingInteractor
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.PermissionsInteractor
import chat.rocket.android.server.domain.RemoveAccountInteractor
import chat.rocket.android.server.domain.SaveCurrentLanguageInteractor
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.extension.HashType
import chat.rocket.android.util.extension.hash
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.adminPanelUrl
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.invalidateFirebaseToken
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.util.ifNull
import chat.rocket.core.internal.rest.deleteOwnAccount
import chat.rocket.core.internal.rest.logout
import chat.rocket.core.internal.rest.me
import chat.rocket.core.internal.rest.serverInfo
import chat.rocket.core.model.Myself
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.*
import javax.inject.Inject
import javax.inject.Named
class SettingsPresenter @Inject constructor(
private val view: SettingsView,
private val strategy: CancelStrategy,
private val navigator: MainNavigator,
@Named("currentServer") private val currentServer: String?,
private val analyticsTrackingInteractor: AnalyticsTrackingInteractor,
private val tokenRepository: TokenRepository,
private val permissions: PermissionsInteractor,
private val rocketChatClientFactory: RocketChatClientFactory,
private val dynamicLinksManager: DynamicLinksForFirebase,
private val saveLanguageInteractor: SaveCurrentLanguageInteractor,
private val serverInteractor: GetCurrentServerInteractor,
private val localRepository: LocalRepository,
private val connectionManagerFactory: ConnectionManagerFactory,
private val removeAccountInteractor: RemoveAccountInteractor,
private val dbManagerFactory: DatabaseManagerFactory
) {
private val token = currentServer?.let { tokenRepository.get(it) }
private lateinit var me: Myself
fun setupView() {
launchUI(strategy) {
try {
view.showLoading()
currentServer?.let { serverUrl ->
val serverInfo = retryIO(description = "serverInfo", times = 5) {
rocketChatClientFactory.get(serverUrl).serverInfo()
}
me = retryIO(description = "me", times = 5) {
rocketChatClientFactory.get(serverUrl).me()
}
me.username?.let { username ->
view.setupSettingsView(
serverUrl.avatarUrl(username, token?.userId, token?.authToken),
username,
me.status.toString(),
permissions.isAdministrationEnabled(),
analyticsTrackingInteractor.get(),
true,
serverInfo.version
)
}
}
} catch (exception: Exception) {
Timber.d(exception, "Error getting server info")
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun enableAnalyticsTracking(isEnabled: Boolean) {
analyticsTrackingInteractor.save(isEnabled)
}
fun deleteAccount(password: String) {
launchUI(strategy) {
view.showLoading()
try {
currentServer?.let { currentServer ->
withContext(Dispatchers.Default) {
// REMARK: Backend API is only working with a lowercase hash.
// https://github.com/RocketChat/Rocket.Chat/issues/12573
rocketChatClientFactory.get(currentServer)
.deleteOwnAccount(password.hash(HashType.Sha256).toLowerCase())
logout()
}
}
} catch (exception: Exception) {
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun getCurrentLocale(context: Context): Locale {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.resources.configuration.locales.get(0)
} else {
context.resources.configuration.locale
}
}
fun saveLocale(language: String, country: String? = null) {
saveLanguageInteractor.save(language, country)
}
fun toProfile() = navigator.toProfile()
fun toAdmin() = currentServer?.let { currentServer ->
tokenRepository.get(currentServer)?.let {
navigator.toAdminPanel(currentServer.adminPanelUrl(), it.authToken)
}
}
fun toLicense(licenseUrl: String, licenseTitle: String) =
navigator.toLicense(licenseUrl, licenseTitle)
fun prepareShareApp() {
launchUI(strategy) {
val deepLinkCallback = { returnedString: String? ->
view.openShareApp(returnedString)
}
currentServer?.let { currentServer ->
me.username?.let { username ->
dynamicLinksManager.createDynamicLink(username, currentServer, deepLinkCallback)
}
}
}
}
fun recreateActivity() = navigator.recreateActivity()
/**
* Logout the user from the current server.
*/
fun logout() {
launchUI(strategy) {
try {
currentServer?.let { currentServer ->
rocketChatClientFactory.get(currentServer).let { client ->
retrieveCurrentPushNotificationToken(client, true)
tokenRepository.remove(currentServer)
serverInteractor.clear()
localRepository.clearAllFromServer(currentServer)
removeAccountInteractor.remove(currentServer)
withContext(Dispatchers.IO) {
invalidateFirebaseToken()
dbManagerFactory.create(currentServer)?.logout()
}
connectionManagerFactory.create(currentServer)?.disconnect()
client.logout()
navigator.switchOrAddNewServer()
}
}
} catch (exception: RocketChatException) {
Timber.e(exception, "Error while trying to logout")
}
}
}
}
| mit | 90b661ef112bf634a392f456bc5e096b | 38.917949 | 100 | 0.626542 | 5.306067 | false | false | false | false |
tommykw/SeekBar | AS/app/src/main/java/com/github/tommykw/as/scenes/CubeScene.kt | 1 | 1811 | package com.github.tommykw.`as`.scenes
import android.content.Context
import jmini3d.Color4
import jmini3d.Object3d
import jmini3d.Scene
import jmini3d.Vector3
import jmini3d.geometry.BoxGeometry
import jmini3d.light.AmbientLight
import jmini3d.light.PointLight
import jmini3d.material.PhongMaterial
import java.util.*
import kotlin.properties.Delegates
class CubeScene : Scene {
private var o3d: Object3d by Delegates.notNull()
private var angle = 0f
constructor(context: Context) {
camera.apply {
setPosition(0f, 0f, 0f)
setTarget(camera.position.x, camera.position.y, camera.position.z - 1f)
setUpAxis(0f, 1f, 0f)
}
val random = Random()
addLight(AmbientLight(Color4(255, 255, 255), 0f))
addLight(PointLight(Vector3(0f, 0f, 0f), Color4(255, 255, 255), 1.1f))
val ambient = Color4(255, 255, 255, 255)
val red = Color4(255, 0, 0, 255)
val green = Color4(0, 255, 0, 255)
val blue = Color4(0, 0, 255, 255)
val material1 = PhongMaterial(ambient, red, red)
val material2 = PhongMaterial(ambient, green, green)
val material3 = PhongMaterial(ambient, blue, blue)
val geometry = BoxGeometry(1.5f)
for (i in 1..5) {
for (x in 1..5) {
val x = (i - 3) * 4
val y = (x - 3) * 4
val z = -25
val o3d: Object3d = if ((i + x) % 2 == 0)
Object3d(geometry, material1)
else
Object3d(geometry, material2)
o3d.setPosition(x.toFloat(), y.toFloat(), z.toFloat())
addChild(o3d)
}
}
}
fun update(timeElapsed: Long) {
angle += (0.001 * timeElapsed).toFloat()
}
} | apache-2.0 | f87a0991ece6459e3865d154a0c334b3 | 29.2 | 83 | 0.580342 | 3.436433 | false | false | false | false |
vjache/klips | src/main/java/org/klips/engine/rete/db/BindingDB.kt | 1 | 674 | package org.klips.engine.rete.db
import org.klips.dsl.Facet
import org.klips.engine.Binding
class BindingDB(val dbId: Int, val base:Binding) : Binding(){
override val entries: Set<Map.Entry<Facet<*>, Facet<*>>>
get() = base.entries
override val keys: Set<Facet<*>>
get() = base.keys
override val size: Int
get() = base.size
override val values: Collection<Facet<*>>
get() = base.values
override fun containsKey(key: Facet<*>) = base.containsKey(key)
override fun containsValue(value: Facet<*>) = base.containsValue(value)
override fun get(key: Facet<*>) = base[key]
override fun isEmpty() = base.isEmpty()
} | apache-2.0 | 6bc1f9edea4bd158a43962c1269c754c | 32.75 | 75 | 0.658754 | 3.895954 | false | false | false | false |
dmcg/hamkrest | src/main/kotlin/com/natpryce/hamkrest/string_matchers.kt | 1 | 7277 | @file:JvmName("StringMatchers")
package com.natpryce.hamkrest
import kotlin.reflect.KFunction3
/**
* The case sensitivity of a [StringMatcher].
*
* A case sensitive [StringMatcher] can be converted into a case insensitive equivalent by calling
* [StringMatcher.caseSensitive], and a case insensitive [StringMatcher] can be converted into a
* case sensitive equivalent by calling [StringMatcher.caseInsensitive].
*
* By convention, [StringMatcher]s are case sensitive by default.
*
* The [StringMatcher] type is parameterised by case sensitivity, so it is possible to enforce
* at compile time whether a match should be case sensitive or not.
*/
sealed class CaseSensitivity {
/**
* Indicates that the match is case sensitive.
*/
object CaseSensitive : CaseSensitivity()
/**
* Indicates that the match is case insensitive.
*/
object CaseInsensitive : CaseSensitivity()
}
/**
* A Matcher of strings with a specified case sensitivity.
*
* A case insensitive version of a case sensitive matcher can be obtained by calling its [caseInsensitive] method,
* and a case sensitive version of a case insensitive matcher can be obtained by calling its [caseSensitive] method.
*
* If desired, case sensitivity can be enforced at compile time, by requiring a
* `StringMatcher<CaseSensitivity.CaseInsensitive>` or `StringMatcher<CaseSensitivity.CaseSensitive>`.
* If case sensitivity does not need to be enforced, require a `Matcher<String>`.
*
* @property caseSensitivity The case sensitivity of the match, either [CaseSensitivity.CaseSensitive] or [CaseSensitivity.CaseInsensitive].
*/
abstract class StringMatcher<S : CaseSensitivity>(protected val caseSensitivity: S) : Matcher.Primitive<CharSequence>() {
/**
* Returns this matcher transformed to have the given case sensitivity.
*/
abstract internal fun <S2 : CaseSensitivity> withCaseSensitivity(newSensitivity: S2): StringMatcher<S2>
companion object {
/**
* Convert a String predicate to a [StringMatcher], specifying the desired case sensitivity.
*
* The predicate must have the signature `(CharSequence, T, Boolean) -> Boolean`, where the final Boolean
* argument indicates case sensitivity.
*/
operator fun <T, S : CaseSensitivity> invoke(fn: KFunction3<CharSequence, T, Boolean, Boolean>, expected: T, sensitivity: S): StringMatcher<S> {
return object : StringMatcher<S>(sensitivity) {
override fun <S2 : CaseSensitivity> withCaseSensitivity(newSensitivity: S2) =
StringMatcher(fn, expected, newSensitivity)
override val description: String get() =
"${identifierToDescription(fn.name)} ${describe(expected)}${suffix(caseSensitivity)}"
override val negatedDescription: String get() =
"${identifierToNegatedDescription(fn.name)} ${describe(expected)}${suffix(caseSensitivity)}"
override fun invoke(actual: CharSequence) =
match(fn(actual, expected, ignoreCase)) { "was: ${describe(actual)}" }
}
}
/**
* Convert a String predicate to a case sensitive [StringMatcher].
*
* The predicate must have the signature `<T> (CharSequence, T, Boolean) -> Boolean`, where the final Boolean
* argument indicates case sensitivity.
*/
operator fun <T> invoke(fn: KFunction3<CharSequence, T, Boolean, Boolean>, expected: T) =
invoke(fn, expected, CaseSensitivity.CaseSensitive)
}
/**
* Should the match ignore case (be case insensitive)?
*/
protected val ignoreCase: Boolean get() = caseSensitivity == CaseSensitivity.CaseInsensitive
/**
* A suffix to add to the description of a string matcher to indicate case sensitivity.
*/
protected fun suffix(s: CaseSensitivity) = when (s) {
CaseSensitivity.CaseSensitive -> ""
CaseSensitivity.CaseInsensitive -> " (case insensitive)"
}
}
/**
* Returns a case sensitive version of a case insensitive [StringMatcher].
*/
fun StringMatcher<CaseSensitivity.CaseInsensitive>.caseSensitive() = withCaseSensitivity(CaseSensitivity.CaseSensitive)
/**
* Returns a case insensitive version of a case sensitive [StringMatcher].
*/
fun StringMatcher<CaseSensitivity.CaseSensitive>.caseInsensitive() = withCaseSensitivity(CaseSensitivity.CaseInsensitive)
/**
* Matches a char sequence if it contain the given [Regex].
*
* @see [String.contains]
*/
fun contains(r: Regex): Matcher<String> = Matcher(::_contains, r)
private fun _contains(s: CharSequence, regex: Regex): Boolean = regex.containsMatchIn(s)
/**
* Matches a char sequence if it all characters matches the given [Regex].
*
* @see [String.matches]
*/
fun matches(r: Regex): Matcher<CharSequence> = Matcher(CharSequence::matches, r)
/**
* Matches a char sequence if it starts with [prefix].
*
* A case insensitive version can be obtained by calling [StringMatcher.caseInsensitive].
*/
fun startsWith(prefix: CharSequence) = StringMatcher(CharSequence::_startsWith, prefix)
private fun CharSequence._startsWith(prefix: CharSequence, ignoreCase: Boolean) =
this.startsWith(prefix, ignoreCase)
/**
* Matches a char sequence if it ends with [suffix].
*
* A case insensitive version can be obtained by calling [StringMatcher.caseInsensitive].
*/
fun endsWith(suffix: CharSequence) = StringMatcher(CharSequence::_endsWith, suffix)
private fun CharSequence._endsWith(prefix: CharSequence, ignoreCase: Boolean) =
this.endsWith(prefix, ignoreCase)
/**
* Matches a char sequence if it contains [substring].
*
* A case insensitive version can be obtained by calling [StringMatcher.caseInsensitive].
*/
fun containsSubstring(substring: CharSequence) = StringMatcher(CharSequence::_containsSubstring, substring)
private fun CharSequence._containsSubstring(substring: CharSequence, ignoreCase: Boolean) =
this.contains(substring, ignoreCase)
/**
* Matches a char sequence if it is empty or consists solely of whitespace characters.
*/
@JvmField
val isBlank = Matcher(CharSequence::isBlank)
/**
* Matches a nullable char sequence if it is either `null` or empty or consists solely of whitespace characters.
*/
@JvmField
val isNullOrBlank = Matcher(CharSequence::isNullOrBlank)
/**
* Matches a char sequence if it is empty (contains no characters).
*/
@JvmField
val isEmptyString = Matcher(CharSequence::isEmpty)
/**
* Matches a char sequence if it is either `null` or empty (contains no characters).
*/
@JvmField
val isNullOrEmptyString = Matcher(CharSequence::isNullOrEmpty)
/**
* Matches a string if it is the same as the given string, ignoring case differences.
*/
fun equalToIgnoringCase(expected: String?): Matcher<String?> =
object : Matcher<String?> {
override fun invoke(actual: String?): MatchResult = match(actual.equals(expected, ignoreCase = true)) { "was: ${describe(actual)}" }
override val description: String get() = "is equal (ignoring case) to ${describe(expected)}"
override val negatedDescription: String get() = "is not equal (ignoring case) to ${describe(expected)}"
} | apache-2.0 | 3b22af94ae9d8d57ce4dabb59fc0d841 | 38.989011 | 152 | 0.708809 | 4.57673 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/values/TimeData.kt | 1 | 2498 | package edu.kit.iti.formal.automation.datatypes.values
/*-
* #%L
* iec61131lang
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
/**
* Created by weigl on 11.06.14.
*
* @author weigl
* @version $Id: $Id
*/
import java.math.BigDecimal
import java.util.regex.Pattern
data class TimeData(var internal: BigDecimal = BigDecimal.ZERO) {
val milliseconds: Long
get() = internal.toLong()
val seconds: Long
get() = 0
val minutes: Long
get() = 0
val hours: Long
get() = 0
val days: Long
get() = 0
constructor(textValue: String) : this() {
var textValue = textValue
textValue = textValue.replace("_", "")
val extractNumbers = Pattern.compile("([.0-9]+)([hmsd]{1,2})")
val matcher = extractNumbers.matcher(textValue)
while (matcher.find()) {
val num = matcher.group(1)
val mod = matcher.group(2)
val factor = getModifier(mod)
internal = internal.add(BigDecimal.valueOf(factor * java.lang.Double.parseDouble(num)))
}
}
constructor(time: Double) : this() {
internal = BigDecimal.valueOf(time)
}
private fun getModifier(mod: String): Double {
when (mod) {
"d" -> return FACTOR_DAY.toDouble()
"h" -> return FACTOR_HOUR.toDouble()
"m" -> return FACTOR_MINUTE.toDouble()
"s" -> return FACTOR_SECONDS.toDouble()
"ms" -> return FACTOR_MILLISECONDS.toDouble()
else -> return 0.0
}
}
companion object {
val FACTOR_MILLISECONDS = 1
val FACTOR_SECONDS = 1000 * FACTOR_MILLISECONDS
val FACTOR_MINUTE = 60 * FACTOR_SECONDS
val FACTOR_HOUR = 60 * FACTOR_MINUTE
val FACTOR_DAY = 24 * FACTOR_HOUR
}
}
| gpl-3.0 | 1fe0f60f3824c2aab10cfa09f8de042c | 27.712644 | 99 | 0.619295 | 3.940063 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/operators/Operators.kt | 1 | 2736 | package edu.kit.iti.formal.automation.operators
/*-
* #%L
* iec61131lang
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.automation.datatypes.AnyBit
import edu.kit.iti.formal.automation.datatypes.AnyNum
/**
* Facade.
*
*
*
*
*
* Created on 24.11.16.
*
* @author Alexander Weigl
* @version 1
*/
object Operators {
val NOT = UnaryOperator("NOT", AnyBit.BOOL)
val MINUS = UnaryOperator("-", AnyNum.ANY_NUM)
val ADD = BinaryOperator("+", AnyNum.ANY_NUM)
val MULT = BinaryOperator("*", AnyNum.ANY_NUM)
val SUB = BinaryOperator("-", AnyNum.ANY_NUM)
val DIV = BinaryOperator("/", AnyNum.ANY_NUM)
val MOD = BinaryOperator("MOD", AnyNum.ANY_NUM)
val AND = BooleanOperator("AND")
val OR = BooleanOperator("OR")
val XOR = BooleanOperator("XOR")
val POWER = BinaryOperator("**", AnyNum())
// Comparison
val EQUALS = ComparisonOperator("=")
val NOT_EQUALS = ComparisonOperator("<>")
val LESS_THAN = ComparisonOperator("<")
val GREATER_THAN = ComparisonOperator(">")
val GREATER_EQUALS = ComparisonOperator(">=")
val LESS_EQUALS = ComparisonOperator("<=")
//
private val TABLE: MutableMap<String, Operator> = mutableMapOf()
init {
register(NOT)
register(MINUS)
register(ADD)
register(MULT)
register(SUB)
register(DIV)
register(MOD)
register(AND)
register(OR)
register(XOR)
register(POWER)
register(EQUALS)
register(NOT_EQUALS)
register(LESS_THAN)
register(GREATER_THAN)
register(GREATER_EQUALS)
register(LESS_EQUALS)
}
fun lookup(operator: String): Operator {
if (operator.toUpperCase() !in TABLE) {
throw IllegalArgumentException("Operator $operator is not defined")
}
return TABLE[operator.toUpperCase()]!!
}
fun register(op: Operator) = register(op.symbol, op)
fun register(symbol: String, op: Operator) {
TABLE[symbol] = op
}
}
| gpl-3.0 | 7e424156f6aac0fd60fdf28303d6fe93 | 27.8 | 79 | 0.650219 | 4.041359 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/base/util/FlowExtension.kt | 1 | 521 | package com.arcao.geocaching4locus.base.util
import kotlinx.coroutines.flow.Flow
suspend fun <T> Flow<T>.takeListVariable(initialCount: Int, action: suspend (List<T>) -> Int) {
if (initialCount <= 0) {
return
}
var nextCount = initialCount
val list = mutableListOf<T>()
collect { value ->
list.add(value)
if (list.size >= nextCount) {
nextCount = action(list)
list.clear()
}
}
if (list.isNotEmpty()) {
action(list)
}
}
| gpl-3.0 | 2f55150e05efe6bd29e153c6ed7b43fe | 19.84 | 95 | 0.577735 | 3.721429 | false | false | false | false |
Fondesa/RecyclerViewDivider | recycler-view-divider/src/test/kotlin/com/fondesa/recyclerviewdivider/test/AssertEqualDrawables.kt | 1 | 5401 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider.test
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import org.junit.Assert.assertTrue
/**
* Asserts that the [actual] [Drawable] is equal to the [expected] [Drawable].
* Unfortunately, using Robolectric we can't use [Bitmap] to compare two [Drawable], since the Robolectric implementation
* translates all the image pixels into transparent ones.
*
* @param expected the expected [Drawable].
* @param actual the actual [Drawable].
*/
internal fun assertEqualDrawables(expected: Drawable?, actual: Drawable?) {
assertTrue(actual.isEqualTo(expected))
}
private fun Drawable?.isEqualTo(other: Drawable?): Boolean {
if (this == null && other == null) return true
return if (this != null && other != null) {
if (this::class.java != other::class.java) {
// If the classes are different, they aren't the same Drawable.
return false
}
if (constantState == other.constantState) {
// If the constant state is identical, the drawables are equal.
// However, the opposite is not necessarily true.
return true
}
if (constantState == null || other.constantState == null) return false
when (this) {
is ColorDrawable -> isEqualTo(other as ColorDrawable)
is BitmapDrawable -> isEqualTo(other as BitmapDrawable)
is GradientDrawable -> isEqualTo(other as GradientDrawable)
else -> throw IllegalArgumentException("The drawable class ${this::class.java.name} isn't supported.")
}
} else {
false
}
}
private fun ColorDrawable.isEqualTo(other: ColorDrawable): Boolean = color == other.color
private fun BitmapDrawable.isEqualTo(other: BitmapDrawable): Boolean = bitmap == other.bitmap
private fun GradientDrawable.isEqualTo(other: GradientDrawable): Boolean = when (Build.VERSION.SDK_INT) {
in 14 until 21 -> false
21, 22 -> isEqualToApi21(other)
23 -> isEqualToApi23(other)
else -> isEqualToApi25(other)
}
private fun GradientDrawable.isEqualToApi21(other: GradientDrawable): Boolean {
val thisState = checkNotNull(constantState)
val otherState = checkNotNull(other.constantState)
val thisDefaultColor = thisState.fieldValue<ColorStateList?>("mColorStateList")?.defaultColor
val otherDefaultColor = otherState.fieldValue<ColorStateList?>("mColorStateList")?.defaultColor
if (thisDefaultColor != null && otherDefaultColor != null) return thisDefaultColor == otherDefaultColor
if (thisDefaultColor == null && otherDefaultColor == null) {
val thisColors = thisState.fieldValue<IntArray?>("mColors")
val otherColors = otherState.fieldValue<IntArray?>("mColors")
if (thisColors != null && otherColors != null) return thisColors.contentEquals(otherColors)
return thisColors == null && otherColors == null
}
return false
}
private fun GradientDrawable.isEqualToApi23(other: GradientDrawable): Boolean {
val thisState = checkNotNull(constantState)
val otherState = checkNotNull(other.constantState)
val thisDefaultColor = thisState.fieldValue<ColorStateList?>("mSolidColors")?.defaultColor
val otherDefaultColor = otherState.fieldValue<ColorStateList?>("mSolidColors")?.defaultColor
if (thisDefaultColor != null && otherDefaultColor != null) return thisDefaultColor == otherDefaultColor
if (thisDefaultColor == null && otherDefaultColor == null) {
val thisColors = thisState.fieldValue<IntArray?>("mGradientColors")
val otherColors = otherState.fieldValue<IntArray?>("mGradientColors")
if (thisColors != null && otherColors != null) return thisColors.contentEquals(otherColors)
return thisColors == null && otherColors == null
}
return false
}
private fun GradientDrawable.isEqualToApi25(other: GradientDrawable): Boolean {
val thisDefaultColor = color?.defaultColor
val otherDefaultColor = other.color?.defaultColor
if (thisDefaultColor != null && otherDefaultColor != null) return thisDefaultColor == otherDefaultColor
if (thisDefaultColor == null && otherDefaultColor == null) {
val thisColors = colors
val otherColors = other.colors
if (thisColors != null && otherColors != null) return thisColors.contentEquals(otherColors)
return thisColors == null && otherColors == null
}
return false
}
private inline fun <reified T> Any.fieldValue(fieldName: String): T =
this::class.java.fields.first { it.name == fieldName }.get(this) as T
| apache-2.0 | d470301345b58e4eea6d9e44e887d5f6 | 44.386555 | 121 | 0.7182 | 4.712914 | false | false | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/request/GeocacheExpand.kt | 1 | 1672 | package com.arcao.geocaching4locus.data.api.model.request
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_GEOCACHE_LOGS
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_GEOCACHE_LOG_IMAGES
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_IMAGES
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_SEPARATOR
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_TRACKABLES
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_USER_WAYPOINTS
class GeocacheExpand : Expand<GeocacheExpand> {
var geocacheLogs: Int? = null
var trackables: Int? = null
var geocacheLogImages: Int? = null
var userWaypoint = false
var images: Int? = null
override fun all(): GeocacheExpand {
geocacheLogs = 0
trackables = 0
geocacheLogImages = 0
userWaypoint = true
images = 0
return this
}
override fun toString(): String {
val items = ArrayList<String>(4)
geocacheLogs?.run {
items.add(EXPAND_FIELD_GEOCACHE_LOGS.expand(this))
}
trackables?.run {
items.add(EXPAND_FIELD_TRACKABLES.expand(this))
}
geocacheLogImages?.run {
items.add(EXPAND_FIELD_GEOCACHE_LOG_IMAGES.expand(this))
}
if (userWaypoint) items.add(EXPAND_FIELD_USER_WAYPOINTS)
images?.run {
items.add(EXPAND_FIELD_IMAGES.expand(this))
}
return items.joinToString(EXPAND_FIELD_SEPARATOR)
}
}
| gpl-3.0 | 4366524b7536232093a50c48c014619f | 36.155556 | 106 | 0.699761 | 3.808656 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/baby/EditBabyInfoActivity.kt | 1 | 14450 | package com.fuyoul.sanwenseller.ui.baby
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.ImageView
import com.alibaba.fastjson.JSON
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.bean.others.MultDialogBean
import com.fuyoul.sanwenseller.bean.reshttp.ResHttpBabyItem
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.enuminfo.BabyType
import com.fuyoul.sanwenseller.helper.MsgDialogHelper
import com.fuyoul.sanwenseller.listener.MultDialogListener
import com.fuyoul.sanwenseller.structure.model.EditBabyM
import com.fuyoul.sanwenseller.structure.presenter.EditBabyP
import com.fuyoul.sanwenseller.structure.view.EditBabyV
import com.fuyoul.sanwenseller.utils.GlideUtils
import com.fuyoul.sanwenseller.utils.PhotoSelectUtils
import com.youquan.selector.Matisse
import kotlinx.android.synthetic.main.editbabyinfo.*
import permissions.dispatcher.RuntimePermissions
import permissions.dispatcher.NeedsPermission
import android.Manifest
import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import com.fuyoul.sanwenseller.bean.reqhttp.ReqReleaseBaby
import com.fuyoul.sanwenseller.configs.Code.SERVICETIME
import com.fuyoul.sanwenseller.listener.KeyBordChangerListener
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import permissions.dispatcher.PermissionRequest
import permissions.dispatcher.OnShowRationale
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.OnNeverAskAgain
/**
* @author: chen
* @CreatDate: 2017\10\27 0027
* @Desc:发布宝贝和编辑宝贝
*/
@RuntimePermissions
class EditBabyInfoActivity : BaseActivity<EditBabyM, EditBabyV, EditBabyP>() {
private var goodsClassifyId = -1
private val selectPath = ArrayList<String>()//图片
private var photoUtils: PhotoSelectUtils = PhotoSelectUtils()
companion object {
fun start(activity: Activity, item: ResHttpBabyItem?) {
val intent = Intent(activity, EditBabyInfoActivity::class.java)
if (item != null) {
val bund = Bundle()
bund.putSerializable("item", item)
intent.putExtras(bund)
}
activity.startActivityForResult(intent, Code.REQ_EDITBABYINFO)
}
}
override fun setLayoutRes(): Int = R.layout.editbabyinfo
override fun initData(savedInstanceState: Bundle?) {
if (intent.extras != null && intent.extras.getSerializable("item") != null) {
val data = intent.extras.getSerializable("item") as ResHttpBabyItem
selectPath.add(JSON.parseArray(data.imgs).getJSONObject(0).getString("url"))
initViewImpl().addImg(this, selectPath[0], editBabyPic)
editBabyName.setText(data.goodsName)
editBabyPrice.setText("${data.price}")
editBabyDes.setText("${data.introduce}")
editBabyServiceTime.setText("${data.serviceTime}")
when (data.goodsClassifyId) {
BabyType.YFTX.typeId -> {
yftxBabyType.isChecked = true
editBabyType.text = BabyType.YFTX.title
goodsClassifyId = BabyType.YFTX.typeId
}
BabyType.BZPP.typeId -> {
bzppBabyType.isChecked = true
editBabyType.text = BabyType.BZPP.title
goodsClassifyId = BabyType.BZPP.typeId
}
BabyType.PJCY.typeId -> {
pjcyBabyType.isChecked = true
editBabyType.text = BabyType.PJCY.title
goodsClassifyId = BabyType.PJCY.typeId
}
BabyType.HYJT.typeId -> {
hyjtBabyType.isChecked = true
editBabyType.text = BabyType.HYJT.title
goodsClassifyId = BabyType.HYJT.typeId
}
BabyType.LCZR.typeId -> {
lczrBabyType.isChecked = true
editBabyType.text = BabyType.LCZR.title
goodsClassifyId = BabyType.LCZR.typeId
}
BabyType.SYCY.typeId -> {
sycyBabyType.isChecked = true
editBabyType.text = BabyType.SYCY.title
goodsClassifyId = BabyType.SYCY.typeId
}
BabyType.ZYQM.typeId -> {
zyqmBabyType.isChecked = true
editBabyType.text = BabyType.ZYQM.title
goodsClassifyId = BabyType.ZYQM.typeId
}
BabyType.ZHYC.typeId -> {
zhycBabyType.isChecked = true
editBabyType.text = BabyType.ZHYC.title
goodsClassifyId = BabyType.ZHYC.typeId
}
}
}
}
override fun setListener() {
registKeyBordListener(editBabyCotent, editBabyDes, object : KeyBordChangerListener {
override fun onShow(keyBordH: Int, srollHeight: Int) {
if (editBabyDes.isFocused) {
editBabyCotent.scrollBy(0, keyBordH)
}
}
override fun onHidden() {
if (editBabyDes.isFocused) {
editBabyCotent.scrollTo(0, 0)
}
}
})
editBabyBtn.setOnClickListener {
if (TextUtils.isEmpty(editBabyName.text)) {
NormalFunUtils.showToast(this, "请输入宝贝名称")
} else if (TextUtils.isEmpty(editBabyPrice.text)) {
NormalFunUtils.showToast(this, "请输入宝贝价格")
} else if (editBabyPrice.text.toString().toInt() == 0) {
NormalFunUtils.showToast(this, "宝贝价格必须大于0")
} else if (goodsClassifyId < 0) {
NormalFunUtils.showToast(this, "请选择宝贝分类")
} else if (selectPath.size == 0) {
NormalFunUtils.showToast(this, "请选择宝贝图片")
} else if (TextUtils.isEmpty(editBabyDes.text)) {
NormalFunUtils.showToast(this, "请输入宝贝描述")
} else {
//编辑
if (intent.extras != null && intent.extras.getSerializable("item") != null) {
val item = intent.extras.getSerializable("item") as ResHttpBabyItem
val array = JSON.parseArray((intent.extras.getSerializable("item") as ResHttpBabyItem).imgs)
val before = (0 until array.size).map { array.getJSONObject(it).getString("url") }
item.goodsName = editBabyName.text.toString()
item.introduce = editBabyDes.text.toString()
item.goodsClassifyId = goodsClassifyId
item.price = editBabyPrice.text.toString().toInt()
item.serviceTime = if (TextUtils.isEmpty(editBabyServiceTime.text.toString())) SERVICETIME else editBabyServiceTime.text.toString().toInt()
getPresenter().editBaby(this, item, selectPath, before)
} else {
//发布
val data = ReqReleaseBaby()
data.imgs = selectPath[0]
data.goodsName = editBabyName.text.toString()
data.price = editBabyPrice.text.toString().toInt()
data.category = goodsClassifyId
data.introduce = editBabyDes.text.toString()
data.serviceTime = if (TextUtils.isEmpty(editBabyServiceTime.text.toString())) SERVICETIME else editBabyServiceTime.text.toString().toInt()
getPresenter().releaseBaby(this, data)
}
}
}
editBabyPic.setOnClickListener {
initViewImpl().doSelectImg(this)
}
editBabyType.setOnClickListener {
if (editBabyTypeList.visibility == View.GONE) {
NormalFunUtils.changeKeyBord(this, false, editBabyName)
NormalFunUtils.changeKeyBord(this, false, editBabyPrice)
NormalFunUtils.changeKeyBord(this, false, editBabyServiceTime)
NormalFunUtils.changeKeyBord(this, false, editBabyDes)
editBabyTypeList.visibility = View.VISIBLE
}
}
editBabyTypeList.setOnCheckedChangeListener { _, i ->
editBabyTypeList.visibility = View.GONE
when (i) {
R.id.yftxBabyType -> {
editBabyType.text = BabyType.YFTX.title
goodsClassifyId = BabyType.YFTX.typeId
}
R.id.bzppBabyType -> {
editBabyType.text = BabyType.BZPP.title
goodsClassifyId = BabyType.BZPP.typeId
}
R.id.pjcyBabyType -> {
editBabyType.text = BabyType.PJCY.title
goodsClassifyId = BabyType.PJCY.typeId
}
R.id.hyjtBabyType -> {
editBabyType.text = BabyType.HYJT.title
goodsClassifyId = BabyType.HYJT.typeId
}
R.id.sycyBabyType -> {
editBabyType.text = BabyType.SYCY.title
goodsClassifyId = BabyType.SYCY.typeId
}
R.id.lczrBabyType -> {
editBabyType.text = BabyType.LCZR.title
goodsClassifyId = BabyType.LCZR.typeId
}
R.id.zyqmBabyType -> {
editBabyType.text = BabyType.ZYQM.title
goodsClassifyId = BabyType.ZYQM.typeId
}
R.id.zhycBabyType -> {
editBabyType.text = BabyType.ZHYC.title
goodsClassifyId = BabyType.ZHYC.typeId
}
}
}
}
override fun getPresenter(): EditBabyP = EditBabyP(initViewImpl())
override fun initViewImpl(): EditBabyV = object : EditBabyV() {
override fun addImg(context: Context, path: Any, view: ImageView) {
GlideUtils.loadNormalImg(context, path, view, R.mipmap.icon_imgloading, R.mipmap.icon_addimg)
}
override fun doSelectImg(activity: Activity) {
doSelectWithPermissionCheck(activity)
}
}
override fun initTopBar(): TopBarOption {
val option = TopBarOption()
option.isShowBar = true
option.mainTitle = if (intent.extras == null || intent.extras.getSerializable("item") == null) {
editBabyBtn.text = "发布"
"发布宝贝"
} else {
editBabyBtn.text = "完成"
"编辑宝贝"
}
return option
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
Code.REQ_SELECTIMGS -> {
selectPath.clear()
selectPath.addAll(Matisse.obtainPathResult(data))
initViewImpl().addImg(this, selectPath[0], editBabyPic)
}
Code.REQ_CAMERA -> {
selectPath.clear()
selectPath.add(photoUtils.getCapturePath(this))
initViewImpl().addImg(this, photoUtils.getCapturePath(this), editBabyPic)
}
}
}
}
@NeedsPermission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun doSelect(activity: Activity) {
val multItem = ArrayList<MultDialogBean>()
val camera = MultDialogBean()
camera.title = "拍照获取"
multItem.add(camera)
val gallary = MultDialogBean()
gallary.title = "相册获取"
multItem.add(gallary)
MsgDialogHelper.showMultItemDialog(activity, multItem, "取消", object : MultDialogListener {
override fun onItemClicked(position: Int) {
when (position) {
0 -> {
photoUtils.doCapture(activity)
}
1 -> {
photoUtils.doSelect(activity, 1, selectPath)
}
}
}
})
}
@SuppressLint("NeedOnRequestPermissionsResult")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
@OnShowRationale(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun doSelectR(request: PermissionRequest) {
MsgDialogHelper.showNormalDialog(this, false, "温馨提示", "缺少必要权限,是否进行授权?", object : MsgDialogHelper.DialogListener {
override fun onPositive() {
request.proceed()
}
override fun onNagetive() {
request.cancel()
}
})
}
@OnPermissionDenied(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun doSelectD() {
NormalFunUtils.showToast(this, "缺少必要权限,请前往权限管理中心开启对应权限")
}
@OnNeverAskAgain(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun doSelectN() {
NormalFunUtils.showToast(this, "缺少必要权限,请前往权限管理中心开启对应权限")
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (editBabyTypeList.visibility == View.VISIBLE) {
editBabyTypeList.visibility = View.GONE
return true
}
}
return super.onKeyDown(keyCode, event)
}
} | apache-2.0 | 7fcb0fa425386a5efa8e8e1e40f96eef | 37.002681 | 159 | 0.595527 | 4.514013 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/en/webtoons/src/eu/kanade/tachiyomi/extension/en/webtoons/Webtoons.kt | 1 | 6494 | package eu.kanade.tachiyomi.extension.en.webtoons
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
class Webtoons : ParsedHttpSource() {
override val name = "Webtoons.com"
override val baseUrl = "http://www.webtoons.com"
override val lang = "en"
override val supportsLatest = true
val day: String
get() {
return when (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> "div._list_SUNDAY"
Calendar.MONDAY -> "div._list_MONDAY"
Calendar.TUESDAY -> "div._list_TUESDAY"
Calendar.WEDNESDAY -> "div._list_WEDNESDAY"
Calendar.THURSDAY -> "div._list_THURSDAY"
Calendar.FRIDAY -> "div._list_FRIDAY"
Calendar.SATURDAY -> "div._list_SATURDAY"
else -> {
"div"
}
}
}
override fun popularMangaSelector() = "div.left_area > ul.lst_type1 > li"
override fun latestUpdatesSelector() = "div#dailyList > $day li > a:has(span:contains(UP))"
override fun headersBuilder() = super.headersBuilder()
.add("Referer", "http://www.webtoons.com/en/")
private val mobileHeaders = super.headersBuilder()
.add("Referer", "http://m.webtoons.com")
.build()
override fun popularMangaRequest(page: Int) = GET("$baseUrl/en/top", headers)
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/en/dailySchedule?sortOrder=UPDATE&webtoonCompleteType=ONGOING", headers)
private fun mangaFromElement(query: String, element: Element): SManga {
val manga = SManga.create()
element.select(query).first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.select("p.subj").text()
}
return manga
}
override fun popularMangaFromElement(element: Element) = mangaFromElement("a", element)
override fun latestUpdatesFromElement(element: Element): SManga {
val manga = SManga.create()
element.let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.select("p.subj").text()
}
return manga
}
override fun popularMangaNextPageSelector() = null
override fun latestUpdatesNextPageSelector() = null
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = HttpUrl.parse("$baseUrl/search?keyword=$query")?.newBuilder()!!
url.addQueryParameter("searchType", "WEBTOON")
return GET(url.toString(), headers)
}
override fun searchMangaParse(response: Response): MangasPage {
val query = response.request().url().queryParameter("keyword")
val toonDocument = response.asJsoup()
val discDocument = client.newCall(GET("$baseUrl/search?keyword=$query&searchType=CHALLENGE", headers)).execute().asJsoup()
val elements = mutableListOf<Element>().apply {
addAll(toonDocument.select(searchMangaSelector()))
addAll(discDocument.select(searchMangaSelector()))
}
val mangas = elements.map { element ->
searchMangaFromElement(element)
}
return MangasPage(mangas, false)
}
override fun searchMangaSelector() = "#content > div.card_wrap.search li"
override fun searchMangaFromElement(element: Element): SManga {
val manga = SManga.create()
element.select("a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.select("p.subj").text()
}
return manga
}
override fun searchMangaNextPageSelector() = null
override fun mangaDetailsParse(document: Document): SManga {
val detailElement = document.select("#content > div.cont_box > div.detail_header > div.info")
val infoElement = document.select("#_asideDetail")
val picElement = document.select("#content > div.cont_box > div.detail_body")
val discoverPic = document.select("#content > div.cont_box > div.detail_header > span.thmb")
val manga = SManga.create()
manga.author = detailElement.select(".author:nth-of-type(1)").text().substringBefore("author info")
manga.artist = detailElement.select(".author:nth-of-type(2)").first()?.text()?.substringBefore("author info") ?: manga.author
manga.genre = detailElement.select(".genre").text()
manga.description = infoElement.select("p.summary").text()
manga.status = infoElement.select("p.day_info").text().orEmpty().let { parseStatus(it) }
manga.thumbnail_url = discoverPic.select("img").not("[alt=Representative image").first()?.attr("src") ?: picElement.attr("style")?.substringAfter("url(")?.substringBeforeLast(")")
return manga
}
private fun parseStatus(status: String) = when {
status.contains("UP") -> SManga.ONGOING
status.contains("COMPLETED") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "ul#_episodeList > li[id*=episode]"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select("a")
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = element.select("a > div.row > div.info > p.sub_title > span.ellipsis").text()
val select = element.select("a > div.row > div.num")
if (select.isNotEmpty()) {
chapter.name = chapter.name + " Ch. " + select.text().substringAfter("#")
}
chapter.date_upload = element.select("a > div.row > div.info > p.date").text()?.let { SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH).parse(it).time } ?: 0
return chapter
}
override fun chapterListRequest(manga: SManga) = GET("http://m.webtoons.com" + manga.url, mobileHeaders)
override fun pageListParse(document: Document) = document.select("div#_imageList > img").mapIndexed { i, element -> Page(i, "", element.attr("data-url")) }
override fun imageUrlParse(document: Document) = document.select("img").first().attr("src")
}
| apache-2.0 | 2ecfb6a1da96321584c675d438223438 | 39.842767 | 187 | 0.646135 | 4.432765 | false | false | false | false |
timrs2998/myretail | myretail-service/src/main/kotlin/com/myretail/service/service/ProductService.kt | 1 | 2804 | package com.myretail.service.service
import com.myretail.api.Price
import com.myretail.api.Product
import com.myretail.service.po.ProductPO
import com.myretail.service.repository.ProductPORepository
import com.redsky.api.RedSkyProduct
import com.redsky.api.RedSkyResponse
import com.redsky.client.RedSkyApi
import org.springframework.data.rest.webmvc.ResourceNotFoundException
import org.springframework.stereotype.Component
import retrofit2.HttpException
import java.util.Optional
import java.util.concurrent.Future
import javax.inject.Inject
@Component
class ProductService @Inject constructor(
val repository: ProductPORepository,
val api: RedSkyApi
) {
val excludes = listOf("taxonomy", "price", "promotion", "bulk_ship",
"rating_and_review_reviews", "rating_and_review_statistics",
"question_answer_statistics")
fun get(id: Long): Product {
val future: Future<RedSkyResponse> = api.get(id, excludes)
val redSkyProduct: RedSkyProduct = getProduct(future)
val productPO: Optional<ProductPO> = repository.findById(id)
return if (productPO.isPresent) {
buildProduct(productPO.get(), redSkyProduct)
} else {
buildProduct(redSkyProduct)
}
}
fun update(updated: Product): Product {
val redSkyProduct: RedSkyProduct? = getProduct(api.get(updated.id, excludes))
if (updated.currentPrice == null) {
repository.deleteById(updated.id)
return buildProduct(redSkyProduct!!)
}
val productPO = repository.save(buildProductPO(updated))
return buildProduct(productPO, redSkyProduct!!)
}
private fun getProduct(future: Future<RedSkyResponse>): RedSkyProduct {
try {
return future.get().product
} catch (ex: java.util.concurrent.ExecutionException) {
val cause = ex.cause
if (cause is HttpException && cause.code() == 404) {
throw ResourceNotFoundException("Product does not exist in Redsky.")
}
throw ex
}
}
private fun buildProductPO(product: Product): ProductPO {
return ProductPO(
id = product.id,
currentPriceValue = product.currentPrice!!.value,
currentPriceCurrencyCode = product.currentPrice!!.currencyCode
)
}
private fun buildProduct(redSkyProduct: RedSkyProduct, price: Price? = null): Product {
return Product(
id = redSkyProduct.availableToPromiseNetwork!!.productId,
name = redSkyProduct.item.productDescription!!.title,
currentPrice = price
)
}
private fun buildProduct(productPO: ProductPO, redSkyProduct: RedSkyProduct): Product {
return Product(
id = productPO.id,
name = redSkyProduct.item.productDescription!!.title,
currentPrice = Price(
value = productPO.currentPriceValue,
currencyCode = productPO.currentPriceCurrencyCode
)
)
}
}
| gpl-3.0 | 459e9ffb6e65bb40bb191b435f534734 | 31.604651 | 89 | 0.725749 | 4.028736 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/data/classes/PalicoWeapon.kt | 1 | 858 | package com.ghstudios.android.data.classes
/**
* Created by Joseph on 7/9/2016.
*/
class PalicoWeapon {
var id: Long = 0
var attackMelee: Int = 0
var attackRanged: Int = 0
var isBlunt: Boolean = false
var balance: Int = 0
var element: String? = null
var elementMelee: Int = 0
var elementRanged: Int = 0
val elementEnum get() = getElementFromString(element ?: "")
var affinityMelee: Int = 0
var affinityRanged: Int = 0
var defense: Int = 0
var creation_cost: Int = 0
var sharpness: Int = 0
var item: Item? = null
val balanceString: String
get() {
when (balance) {
// todo: support translations in some way
0 -> return "Balanced"
1 -> return "Melee+"
else -> return "Boomerang+"
}
}
}
| mit | 771adfba9cadf7304a2e08a9e910bdfa | 23.514286 | 63 | 0.561772 | 4.04717 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiEditTexts.kt | 1 | 2247 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and 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.
*/
@file:JvmName("EmojiEditTexts")
package com.vanniktech.emoji
import android.view.KeyEvent
import android.widget.EditText
import com.vanniktech.emoji.traits.DisableKeyboardInputTrait
import com.vanniktech.emoji.traits.EmojiTrait
import com.vanniktech.emoji.traits.ForceSingleEmojiTrait
import com.vanniktech.emoji.traits.SearchInPlaceTrait
import kotlin.math.max
import kotlin.math.min
/** Dispatches a KeyEvent which mimics the press of the Backspace key */
fun EditText.backspace() {
val event = KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL)
dispatchKeyEvent(event)
}
/** Inserts the given [emoji] into [this] while preserving the current selection. */
fun EditText.input(emoji: Emoji, addWhitespace: Boolean = false) {
val start = selectionStart
val end = selectionEnd
val new = emoji.unicode + when {
addWhitespace -> " "
else -> ""
}
if (start < 0) {
append(new)
} else {
text.replace(min(start, end), max(start, end), new, 0, new.length)
}
}
/** Disables the keyboard. Only [emojiPopup] will be shown. */
fun EditText.installDisableKeyboardInput(emojiPopup: EmojiPopup): EmojiTrait =
DisableKeyboardInputTrait(emojiPopup).install(this)
/** Forces this EditText to contain only one Emoji. */
fun EditText.installForceSingleEmoji(): EmojiTrait =
ForceSingleEmojiTrait().install(this)
/** When typing :query it will display a Popup similar to how Telegram and Slack does it to search for an Emoji. */
fun EditText.installSearchInPlace(emojiPopup: EmojiPopup): EmojiTrait =
SearchInPlaceTrait(emojiPopup).install(this)
| apache-2.0 | af80a8f99e9e6a85ec5517f88d5aef62 | 35.209677 | 115 | 0.751002 | 3.917976 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/properties/playstats/factory/GivenAVersionOfMediaCenterIsNotReturned/WhenGettingThePlaystatsUpdater.kt | 2 | 2806 | package com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory.GivenAVersionOfMediaCenterIsNotReturned
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.FakeFilePropertiesContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ScopedFilePropertiesProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.IPlaystatsUpdate
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory.PlaystatsUpdateSelector
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.fileproperties.FilePropertiesPlayStatsUpdater
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.storage.ScopedFilePropertiesStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeScopedRevisionProvider
import com.lasthopesoftware.bluewater.client.connection.FakeConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.authentication.CheckIfScopedConnectionIsReadOnly
import com.lasthopesoftware.bluewater.client.servers.version.IProgramVersionProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenGettingThePlaystatsUpdater {
companion object {
private var updater: IPlaystatsUpdate? = null
@BeforeClass
@JvmStatic
fun before() {
val fakeConnectionProvider = FakeConnectionProvider()
val programVersionProvider = mockk<IProgramVersionProvider>()
every { programVersionProvider.promiseServerVersion() } returns Promise.empty()
val checkConnection = mockk<CheckIfScopedConnectionIsReadOnly>()
every { checkConnection.promiseIsReadOnly() } returns false.toPromise()
val fakeScopedRevisionProvider = FakeScopedRevisionProvider(1)
val fakeFilePropertiesContainer = FakeFilePropertiesContainer()
val playstatsUpdateSelector = PlaystatsUpdateSelector(
fakeConnectionProvider,
ScopedFilePropertiesProvider(fakeConnectionProvider, fakeScopedRevisionProvider, fakeFilePropertiesContainer),
ScopedFilePropertiesStorage(fakeConnectionProvider, checkConnection, fakeScopedRevisionProvider, fakeFilePropertiesContainer),
programVersionProvider
)
updater = playstatsUpdateSelector.promisePlaystatsUpdater().toFuture().get()
}
}
@Test
fun thenTheFilePropertiesPlaystatsUpdaterIsGiven() {
assertThat(updater).isInstanceOf(FilePropertiesPlayStatsUpdater::class.java)
}
}
| lgpl-3.0 | 61a4f08a487376dad02da1767d0297b3 | 51.943396 | 141 | 0.859943 | 4.684474 | false | false | false | false |
includex/LineageWatcher | app/src/main/java/com/stolineage/lineagewatcher/service/WatcherService.kt | 1 | 7528 | package com.stolineage.lineagewatcher.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.graphics.Rect
import android.hardware.display.VirtualDisplay
import android.media.projection.MediaProjection
import android.util.DisplayMetrics
import com.stolineage.lineagewatcher.R
import com.stolineage.lineagewatcher.utils.ImageTransmogrifier
import android.hardware.display.DisplayManager
import android.os.*
import android.content.pm.ApplicationInfo
import android.app.ActivityManager
import android.content.pm.ConfigurationInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.util.Log
import android.view.*
import com.stolineage.lineagewatcher.activity.AlarmActivity
import com.stolineage.lineagewatcher.singleton.Config
class WatcherService : Service() {
private var windowManager: WindowManager? = null;
private var uiView: View? = null;
private var metrics: DisplayMetrics = DisplayMetrics();
private var roundButton: View? = null
private var ivMover: View? = null
private var touchX: Float = 0f
private var touchY: Float = 0f
private var viewX: Int = 0
private var viewY: Int = 0
private var currentX: Int = 0
private var currentY: Int = 0
private var watching: Boolean = false
private var virtualDisplay: VirtualDisplay? = null
private val DISPLAY_NAME: String = "capture"
private val handlerThread = HandlerThread(javaClass.simpleName, android.os.Process.THREAD_PRIORITY_BACKGROUND)
private var handler: Handler? = null
//private var scaleX: Float = 0f
//private var scaleY: Float = 0f
private var color: Int? = null
private var vibrator: Vibrator? = null
private var defaultDisplay: Display? = null
private var params: WindowManager.LayoutParams = WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT)
private var imageTransmogrifier: ImageTransmogrifier? = null
override fun onCreate() {
super.onCreate()
windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
defaultDisplay = windowManager?.defaultDisplay;
defaultDisplay?.getMetrics(metrics)
installView()
handlerThread.start();
handler = Handler(handlerThread.getLooper());
vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
}
private fun updateUI(watching: Boolean) {
this.watching = watching
ivMover?.visibility = if (watching) View.GONE else View.VISIBLE
roundButton?.setBackgroundResource(if (watching) R.drawable.control_ui_round_watching else R.drawable.control_ui_round)
}
private fun installView() {
uiView = getUIView();
roundButton = uiView?.findViewById(R.id.v_round);
ivMover = uiView?.findViewById(R.id.iv_mover)
roundButton?.setOnClickListener({
updateUI(!watching);
if (watching == true) {
color = null;
if (virtualDisplay != null) {
virtualDisplay?.release();
virtualDisplay = null;
}
imageTransmogrifier = ImageTransmogrifier(this);
virtualDisplay = Config.mediaProjection?.createVirtualDisplay(DISPLAY_NAME,
imageTransmogrifier?.getWidth()!!, imageTransmogrifier?.getHeight()!!,
getResources().getDisplayMetrics().densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY or DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, imageTransmogrifier?.surface, null, handler);
Config.mediaProjection?.registerCallback(CallBack(virtualDisplay), handler)
}
})
bindDragEvent(uiView)
params.height = (43 * metrics.density).toInt()
params.width = (43 * metrics.density).toInt()
windowManager?.addView(uiView, params)
}
private fun bindDragEvent(view: View?) {
view?.setOnTouchListener(fun(view: View, ev: MotionEvent): Boolean {
if (watching) {
return false
}
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
touchX = ev.rawX
touchY = ev.rawY
viewX = params.x
viewY = params.y
currentX = params.x
currentY = params.y
}
MotionEvent.ACTION_MOVE -> {
val offsetX = ev.rawX - touchX
val offsetY = ev.rawY - touchY
params.x = viewX + offsetX.toInt()
params.y = viewY + offsetY.toInt()
var rect: Rect? = Rect()
var array: IntArray = IntArray(4);
roundButton?.getLocationOnScreen(array)
currentX = array[0];
currentY = array[1];
windowManager?.updateViewLayout(uiView, params)
}
}
return false
})
}
private fun getUIView(): View? {
val layoutInflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater;
val view = layoutInflater?.inflate(R.layout.overlay_view, null)
return view
}
override fun onDestroy() {
super.onDestroy()
if (virtualDisplay != null) {
virtualDisplay?.release()
virtualDisplay = null
}
if (uiView != null) {
windowManager?.removeView(uiView)
}
}
override fun onBind(pendingIntent: Intent?): IBinder? {
return null;
}
class CallBack : MediaProjection.Callback {
private var display: VirtualDisplay?
constructor(virtualDisplay: VirtualDisplay?) {
display = virtualDisplay
}
override fun onStop() {
display?.release()
super.onStop()
}
}
fun getWindowManager(): WindowManager? {
return windowManager
}
fun updateImage(bitmap: Bitmap?) {
if (!watching) {
return
}
if (currentX < 0 || currentY < 0) {
return;
}
Handler(Looper.getMainLooper()).post({
var x: Int? = null
var y: Int? = null
if (imageTransmogrifier?.orientation != getResources().getConfiguration().orientation) {
updateUI(false);
} else {
val currentColor = bitmap?.getPixel((currentX / imageTransmogrifier?.scaleX!! + (10 * metrics.density) / 2).toInt(), (currentY / imageTransmogrifier?.scaleY!! + (10 * metrics.density) / 2).toInt());
if (color == null) {
color = currentColor
} else if (currentColor != color) {
vibrator?.vibrate(5000)
updateUI(false);
if (Config.appKill) {
val intent = Intent(this, AlarmActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
}
}
})
}
fun getHandler(): Handler? {
return handler
}
}
| gpl-3.0 | 4539ddcab7915366b3a3402d0bb62de8 | 32.607143 | 214 | 0.602683 | 4.844273 | false | false | false | false |
koesie10/AdventOfCode-Solutions-Kotlin | 2015/src/main/kotlin/com/koenv/adventofcode/Day6.kt | 1 | 3972 | package com.koenv.adventofcode
class Day6Part1(val width: Int, val height: Int) {
val grid: Array<Array<Int>>
val numberOfLightsInOnState: Int
get() = grid.sumBy {
it.sum()
}
val numberOfLightsInOffState: Int
get() = width * height - numberOfLightsInOnState
init {
this.grid = Array(width, { Array(height, { STATE_OFF }) }) // Initialize an array of int[width][height] with all states set to 0
}
fun setStateForAll(newState: Int) {
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, column ->
grid[x][y]= newState
}
}
}
fun parseCommand(input: String) {
val matchResult = COMMAND_REGEX.find(input) ?: throw IllegalArgumentException("Not a valid command: $input")
val command = matchResult.groups[1]!!.value
val startX = matchResult.groups[2]!!.value.toInt()
val startY = matchResult.groups[3]!!.value.toInt()
val endX = matchResult.groups[4]!!.value.toInt()
val endY = matchResult.groups[5]!!.value.toInt()
val operator = getOperatorForCommand(command)
for (x in startX..endX) {
for (y in startY..endY) {
grid[x][y] = operator(grid[x][y])
}
}
}
fun parseCommands(input: String) {
return input.lines().forEach {
parseCommand(it)
}
}
private fun getOperatorForCommand(command: String): (Int) -> Int {
when (command) {
"turn on" -> return {
STATE_ON
}
"turn off" -> return {
STATE_OFF
}
"toggle" -> return {
if (it == STATE_OFF) STATE_ON else STATE_OFF
}
}
throw IllegalArgumentException("Invalid command: $command")
}
companion object {
const val STATE_OFF = 0
const val STATE_ON = 1
val COMMAND_REGEX = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)".toRegex()
}
}
class Day6Part2(val width: Int, val height: Int) {
val grid: Array<Array<Int>>
val totalBrightness: Int
get() = grid.sumBy {
it.sum()
}
init {
this.grid = Array(width, { Array(height, { DEFAULT_BRIGHTNESS }) }) // Initialize an array of int[width][height] with all states set to 0
}
fun setStateForAll(newState: Int) {
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, column ->
grid[x][y]= newState
}
}
}
fun parseCommand(input: String) {
val matchResult = COMMAND_REGEX.find(input) ?: throw IllegalArgumentException("Not a valid command: $input")
val command = matchResult.groups[1]!!.value
val startX = matchResult.groups[2]!!.value.toInt()
val startY = matchResult.groups[3]!!.value.toInt()
val endX = matchResult.groups[4]!!.value.toInt()
val endY = matchResult.groups[5]!!.value.toInt()
val operator = getOperatorForCommand(command)
for (x in startX..endX) {
for (y in startY..endY) {
grid[x][y] = operator(grid[x][y])
}
}
}
fun parseCommands(input: String) {
return input.lines().forEach {
parseCommand(it)
}
}
private fun getOperatorForCommand(command: String): (Int) -> Int {
when (command) {
"turn on" -> return {
it + 1
}
"turn off" -> return {
if (it > 0) it - 1 else it
}
"toggle" -> return {
it + 2
}
}
throw IllegalArgumentException("Invalid command: $command")
}
companion object {
const val DEFAULT_BRIGHTNESS = 0
val COMMAND_REGEX = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)".toRegex()
}
} | mit | f143c6119e207a0523da15b284475935 | 28 | 145 | 0.531219 | 4.159162 | false | false | false | false |
lttng/lttng-scope | jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/views/timegraph/model/provider/arrows/TimeGraphModelArrowProvider.kt | 2 | 2975 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.views.timegraph.model.provider.arrows;
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.project.TraceProject
import com.efficios.jabberwocky.views.timegraph.model.render.arrows.TimeGraphArrowRender
import com.efficios.jabberwocky.views.timegraph.model.render.arrows.TimeGraphArrowSeries
import com.efficios.jabberwocky.views.timegraph.model.render.tree.TimeGraphTreeRender
import javafx.beans.property.BooleanProperty
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import java.util.concurrent.FutureTask
/**
* Provider for timegraph arrow series.
*
* It can be used stand-alone (ie, for testing) but usually would be part of a
* {@link ITimeGraphModelProvider}.
*
* @author Alexandre Montplaisir
*/
abstract class TimeGraphModelArrowProvider(val arrowSeries: TimeGraphArrowSeries) {
/**
* Property representing the trace this arrow provider fetches its data for.
*/
private val traceProjectProperty: ObjectProperty<TraceProject<*, *>?> = SimpleObjectProperty(null)
fun traceProjectProperty() = traceProjectProperty
var traceProject
get() = traceProjectProperty.get()
set(value) = traceProjectProperty.set(value)
/**
* Property indicating if this specific arrow provider is currently enabled
* or not.
*
* Normally the controls should not send queries to this provider if it is
* disabled (they would only query this state), but the arrow provider is
* free to make use of this property for other reasons.
*/
private val enabledProperty: BooleanProperty = SimpleBooleanProperty(false)
fun enabledProperty() = enabledProperty
var enabled
get() = enabledProperty.get()
set(value) = enabledProperty.set(value)
/**
* Get a render of arrows from this arrow provider.
*
* @param treeRender
* The tree render for which the query is done
* @param timeRange
* The time range of the query. The provider may decide to
* include arrows partially inside this range, or not.
* @param task
* An optional task parameter, which can be checked for
* cancellation to stop processing at any point and return.
* @return The corresponding arrow render
*/
abstract fun getArrowRender(treeRender: TimeGraphTreeRender,
timeRange: TimeRange,
task: FutureTask<*>?): TimeGraphArrowRender
}
| epl-1.0 | 2090938a0a210762db556831cf0030e9 | 39.753425 | 102 | 0.718655 | 4.692429 | false | false | false | false |
googlearchive/android-text | RoundedBackground-Kotlin/lib/src/main/java/com/android/example/text/styling/roundedbg/TextRoundedBgAttributeReader.kt | 2 | 2714 | /*
* 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 com.android.example.text.styling.roundedbg
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.core.content.res.getDrawableOrThrow
/**
* Reads default attributes that [TextRoundedBgHelper] needs from resources. The attributes read
* are:
*
* - chHorizontalPadding: the padding to be applied to left & right of the background
* - chVerticalPadding: the padding to be applied to top & bottom of the background
* - chDrawable: the drawable used to draw the background
* - chDrawableLeft: the drawable used to draw left edge of the background
* - chDrawableMid: the drawable used to draw for whole line
* - chDrawableRight: the drawable used to draw right edge of the background
*/
class TextRoundedBgAttributeReader(context: Context, attrs: AttributeSet?) {
val horizontalPadding: Int
val verticalPadding: Int
val drawable: Drawable
val drawableLeft: Drawable
val drawableMid: Drawable
val drawableRight: Drawable
init {
val typedArray = context.obtainStyledAttributes(
attrs,
R.styleable.TextRoundedBgHelper,
0,
R.style.RoundedBgTextView
)
horizontalPadding = typedArray.getDimensionPixelSize(
R.styleable.TextRoundedBgHelper_roundedTextHorizontalPadding,
0
)
verticalPadding = typedArray.getDimensionPixelSize(
R.styleable.TextRoundedBgHelper_roundedTextVerticalPadding,
0
)
drawable = typedArray.getDrawableOrThrow(
R.styleable.TextRoundedBgHelper_roundedTextDrawable
)
drawableLeft = typedArray.getDrawableOrThrow(
R.styleable.TextRoundedBgHelper_roundedTextDrawableLeft
)
drawableMid = typedArray.getDrawableOrThrow(
R.styleable.TextRoundedBgHelper_roundedTextDrawableMid
)
drawableRight = typedArray.getDrawableOrThrow(
R.styleable.TextRoundedBgHelper_roundedTextDrawableRight
)
typedArray.recycle()
}
}
| apache-2.0 | ebf3bbcfb5abc6bedfd1ad52be58ba7f | 36.694444 | 96 | 0.717023 | 4.769772 | false | false | false | false |
voidcorp/SerialToDb | src/main/kotlin/nl/voidcorp/arduino/Num.kt | 1 | 800 | package nl.voidcorp.arduino
val tensNames = arrayOf("", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety")
val numNames = arrayOf("", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen")
fun convertLessThanOneThousand(number: Int): String {
var number = number
var soFar: String
if (number % 100 < 20) {
soFar = numNames[number % 100]
number /= 100
} else {
soFar = numNames[number % 10]
number /= 10
soFar = tensNames[number % 10] + soFar
number /= 10
}
if (number == 0) return soFar
return numNames[number] + "hundred" + soFar
} | apache-2.0 | 11c6f0b91d44cb11572e14b50cb460d3 | 29.807692 | 101 | 0.56625 | 3.34728 | false | false | false | false |
ze-pequeno/okhttp | samples/tlssurvey/src/main/kotlin/okhttp3/survey/CipherSuiteSurvey.kt | 2 | 2037 | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.survey
import okhttp3.survey.types.Client
import okhttp3.survey.types.SuiteId
/**
* Organizes information on SSL cipher suite inclusion and precedence for this spreadsheet.
* https://docs.google.com/spreadsheets/d/1C3FdZSlCBq_-qrVwG1KDIzNIB3Hyg_rKAcgmSzOsHyQ/edit#gid=0
*/
class CipherSuiteSurvey(
val clients: List<Client>,
val ianaSuites: IanaSuites,
val orderBy: List<SuiteId>
) {
fun printGoogleSheet() {
print("name")
for (client in clients) {
print("\t")
print(client.nameAndVersion)
}
println()
val sortedSuites = ianaSuites.suites.sortedBy { ianaSuite ->
val index = orderBy.indexOfFirst { it.matches(ianaSuite) }
if (index == -1) Integer.MAX_VALUE else index
}
for (suiteId in sortedSuites) {
print(suiteId.name)
for (client in clients) {
print("\t")
val index = client.enabled.indexOfFirst { it.matches(suiteId) }
if (index != -1) {
print(index + 1)
} else if (client.supported.find { it.matches(suiteId) } != null) {
// Not currently supported, as since 3.9.x we filter to a list
// that is a subset of the platforms.
// The correct answer for developers who override ConnectionSpec,
// it would be the platform defaults, so look at Java and Android
// for the answers.
print("□")
}
}
println()
}
}
}
| apache-2.0 | 5c390f61be81fa30d0d5196915896f72 | 32.360656 | 97 | 0.663391 | 3.761553 | false | false | false | false |
google/horologist | tiles/src/androidTest/java/com/google/android/horologist/tiles/ImagesTest.kt | 1 | 2668 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalCoroutinesApi::class, ExperimentalCoroutinesApi::class)
package com.google.android.horologist.tiles
import android.content.Context
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.wear.tiles.ResourceBuilders
import com.google.android.horologist.tiles.images.loadImageResource
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@SmallTest
class ImagesTest {
private lateinit var context: Context
@Before
fun setup() {
context = InstrumentationRegistry.getInstrumentation().context
}
@Test
public fun loadImageResource() {
runTest {
val imageLoader = FakeImageLoader {
// https://wordpress.org/openverse/image/34896de8-afb0-494c-af63-17b73fc14124/
FakeImageLoader.loadSuccessBitmap(context, it, R.drawable.coil)
}
val imageResource = imageLoader.loadImageResource(context, R.drawable.coil)
val inlineResource = imageResource!!.inlineResource!!
assertThat(inlineResource.format).isEqualTo(ResourceBuilders.IMAGE_FORMAT_RGB_565)
assertThat(inlineResource.widthPx).isEqualTo(200)
assertThat(inlineResource.heightPx).isEqualTo(134)
}
}
@Test
public fun handlesFailures() {
runTest {
val imageLoader = FakeImageLoader {
// https://wordpress.org/openverse/image/34896de8-afb0-494c-af63-17b73fc14124/
FakeImageLoader.loadErrorBitmap(context, it, R.drawable.coil)
}
val imageResource = imageLoader.loadImageResource(context, R.drawable.coil) {
error(R.drawable.coil)
}
val inlineResource = imageResource!!.inlineResource!!
assertThat(inlineResource.format).isEqualTo(ResourceBuilders.IMAGE_FORMAT_RGB_565)
}
}
}
| apache-2.0 | 735e8161a24f89ec87144adda14610da | 35.054054 | 94 | 0.708021 | 4.537415 | false | true | false | false |
xfournet/intellij-community | platform/configuration-store-impl/src/StateStorageManagerImpl.kt | 1 | 19592 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.roots.ProjectModelElement
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.PathUtilRt
import com.intellij.util.ReflectionUtil
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.systemIndependentPath
import gnu.trove.THashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.regex.Pattern
import kotlin.concurrent.read
import kotlin.concurrent.write
private val MACRO_PATTERN = Pattern.compile("(\\$[^$]*\\$)")
/**
* If componentManager not specified, storage will not add file tracker
*/
open class StateStorageManagerImpl(private val rootTagName: String,
override final val macroSubstitutor: TrackingPathMacroSubstitutor? = null,
override val componentManager: ComponentManager? = null,
private val virtualFileTracker: StorageVirtualFileTracker? = StateStorageManagerImpl.createDefaultVirtualTracker(componentManager) ) : StateStorageManager {
private val macros: MutableList<Macro> = ContainerUtil.createLockFreeCopyOnWriteList()
private val storageLock = ReentrantReadWriteLock()
private val storages = THashMap<String, StateStorage>()
val compoundStreamProvider = CompoundStreamProvider()
override fun addStreamProvider(provider: StreamProvider, first: Boolean) {
if (first) {
compoundStreamProvider.providers.add(0, provider)
}
else {
compoundStreamProvider.providers.add(provider)
}
}
override fun removeStreamProvider(clazz: Class<out StreamProvider>) {
compoundStreamProvider.providers.removeAll { clazz.isInstance(it) }
}
// access under storageLock
@Suppress("LeakingThis")
private var isUseVfsListener = if (componentManager == null) ThreeState.NO else ThreeState.UNSURE // unsure because depends on stream provider state
protected open val isUseXmlProlog: Boolean
get() = true
companion object {
private fun createDefaultVirtualTracker(componentManager: ComponentManager?): StorageVirtualFileTracker? {
return when (componentManager) {
null -> {
null
}
is Application -> {
StorageVirtualFileTracker(componentManager.messageBus)
}
else -> {
val tracker = (ApplicationManager.getApplication().stateStore.storageManager as? StateStorageManagerImpl)?.virtualFileTracker ?: return null
Disposer.register(componentManager, Disposable {
tracker.remove { it.storageManager.componentManager == componentManager }
})
tracker
}
}
}
}
private data class Macro(val key: String, var value: String)
@TestOnly fun getVirtualFileTracker() = virtualFileTracker
/**
* @param expansion System-independent
*/
fun addMacro(key: String, expansion: String): Boolean {
LOG.assertTrue(!key.isEmpty())
val value: String
if (expansion.contains("\\")) {
val message = "Macro $key set to system-dependent expansion $expansion"
if (ApplicationManager.getApplication().isUnitTestMode) {
throw IllegalArgumentException(message)
}
else {
LOG.warn(message)
value = FileUtilRt.toSystemIndependentName(expansion)
}
}
else {
value = expansion
}
// e.g ModuleImpl.setModuleFilePath update macro value
for (macro in macros) {
if (key == macro.key) {
macro.value = value
return false
}
}
macros.add(Macro(key, value))
return true
}
// system-independent paths
open fun pathRenamed(oldPath: String, newPath: String, event: VFileEvent?) {
for (macro in macros) {
if (oldPath == macro.value) {
macro.value = newPath
}
}
}
@Suppress("CAST_NEVER_SUCCEEDS")
override final fun getStateStorage(storageSpec: Storage) = getOrCreateStorage(
storageSpec.path,
storageSpec.roamingType,
storageSpec.storageClass.java,
storageSpec.stateSplitter.java,
storageSpec.exclusive,
storageCreator = storageSpec as? StorageCreator
)
protected open fun normalizeFileSpec(fileSpec: String): String {
val path = FileUtilRt.toSystemIndependentName(fileSpec)
// fileSpec for directory based storage could be erroneously specified as "name/"
return if (path.endsWith('/')) path.substring(0, path.length - 1) else path
}
// storageCustomizer - to ensure that other threads will use fully constructed and configured storage (invoked under the same lock as created)
fun getOrCreateStorage(collapsedPath: String,
roamingType: RoamingType = RoamingType.DEFAULT,
storageClass: Class<out StateStorage> = StateStorage::class.java,
@Suppress("DEPRECATION") stateSplitter: Class<out StateSplitter> = StateSplitterEx::class.java,
exclusive: Boolean = false,
storageCustomizer: (StateStorage.() -> Unit)? = null,
storageCreator: StorageCreator? = null): StateStorage {
val normalizedCollapsedPath = normalizeFileSpec(collapsedPath)
val key: String
if (storageClass == StateStorage::class.java) {
if (normalizedCollapsedPath.isEmpty()) {
throw Exception("Normalized path is empty, raw path '$collapsedPath'")
}
key = storageCreator?.key ?: normalizedCollapsedPath
}
else {
key = storageClass.name!!
}
val storage = storageLock.read { storages.get(key) } ?: return storageLock.write {
storages.getOrPut(key) {
@Suppress("IfThenToElvis")
val storage = if (storageCreator == null) createStateStorage(storageClass, normalizedCollapsedPath, roamingType, stateSplitter, exclusive) else storageCreator.create(this)
storageCustomizer?.let { storage.it() }
storage
}
}
storageCustomizer?.let { storage.it() }
return storage
}
fun getCachedFileStorages() = storageLock.read { storages.values.toSet() }
fun findCachedFileStorage(name: String) : StateStorage? = storageLock.read { storages.get(name) }
fun getCachedFileStorages(changed: Collection<String>, deleted: Collection<String>, pathNormalizer: ((String) -> String)? = null) = storageLock.read {
Pair(getCachedFileStorages(changed, pathNormalizer), getCachedFileStorages(deleted, pathNormalizer))
}
fun updatePath(spec: String, newPath: String) {
val storage = getCachedFileStorages(listOf(spec)).firstOrNull() ?: return
if (storage is StorageVirtualFileTracker.TrackedStorage) {
virtualFileTracker?.let { tracker ->
tracker.remove(storage.file.systemIndependentPath)
tracker.put(newPath, storage)
}
}
storage.setFile(null, Paths.get(newPath))
}
fun getCachedFileStorages(fileSpecs: Collection<String>, pathNormalizer: ((String) -> String)? = null): Collection<FileBasedStorage> {
if (fileSpecs.isEmpty()) {
return emptyList()
}
storageLock.read {
var result: MutableList<FileBasedStorage>? = null
for (fileSpec in fileSpecs) {
val path = normalizeFileSpec(pathNormalizer?.invoke(fileSpec) ?: fileSpec)
val storage = storages.get(path)
if (storage is FileBasedStorage) {
if (result == null) {
result = SmartList<FileBasedStorage>()
}
result.add(storage)
}
}
return result ?: emptyList()
}
}
// overridden in upsource
protected open fun createStateStorage(storageClass: Class<out StateStorage>,
collapsedPath: String,
roamingType: RoamingType,
@Suppress("DEPRECATION") stateSplitter: Class<out StateSplitter>,
exclusive: Boolean = false): StateStorage {
if (storageClass != StateStorage::class.java) {
val constructor = storageClass.constructors.first { it.parameterCount <= 3 }
constructor.isAccessible = true
if (constructor.parameterCount == 2) {
return constructor.newInstance(componentManager!!, this) as StateStorage
}
else {
return constructor.newInstance(collapsedPath, componentManager!!, this) as StateStorage
}
}
val effectiveRoamingType = getEffectiveRoamingType(roamingType, collapsedPath)
if (isUseVfsListener == ThreeState.UNSURE) {
isUseVfsListener = ThreeState.fromBoolean(!compoundStreamProvider.isApplicable(collapsedPath, effectiveRoamingType))
}
val filePath = expandMacros(collapsedPath)
@Suppress("DEPRECATION")
if (stateSplitter != StateSplitter::class.java && stateSplitter != StateSplitterEx::class.java) {
val storage = createDirectoryBasedStorage(filePath, collapsedPath, ReflectionUtil.newInstance(stateSplitter))
if (storage is StorageVirtualFileTracker.TrackedStorage) {
virtualFileTracker?.put(filePath, storage)
}
return storage
}
if (!ApplicationManager.getApplication().isHeadlessEnvironment && PathUtilRt.getFileName(filePath).lastIndexOf('.') < 0) {
throw IllegalArgumentException("Extension is missing for storage file: $filePath")
}
val storage = createFileBasedStorage(filePath, collapsedPath, effectiveRoamingType, if (exclusive) null else this.rootTagName)
if (isUseVfsListener == ThreeState.YES && storage is StorageVirtualFileTracker.TrackedStorage) {
virtualFileTracker?.put(filePath, storage)
}
return storage
}
// open for upsource
protected open fun createFileBasedStorage(path: String, collapsedPath: String, roamingType: RoamingType, rootTagName: String?): StateStorage
= MyFileStorage(this, Paths.get(path), collapsedPath, rootTagName, roamingType, getMacroSubstitutor(collapsedPath), if (roamingType == RoamingType.DISABLED) null else compoundStreamProvider)
// open for upsource
protected open fun createDirectoryBasedStorage(path: String, collapsedPath: String, @Suppress("DEPRECATION") splitter: StateSplitter): StateStorage
= MyDirectoryStorage(this, Paths.get(path), splitter)
private class MyDirectoryStorage(override val storageManager: StateStorageManagerImpl, file: Path, @Suppress("DEPRECATION") splitter: StateSplitter) :
DirectoryBasedStorage(file, splitter, storageManager.macroSubstitutor), StorageVirtualFileTracker.TrackedStorage
protected open class MyFileStorage(override val storageManager: StateStorageManagerImpl,
file: Path,
fileSpec: String,
rootElementName: String?,
roamingType: RoamingType,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
provider: StreamProvider? = null) : FileBasedStorage(file, fileSpec, rootElementName, pathMacroManager, roamingType, provider), StorageVirtualFileTracker.TrackedStorage {
override val isUseXmlProlog: Boolean
get() = rootElementName != null && storageManager.isUseXmlProlog
override fun beforeElementSaved(element: Element) {
if (rootElementName != null) {
storageManager.beforeElementSaved(element)
}
super.beforeElementSaved(element)
}
override fun beforeElementLoaded(element: Element) {
storageManager.beforeElementLoaded(element)
super.beforeElementLoaded(element)
}
override fun providerDataStateChanged(element: Element?, type: DataStateChanged) {
storageManager.providerDataStateChanged(this, element, type)
super.providerDataStateChanged(element, type)
}
override fun getResolution(component: PersistentStateComponent<*>, operation: StateStorageOperation): Resolution {
if (operation == StateStorageOperation.WRITE && component is ProjectModelElement && storageManager.isExternalSystemStorageEnabled && component.externalSource != null) {
return Resolution.CLEAR
}
return Resolution.DO
}
}
open val isExternalSystemStorageEnabled: Boolean
get() = false
protected open fun beforeElementSaved(element: Element) {
}
protected open fun providerDataStateChanged(storage: FileBasedStorage, element: Element?, type: DataStateChanged) {
}
protected open fun beforeElementLoaded(element: Element) {
}
override final fun rename(path: String, newName: String) {
storageLock.write {
val storage = getOrCreateStorage(collapseMacros(path), RoamingType.DEFAULT) as FileBasedStorage
val file = storage.virtualFile
try {
if (file != null) {
file.rename(storage, newName)
}
else if (storage.file.fileName.toString() != newName) {
// old file didn't exist or renaming failed
val expandedPath = expandMacros(path)
val parentPath = PathUtilRt.getParentPath(expandedPath)
storage.setFile(null, Paths.get(parentPath, newName))
pathRenamed(expandedPath, "$parentPath/$newName", null)
}
}
catch (e: IOException) {
LOG.debug(e)
}
}
}
fun clearStorages() {
storageLock.write {
try {
virtualFileTracker?.let {
storages.forEachEntry { collapsedPath, _ ->
it.remove(expandMacros(collapsedPath))
true
}
}
}
finally {
storages.clear()
}
}
}
protected open fun getMacroSubstitutor(fileSpec: String): TrackingPathMacroSubstitutor? = macroSubstitutor
override fun expandMacros(path: String): String {
// replacement can contains $ (php tests), so, this check must be performed before expand
val matcher = MACRO_PATTERN.matcher(path)
matcherLoop@
while (matcher.find()) {
val m = matcher.group(1)
for ((key) in macros) {
if (key == m) {
continue@matcherLoop
}
}
throw IllegalArgumentException("Unknown macro: $m in storage file spec: $path")
}
var expanded = path
for ((key, value) in macros) {
expanded = StringUtil.replace(expanded, key, value)
}
return expanded
}
fun expandMacro(macro: String): String {
for ((key, value) in macros) {
if (key == macro) {
return value
}
}
throw IllegalArgumentException("Unknown macro $macro")
}
fun collapseMacros(path: String): String {
var result = path
for ((key, value) in macros) {
result = result.replace(value, key)
}
return normalizeFileSpec(result)
}
override final fun startExternalization() = object : StateStorageManager.ExternalizationSession {
private val sessions = LinkedHashMap<StateStorage, StateStorage.ExternalizationSession>()
override fun setState(storageSpecs: List<Storage>, component: Any, componentName: String, state: Any) {
val stateStorageChooser = component as? StateStorageChooserEx
for (storageSpec in storageSpecs) {
@Suppress("IfThenToElvis")
var resolution = if (stateStorageChooser == null) Resolution.DO else stateStorageChooser.getResolution(storageSpec, StateStorageOperation.WRITE)
if (resolution == Resolution.SKIP) {
continue
}
val storage = getStateStorage(storageSpec)
if (resolution == Resolution.DO && component is PersistentStateComponent<*>) {
resolution = storage.getResolution(component, StateStorageOperation.WRITE)
if (resolution == Resolution.SKIP) {
continue
}
}
getExternalizationSession(storage)?.setState(component, componentName, if (storageSpec.deprecated || resolution == Resolution.CLEAR) Element("empty") else state)
}
}
override fun setStateInOldStorage(component: Any, componentName: String, state: Any) {
getOldStorage(component, componentName, StateStorageOperation.WRITE)?.let {
getExternalizationSession(it)?.setState(component, componentName, state)
}
}
private fun getExternalizationSession(storage: StateStorage): StateStorage.ExternalizationSession? {
var session = sessions.get(storage)
if (session == null) {
session = storage.startExternalization()
if (session != null) {
sessions.put(storage, session)
}
}
return session
}
override fun createSaveSessions(): List<SaveSession> {
if (sessions.isEmpty()) {
return emptyList()
}
var saveSessions: MutableList<SaveSession>? = null
val externalizationSessions = sessions.values
for (session in externalizationSessions) {
val saveSession = session.createSaveSession()
if (saveSession != null) {
if (saveSessions == null) {
if (externalizationSessions.size == 1) {
return listOf(saveSession)
}
saveSessions = SmartList<SaveSession>()
}
saveSessions.add(saveSession)
}
}
return saveSessions ?: emptyList()
}
}
override final fun getOldStorage(component: Any, componentName: String, operation: StateStorageOperation): StateStorage? {
val oldStorageSpec = getOldStorageSpec(component, componentName, operation) ?: return null
return getOrCreateStorage(oldStorageSpec, RoamingType.DEFAULT)
}
protected open fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? = null
}
private fun String.startsWithMacro(macro: String): Boolean {
val i = macro.length
return getOrNull(i) == '/' && startsWith(macro)
}
fun removeMacroIfStartsWith(path: String, macro: String) = if (path.startsWithMacro(macro)) path.substring(macro.length + 1) else path
@Suppress("DEPRECATION")
internal val Storage.path: String
get() = if (value.isEmpty()) file else value
internal fun getEffectiveRoamingType(roamingType: RoamingType, collapsedPath: String): RoamingType {
if (roamingType != RoamingType.DISABLED && (collapsedPath == StoragePathMacros.WORKSPACE_FILE || collapsedPath == "other.xml")) {
return RoamingType.DISABLED
}
else {
return roamingType
}
} | apache-2.0 | eacf81f148dfcffdf08845e0ee6011d0 | 37.417647 | 207 | 0.689465 | 5.200956 | false | true | false | false |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/bottomsheet_dialog/dagger/BottomSheetModule.kt | 1 | 6137 | /*
* Copyright 2019 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.bottomsheet_dialog.dagger
import android.view.View
import com.github.vase4kin.teamcityapp.base.list.view.BaseListView
import com.github.vase4kin.teamcityapp.base.list.view.ViewHolderFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.ArtifactBrowserMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.ArtifactDefaultMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.ArtifactFolderMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.ArtifactFullMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.BranchMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.BuildTypeMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.DefaultMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.MenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items.ProjectMenuItemsFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.model.BottomSheetDataModel
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.model.BottomSheetDataModelImpl
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.model.BottomSheetInteractor
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.model.BottomSheetInteractorImpl
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.view.BottomSheetAdapter
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.view.BottomSheetItemViewHolderFactory
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.view.BottomSheetView
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.view.BottomSheetViewImpl
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntKey
import dagger.multibindings.IntoMap
import org.greenrobot.eventbus.EventBus
/**
* Bottom sheet dialog dependencies
*/
@Module
class BottomSheetModule(private val view: View, private val fragment: BottomSheetDialogFragment) {
private val menuType: Int
private val title: String
private val descriptions: List<String>
init {
this.menuType = fragment.arguments?.getInt(ARG_BOTTOM_SHEET_TYPE) ?: 0
this.title = fragment.arguments?.getString(ARG_TITLE) ?: ""
val descriptions = fragment.arguments?.getStringArray(ARG_DESCRIPTION)?.toList() ?: emptyList()
this.descriptions = if (descriptions.isNotEmpty()) descriptions else listOf("")
}
@Provides
fun providesBottomSheetDataModel(menuItemsFactories: Map<Int, @JvmSuppressWildcards MenuItemsFactory>): BottomSheetDataModel {
return BottomSheetDataModelImpl(
menuItemsFactories[menuType]?.createMenuItems() ?: emptyList()
)
}
@Provides
fun providesInteractor(
model: BottomSheetDataModel,
eventBus: EventBus
): BottomSheetInteractor {
return BottomSheetInteractorImpl(title, model, view.context, eventBus)
}
@Provides
fun providesBottomSheetView(adapter: BottomSheetAdapter): BottomSheetView {
return BottomSheetViewImpl(view, fragment, adapter)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_DEFAULT)
@Provides
fun providesDefaultMenu(): MenuItemsFactory {
return DefaultMenuItemsFactory(view.context, descriptions)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_BRANCH)
@Provides
fun providesBranchMenu(): MenuItemsFactory {
return BranchMenuItemsFactory(view.context, descriptions)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_ARTIFACT_DEFAULT)
@Provides
fun providesArtifactDefaultMenu(): MenuItemsFactory {
return ArtifactDefaultMenuItemsFactory(view.context, descriptions)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_ARTIFACT_BROWSER)
@Provides
fun providesArtifactBrowserMenu(): MenuItemsFactory {
return ArtifactBrowserMenuItemsFactory(view.context, descriptions)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_ARTIFACT_FOLDER)
@Provides
fun providesArtifactFolderMenu(): MenuItemsFactory {
return ArtifactFolderMenuItemsFactory(view.context, descriptions)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_ARTIFACT_FULL)
@Provides
fun providesArtifactFullMenu(): MenuItemsFactory {
return ArtifactFullMenuItemsFactory(view.context, descriptions)
}
@Provides
fun providesAdapter(viewHolderFactories: Map<Int, @JvmSuppressWildcards ViewHolderFactory<BottomSheetDataModel>>): BottomSheetAdapter {
return BottomSheetAdapter(viewHolderFactories)
}
@IntoMap
@IntKey(BaseListView.TYPE_DEFAULT)
@Provides
fun providesViewHolderFactory(): ViewHolderFactory<BottomSheetDataModel> {
return BottomSheetItemViewHolderFactory()
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_BUILD_TYPE)
@Provides
fun providesBuildTypeMenu(): MenuItemsFactory {
return BuildTypeMenuItemsFactory(view.context, descriptions)
}
@IntoMap
@IntKey(MenuItemsFactory.TYPE_PROJECT)
@Provides
fun providesProjectMenu(): MenuItemsFactory {
return ProjectMenuItemsFactory(view.context, descriptions)
}
companion object {
const val ARG_TITLE = "arg_title"
const val ARG_DESCRIPTION = "arg_description"
const val ARG_BOTTOM_SHEET_TYPE = "arg_bottom_sheet_type"
}
}
| apache-2.0 | 80dbfe337c8436699cc4373116f30255 | 38.339744 | 139 | 0.774809 | 4.56622 | false | false | false | false |
FredJul/TaskGame | TaskGame-Hero/src/main/java/net/fred/taskgame/hero/fragments/EndBattleDialogFragment.kt | 1 | 5274 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.fragments
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.DialogFragment
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.dialog_end_battle.*
import net.fred.taskgame.hero.R
import net.fred.taskgame.hero.models.Card
import net.fred.taskgame.hero.models.Level
import net.fred.taskgame.hero.utils.UiUtils
import org.jetbrains.anko.sdk21.coroutines.onClick
import org.parceler.Parcels
class EndBattleDialogFragment : ImmersiveDialogFragment() {
enum class EndType {
PLAYER_WON, ENEMY_WON, DRAW
}
private var level: Level? = null
private var wasAlreadyCompletedOnce: Boolean = false
private var endType: EndType? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
level = Parcels.unwrap<Level>(arguments.getParcelable<Parcelable>(ARG_LEVEL))
wasAlreadyCompletedOnce = arguments.getBoolean(ARG_WAS_ALREADY_COMPLETED_ONCE)
endType = arguments.getSerializable(ARG_END_TYPE) as EndType
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme_Dialog)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.dialog_end_battle, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
when (endType) {
EndBattleDialogFragment.EndType.PLAYER_WON -> {
title.text = "VICTORY"
var contentText = "Who is the boss now?\n\n"
if (!wasAlreadyCompletedOnce) {
level?.let { lvl ->
val previousSlots = Level.getCorrespondingDeckSlots(lvl.levelNumber - 1)
val newSlots = Level.getCorrespondingDeckSlots(lvl.levelNumber)
val previousAvailableCreatures = Card.getNonObtainedCardList(previousSlots).size
val newAvailableCreatures = Card.getNonObtainedCardList(newSlots).size
if (newAvailableCreatures > previousAvailableCreatures) {
contentText += " ● You can now summon more creatures!\n"
}
if (newSlots > previousSlots) {
contentText += " ● You have earned new deck slots!\n"
}
}
}
content.text = contentText
}
EndBattleDialogFragment.EndType.ENEMY_WON -> {
title.text = "DEFEAT"
content.text = "Well, that was close, right?"
crown.visibility = View.GONE
}
EndBattleDialogFragment.EndType.DRAW -> {
title.text = "DRAW"
content.text = "Well, that was close, right?"
crown.visibility = View.GONE
}
}
ok.onClick { dialog.cancel() }
}
override fun onDetach() {
// We are removing this fragment, let's also remove the battle one which were used as background
fragmentManager.popBackStack()
level?.let { lvl ->
if (endType == EndType.PLAYER_WON && !TextUtils.isEmpty(lvl.getEndStory(context))) {
val transaction = fragmentManager.beginTransaction()
UiUtils.animateTransition(transaction, UiUtils.TransitionType.TRANSITION_FADE_IN)
transaction.replace(R.id.fragment_container, StoryFragment.newInstance(lvl, true), StoryFragment::class.java.name).addToBackStack(null).commitAllowingStateLoss()
}
}
super.onDetach()
}
companion object {
val ARG_LEVEL = "ARG_LEVEL"
private val ARG_WAS_ALREADY_COMPLETED_ONCE = "ARG_WAS_ALREADY_COMPLETED_ONCE"
private val ARG_END_TYPE = "ARG_END_TYPE"
internal fun newInstance(level: Level, wasAlreadyCompletedOnce: Boolean, endType: EndType): EndBattleDialogFragment {
val f = EndBattleDialogFragment()
val args = Bundle()
args.putParcelable(ARG_LEVEL, Parcels.wrap(level))
args.putBoolean(ARG_WAS_ALREADY_COMPLETED_ONCE, wasAlreadyCompletedOnce)
args.putSerializable(ARG_END_TYPE, endType)
f.arguments = args
return f
}
}
} | gpl-3.0 | 0cfb82c9d584cd1dee7c80675fbde9b0 | 38.335821 | 177 | 0.6463 | 4.554883 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/transformers/documentables/ActualTypealiasAdder.kt | 1 | 3748 | package org.jetbrains.dokka.base.transformers.documentables
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.model.properties.WithExtraProperties
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.transformers.documentation.DocumentableTransformer
class ActualTypealiasAdder : DocumentableTransformer {
override fun invoke(original: DModule, context: DokkaContext) = original.generateTypealiasesMap().let { aliases ->
original.copy(packages = original.packages.map { it.copy(classlikes = addActualTypeAliasToClasslikes(it.classlikes, aliases)) })
}
private fun DModule.generateTypealiasesMap(): Map<DRI, DTypeAlias> =
packages.flatMap { pkg ->
pkg.typealiases.map { typeAlias ->
typeAlias.dri to typeAlias
}
}.toMap()
private fun addActualTypeAliasToClasslikes(
elements: Iterable<DClasslike>,
typealiases: Map<DRI, DTypeAlias>
): List<DClasslike> = elements.flatMap {
when (it) {
is DClass -> addActualTypeAlias(
it.copy(
classlikes = addActualTypeAliasToClasslikes(it.classlikes, typealiases)
).let(::listOf),
typealiases
)
is DEnum -> addActualTypeAlias(
it.copy(
classlikes = addActualTypeAliasToClasslikes(it.classlikes, typealiases)
).let(::listOf),
typealiases
)
is DInterface -> addActualTypeAlias(
it.copy(
classlikes = addActualTypeAliasToClasslikes(it.classlikes, typealiases)
).let(::listOf),
typealiases
)
is DObject -> addActualTypeAlias(
it.copy(
classlikes = addActualTypeAliasToClasslikes(it.classlikes, typealiases)
).let(::listOf),
typealiases
)
is DAnnotation -> addActualTypeAlias(
it.copy(
classlikes = addActualTypeAliasToClasslikes(it.classlikes, typealiases)
).let(::listOf),
typealiases
)
else -> throw IllegalStateException("${it::class.qualifiedName} ${it.name} cannot have extra added")
}
}
private fun <T> addActualTypeAlias(
elements: Iterable<T>,
typealiases: Map<DRI, DTypeAlias>
): List<T> where T : DClasslike, T : WithExtraProperties<T>, T : WithSources =
elements.map { element ->
if (element.expectPresentInSet != null) {
typealiases[element.dri]?.let { ta ->
val merged = element.withNewExtras(element.extra + ActualTypealias(ta.underlyingType)).let {
when(it) {
is DClass -> it.copy(sourceSets = element.sourceSets + ta.sourceSets)
is DEnum -> it.copy(sourceSets = element.sourceSets + ta.sourceSets)
is DInterface -> it.copy(sourceSets = element.sourceSets + ta.sourceSets)
is DObject -> it.copy(sourceSets = element.sourceSets + ta.sourceSets)
is DAnnotation -> it.copy(sourceSets = element.sourceSets + ta.sourceSets)
else -> throw IllegalStateException("${it::class.qualifiedName} ${it.name} cannot have copy its sourceSets")
}
}
@Suppress("UNCHECKED_CAST")
merged as T
} ?: element
} else {
element
}
}
}
| apache-2.0 | a8dc8fb9664f5268b66af8d1f7cedfa8 | 42.581395 | 136 | 0.568837 | 5.176796 | false | false | false | false |
eugeis/ee-schkola | ee-schkola/src/test/kotlin/ee/schkola/SchkolaCsvParser.kt | 1 | 5750 | package ee.schkola
import ee.common.ext.logger
import ee.common.ext.toIntOr0
import ee.schkola.ImportFields.*
import ee.schkola.ImportFields.Church
import ee.schkola.person.*
import ee.schkola.student.SchoolApplication
import ee.schkola.student.SchoolYear
import java.nio.file.Path
import java.text.SimpleDateFormat
import java.util.*
enum class ImportFields(val regex: Regex) {
SubmitDate(Regex(".*Submit date")), Ip(Regex("Ip")), Name(Regex("Name:")), Geschlecht(Regex("Geschlecht:")),
Geburtsdatum(Regex("Geburtsdatum:")), Adresse(Regex("Adresse")), PLZ(Regex("PLZ")), Ort(Regex("Ort")),
TelefonHandy(Regex("Telefon / Handy:")), Email(Regex("E-mail:")), Passbild(Regex("Passbild:")),
Schulabschluss(Regex("Schulabschluss:")), Beruf(Regex("Beruf:")), Familienstand(Regex("Familienstand:")),
Partner(Regex("Name des Ehepartners:")), ChildrenCount(Regex("Anzahl der Kinder:")),
MemberOfChurch(Regex("Mitglied in Ortsgemeinde:")), Church(Regex("Name der Ortsgemeinde:")),
ChurchServices(Regex("Gemeindedienste:")), Mentor(Regex("Mentor:")),
MentorTelefon(Regex("Telefonnummer deines Pastors oder Mentors:")), Recommendation(Regex("Mündliche Empfehlung:")),
RecommendationOf(Regex("Empfehlung von:")), ApplicationFor(Regex("Bewerbung für:"));
companion object {
fun findByCode(code: String): ImportFields? {
return values().find { it.regex.matches(code) }
}
}
}
class SchkolaCsvParser {
val log = logger()
val dateFormatEn = SimpleDateFormat("yyyy-MM-dd")
val dateTimeFormatEn = SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
val dateFormatDe = SimpleDateFormat("dd.MM.yyyy")
val dateTimeFormatDe = SimpleDateFormat("dd.MM.yyyy hh:mm:ss")
val f = HashMap<ImportFields, Int>()
fun List<String>.f(field: ImportFields): String {
return get(f[field]!!)
}
fun String.toPersonName(): PersonName {
val parts = split(" ")
return PersonName(parts.first(), parts.last())
}
fun String.toGender(): Gender {
return if (equals("Weiblich")) Gender.FEMALE else Gender.MALE
}
fun String.toDate(): Date {
try {
return dateFormatEn.parse(this)
} catch (e: Exception) {
try {
return dateFormatDe.parse(this)
} catch (e: Exception) {
return Date()
}
}
}
fun String.toDateTime(): Date {
try {
return dateTimeFormatEn.parse(this)
} catch (e: Exception) {
try {
return dateTimeFormatDe.parse(this)
} catch (e: Exception) {
return Date()
}
}
}
fun String.toMaritalState(): MaritalState {
return when (this) {
"Verheiratet" -> MaritalState.MARRIED
"ledig" -> MaritalState.SINGLE
else -> MaritalState.SINGLE
}
}
fun String.split(): List<String> {
try {
return trim().split(",").map { it.trim().substring(1, it.length - 1).trim() }
} catch (e: Exception) {
return emptyList()
}
}
val graduation = hashMapOf<String, Graduation>()
fun String.toGraduation(): Graduation {
return graduation.getOrPut(this, { Graduation(id = this, level = GraduationLevel.UNKNOWN) })
}
fun load(schoolYearName: String, source: Path): List<SchoolApplication> {
val schoolYear = SchoolYear(name = schoolYearName)
val applications = arrayListOf<SchoolApplication>()
f.clear()
source.toFile().readLines().forEachIndexed { i, s ->
log.info("parse: $s")
try {
if (i == 0) {
s.split().forEachIndexed { i, s ->
val field = Companion.findByCode(s)
if (field != null) f.put(field, i) else log.warn("Unknown code $s")
}
} else {
val l = s.split()
if (l.isNotEmpty()) {
val person = Profile(gender = l.f(Geschlecht).toGender(), name = l.f(Name).toPersonName(),
birthday = l.f(Geburtsdatum).toDate(),
address = Address(street = l.f(Adresse), code = l.f(PLZ), city = l.f(Ort)),
contact = Contact(phone = l.f(TelefonHandy), email = l.f(Email)), photo = l.f(Passbild),
family = Family(l.f(Familienstand).toMaritalState(),
childrenCount = l.f(ChildrenCount).toIntOr0(), partner = l.f(Partner).toPersonName()),
church = ChurchInfo(church = l.f(Church), member = l.f(MemberOfChurch).toBoolean(),
services = l.f(ChurchServices).split(",").toMutableList()),
education = Education(graduation = l.f(Schulabschluss).toGraduation(),
profession = l.f(Beruf)), id = "2016_" + i)
person.trace.createdAt = l.f(SubmitDate).toDateTime()
val application = SchoolApplication(recommendationOf = l.f(RecommendationOf).toPersonName(),
churchContactPerson = l.f(Mentor).toPersonName(),
churchContact = Contact(phone = l.f(MentorTelefon)), group = l.f(ApplicationFor),
schoolYear = schoolYear, profile = person)
applications.add(application)
}
}
} catch (e: Exception) {
log.error("Parse problem of $i: $s", e)
}
}
return applications
}
} | apache-2.0 | a51a3faa3eaaa187e3d7d47698089b3b | 38.923611 | 119 | 0.562283 | 3.936986 | false | false | false | false |
michael-johansen/workshop-jb | src/iv_builders/_22_ExtensionFunctionLiterals.kt | 5 | 1125 | package iv_builders
import java.util.HashMap
import util.TODO
fun functions() {
// function
fun getLastChar(s: String) = s.charAt(s.length() - 1)
getLastChar("abc")
// extension function
fun String.lastChar() = this.charAt(this.length() - 1)
// 'this' can be omitted
fun String.lastChar2() = charAt(length() - 1)
"abc".lastChar()
}
fun functionLiterals() {
// function literal
val getLastChar: (String) -> Char = { s -> s.charAt(s.length() - 1) }
getLastChar("abc")
// extension function literal
val lastChar: String.() -> Char = { this.charAt(this.length() - 1) }
// 'this' can be omitted
val lastChar2: String.() -> Char = { charAt(length() - 1) }
"abc".lastChar()
}
fun todoTask22() = TODO(
"""
Task 22.
Rewrite 'todoTask22()' so that 'x.isEven()' checks that x is even
and 'x.isOdd()' checks that x is odd.
"""
)
fun task22(): List<Boolean> {
val isEven: Int.() -> Boolean = { todoTask22() }
val isOdd: Int.() -> Boolean = { todoTask22() }
return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}
| mit | dd4cdb2a3cb7c9562ac30482940f82ad | 22.93617 | 73 | 0.591111 | 3.493789 | false | false | false | false |
dya-tel/TSU-Schedule | src/main/kotlin/ru/dyatel/tsuschedule/utilities/AndroidUtilities.kt | 1 | 1879 | package ru.dyatel.tsuschedule.utilities
import android.app.Activity
import android.content.Context
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.support.v7.preference.Preference
import android.view.View
import com.wealthfront.magellan.Screen
import org.jetbrains.anko.inputMethodManager
import org.json.JSONArray
import org.json.JSONObject
class NumberPreferenceValidator(
private val acceptEmptyInput: Boolean = false,
private val constraint: IntRange? = null
) : Preference.OnPreferenceChangeListener {
override fun onPreferenceChange(preference: Preference?, newValue: Any): Boolean {
if (newValue == "")
return acceptEmptyInput && (constraint == null || 0 in constraint)
return try {
val number = (newValue as String).toInt()
constraint == null || number in constraint
} catch (e: NumberFormatException) {
false
}
}
}
fun Activity.hideKeyboard() {
val view = currentFocus ?: return
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
view.clearFocus()
}
fun View.hideIf(condition: () -> Boolean) {
visibility = if (condition()) View.GONE else View.VISIBLE
}
fun View.setBackgroundTintResource(colorRes: Int) {
ViewCompat.setBackgroundTintList(this, ContextCompat.getColorStateList(context, colorRes))
}
inline fun <reified T> JSONObject.find(name: String): T =
get(name) as T? ?: throw NoSuchElementException()
operator fun JSONArray.iterator() = object : Iterator<Any> {
private var current = 0
override fun hasNext() = current < [email protected]()
override fun next() = this@iterator[current++]
}
val Screen<*>.ctx: Context?
get() = getActivity()
val Fragment.ctx: Context?
get() = context
| mit | 31d3d64c61678ded9efd7d6eed6ca75a | 27.469697 | 94 | 0.71421 | 4.410798 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/extensions/LiveData.kt | 1 | 1132 | package com.booboot.vndbandroid.extensions
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
operator fun <T> MutableLiveData<T>?.plusAssign(value: T?) {
this?.postValue(value)
}
fun MutableLiveData<Int>.plus() = Handler(Looper.getMainLooper()).post {
value = value?.inc() ?: 1
}
fun MutableLiveData<Int>.minus() = Handler(Looper.getMainLooper()).post {
value = if (value ?: 0 <= 1) 0 else value?.dec()
}
fun MutableLiveData<*>.reset() = Handler(Looper.getMainLooper()).post {
postValue(null)
}
fun <T> MutableLiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner, action: (T) -> Unit) = observe(lifecycleOwner.actualOwner(), Observer<T> {
it ?: return@Observer
reset()
action(it)
})
/** Remove result nullabilty **/
fun <T> MutableLiveData<T>.observeNonNull(lifecycleOwner: LifecycleOwner, action: (T) -> Unit) {
removeObservers(lifecycleOwner.actualOwner())
observe(lifecycleOwner.actualOwner(), Observer<T> {
it ?: return@Observer
action(it)
})
} | gpl-3.0 | 305c7005c0d6be4b1a147a53801c4253 | 28.815789 | 145 | 0.712898 | 3.985915 | false | false | false | false |
android/architecture-samples | app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsUtils.kt | 1 | 1407 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.statistics
import com.example.android.architecture.blueprints.todoapp.data.Task
/**
* Function that does some trivial computation. Used to showcase unit tests.
*/
internal fun getActiveAndCompletedStats(tasks: List<Task>?): StatsResult {
return if (tasks == null || tasks.isEmpty()) {
StatsResult(0f, 0f)
} else {
val totalTasks = tasks.size
val numberOfActiveTasks = tasks.count { it.isActive }
StatsResult(
activeTasksPercent = 100f * numberOfActiveTasks / tasks.size,
completedTasksPercent = 100f * (totalTasks - numberOfActiveTasks) / tasks.size
)
}
}
data class StatsResult(val activeTasksPercent: Float, val completedTasksPercent: Float)
| apache-2.0 | 278786c4a3aa1d8011b8074e6643b0f5 | 36.026316 | 90 | 0.719972 | 4.263636 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/dialogfragments/checkertaskfilterdialog/CheckerTaskFilterDialogFragment.kt | 1 | 6962 | package com.mifos.mifosxdroid.dialogfragments.checkertaskfilterdialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.DialogFragment
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.online.checkerinbox.CheckerInboxViewModel
import com.mifos.mifosxdroid.online.checkerinbox.CheckerInboxViewModelFactory
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.utils.FragmentConstants
import kotlinx.android.synthetic.main.dialog_fragment_checker_task_filter.*
import java.lang.ClassCastException
import java.sql.Timestamp
import java.text.SimpleDateFormat
import javax.inject.Inject
class CheckerTaskFilterDialogFragment : DialogFragment(), MFDatePicker.OnDatePickListener,
AdapterView.OnItemSelectedListener {
private lateinit var mOnInputSelected: OnInputSelected
private lateinit var datePickerFromDate: DialogFragment
private lateinit var datePickerToDate: DialogFragment
private lateinit var mCurrentDateView: View
private lateinit var selectedAction: String
private lateinit var selectedEntity: String
private lateinit var actionOptionsList: MutableList<String>
private lateinit var entityOptionsList: MutableList<String>
private lateinit var actionOptionsAdapter: ArrayAdapter<String>
private lateinit var entityOptionsAdapter: ArrayAdapter<String>
private lateinit var fromDate: String
private lateinit var toDate: String
private val ALL = "ALL"
private val TO_TIME = "23:59:59"
@Inject
lateinit var factory: CheckerInboxViewModelFactory
private lateinit var viewModel: CheckerInboxViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
actionOptionsList = mutableListOf()
entityOptionsList = mutableListOf()
actionOptionsList.add(ALL)
entityOptionsList.add(ALL)
fromDate = ""
selectedAction = ALL
selectedEntity = ALL
datePickerFromDate = MFDatePicker.newInsance(this)
datePickerToDate = MFDatePicker.newInsance(this)
(activity as MifosBaseActivity).activityComponent.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?
, savedInstanceState: Bundle?): View? {
return inflater.inflate(
R.layout.dialog_fragment_checker_task_filter, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sp_action.onItemSelectedListener = this
sp_entity.onItemSelectedListener = this
setOnClickListeners()
tv_from_date.text = getString(R.string.select_from_date)
toDate = "${MFDatePicker.getDatePickedAsString()} $TO_TIME"
tv_to_date.text = toDate.substringBefore(" ")
}
private fun setOnClickListeners() {
tv_from_date.setOnClickListener {
activity?.supportFragmentManager?.let { it1 ->
datePickerFromDate.show(it1,
FragmentConstants.DFRAG_DATE_PICKER)
}
mCurrentDateView = tv_from_date
}
tv_to_date.setOnClickListener {
activity?.supportFragmentManager?.let { it1 ->
datePickerToDate.show(it1,
FragmentConstants.DFRAG_DATE_PICKER)
}
mCurrentDateView = tv_to_date
}
btn_apply_filter.setOnClickListener {
val resourceId = et_resource_id.text.toString().trim()
var fromDateTimeStamp: Timestamp? = null
if (fromDate.isNotEmpty()) {
fromDateTimeStamp = Timestamp(
SimpleDateFormat("dd-MM-yyyy").parse(fromDate).time
)
}
val toDateTimeStamp = Timestamp(
SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(toDate).time
)
mOnInputSelected.sendInput(fromDateTimeStamp, toDateTimeStamp,
selectedAction, selectedEntity, resourceId)
dialog?.dismiss()
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this, factory)
.get(CheckerInboxViewModel::class.java)
viewModel.getSearchTemplate().observe(this, Observer {
val checkerInboxSearchTemplate = it!!
actionOptionsList.addAll(checkerInboxSearchTemplate.actionNames)
entityOptionsList.addAll(checkerInboxSearchTemplate.entityNames)
actionOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, actionOptionsList)
actionOptionsAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
entityOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, entityOptionsList)
entityOptionsAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
sp_action.adapter = actionOptionsAdapter
sp_entity.adapter = entityOptionsAdapter
selectedAction = checkerInboxSearchTemplate.actionNames[0]
selectedEntity = checkerInboxSearchTemplate.entityNames[0]
})
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
mOnInputSelected = targetFragment as OnInputSelected
} catch (e: ClassCastException) {
Log.e("TaskFilterDialog", e.message.toString())
}
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
when (p0?.id) {
R.id.sp_action -> {
selectedAction = p0.getItemAtPosition(p2) as String
}
R.id.sp_entity -> {
selectedEntity = p0.getItemAtPosition(p2) as String
}
}
}
interface OnInputSelected {
fun sendInput(fromDate: Timestamp?, toDate: Timestamp, action: String = "",
entity: String = "", resourceId: String = "")
}
override fun onDatePicked(date: String) {
if (mCurrentDateView === tv_from_date) {
fromDate = date
tv_from_date.text = fromDate
} else if (mCurrentDateView === tv_to_date) {
toDate = "$date $TO_TIME"
tv_to_date.text = toDate.substringBefore(" ")
}
}
}
| mpl-2.0 | b9247a6b182d75d0a0eb722c305e9872 | 37.043716 | 90 | 0.668917 | 4.969308 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/program/ProgramInfoDialog.kt | 1 | 6496 | package cz.vhromada.catalog.gui.program
import cz.vhromada.catalog.entity.Program
import cz.vhromada.catalog.gui.common.AbstractInfoDialog
import cz.vhromada.catalog.gui.common.CatalogSwingConstants
import javax.swing.GroupLayout
import javax.swing.JCheckBox
import javax.swing.JLabel
import javax.swing.JSpinner
import javax.swing.JTextField
import javax.swing.SpinnerNumberModel
/**
* A class represents dialog for program.
*
* @author Vladimir Hromada
*/
class ProgramInfoDialog : AbstractInfoDialog<Program> {
/**
* Label for name
*/
private val nameLabel = JLabel("Name")
/**
* Text field for name
*/
private val nameData = JTextField()
/**
* Label for czech Wikipedia
*/
private val wikiCzLabel = JLabel("Czech Wikipedia")
/**
* Text field for czech Wikipedia
*/
private val wikiCzData = JTextField()
/**
* Label for english Wikipedia
*/
private val wikiEnLabel = JLabel("English Wikipedia")
/**
* Text field for english Wikipedia
*/
private val wikiEnData = JTextField()
/**
* Label for count of media
*/
private val mediaCountLabel = JLabel("Count of media")
/**
* Spinner for count of media
*/
private val mediaCountData = JSpinner(SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1))
/**
* Check box for crack
*/
private val crackData = JCheckBox("Crack")
/**
* Check box for serial key
*/
private val serialData = JCheckBox("Serial key")
/**
* Label for other data
*/
private val otherDataLabel = JLabel("Other data")
/**
* Text field for other data
*/
private val otherDataData = JTextField()
/**
* Label for note
*/
private val noteLabel = JLabel("Note")
/**
* Text field for note
*/
private val noteData = JTextField()
/**
* Creates a new instance of ProgramInfoDialog.
*/
constructor() {
init()
}
/**
* Creates a new instance of ProgramInfoDialog.
*
* @param program program
*/
constructor(program: Program) : super(program) {
init()
this.nameData.text = program.name
this.wikiCzData.text = program.wikiCz
this.wikiEnData.text = program.wikiEn
this.mediaCountData.value = program.mediaCount
this.crackData.isSelected = program.crack!!
this.serialData.isSelected = program.serialKey!!
this.otherDataData.text = program.otherData
this.noteData.text = program.note
}
override fun initComponents() {
initLabelComponent(nameLabel, nameData)
initLabelComponent(wikiCzLabel, wikiCzData)
initLabelComponent(wikiEnLabel, wikiEnData)
initLabelComponent(mediaCountLabel, mediaCountData)
initLabelComponent(otherDataLabel, otherDataData)
initLabelComponent(noteLabel, noteData)
addInputValidator(nameData)
}
override fun processData(objectData: Program?): Program {
if (objectData == null) {
return Program(id = null,
name = nameData.text,
wikiCz = wikiCzData.text,
wikiEn = wikiEnData.text,
mediaCount = mediaCountData.value as Int,
crack = crackData.isSelected,
serialKey = serialData.isSelected,
otherData = otherDataData.text,
note = noteData.text,
position = null)
}
return objectData.copy(name = nameData.text,
wikiCz = wikiCzData.text,
wikiEn = wikiEnData.text,
mediaCount = mediaCountData.value as Int,
crack = crackData.isSelected,
serialKey = serialData.isSelected,
otherData = otherDataData.text,
note = noteData.text)
}
/**
* Returns true if input is valid: name isn't empty string.
*
* @return true if input is valid: name isn't empty string
*/
override fun isInputValid(): Boolean {
return nameData.text.isNotBlank()
}
override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createHorizontalComponents(layout, nameLabel, nameData))
.addGroup(createHorizontalComponents(layout, wikiCzLabel, wikiCzData))
.addGroup(createHorizontalComponents(layout, wikiEnLabel, wikiEnData))
.addGroup(createHorizontalComponents(layout, mediaCountLabel, mediaCountData))
.addComponent(crackData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(serialData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addGroup(createHorizontalComponents(layout, otherDataLabel, otherDataData))
.addGroup(createHorizontalComponents(layout, noteLabel, noteData))
}
@Suppress("DuplicatedCode")
override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createVerticalComponents(layout, nameLabel, nameData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, wikiCzLabel, wikiCzData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, wikiEnLabel, wikiEnData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, mediaCountLabel, mediaCountData))
.addGap(VERTICAL_GAP_SIZE)
.addComponent(crackData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(serialData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, otherDataLabel, otherDataData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, noteLabel, noteData))
}
}
| mit | 56098ee7a802e2b7e831b50c7a6cfd6c | 33.189474 | 182 | 0.64178 | 5.205128 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/program/ProgramsStatsTableDataModel.kt | 1 | 2004 | package cz.vhromada.catalog.gui.program
import cz.vhromada.catalog.entity.Program
import cz.vhromada.catalog.facade.ProgramFacade
import cz.vhromada.catalog.gui.common.AbstractStatsTableDataModel
import cz.vhromada.common.result.Result
import cz.vhromada.common.result.Status
/**
* A class represents data model for table with stats for programs.
*
* @author Vladimir Hromada
*/
class ProgramsStatsTableDataModel(private val programFacade: ProgramFacade) : AbstractStatsTableDataModel() {
/**
* List of programs
*/
private lateinit var programs: List<Program>
/**
* Total count of media
*/
private var totalMediaCount: Int = 0
init {
update()
}
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any {
return when (columnIndex) {
0 -> programs.size
1 -> totalMediaCount
else -> throw IndexOutOfBoundsException("Bad column")
}
}
override fun getColumnCount(): Int {
return 2
}
override fun getRowCount(): Int {
return 1
}
override fun getColumnClass(columnIndex: Int): Class<*> {
return Int::class.java
}
override fun getColumnName(column: Int): String {
return when (column) {
0 -> "Count of programs"
1 -> "Count of media"
else -> throw IndexOutOfBoundsException("Bad column")
}
}
@Suppress("DuplicatedCode")
override fun update() {
val programsResult = programFacade.getAll()
val totalMediaCountResult = programFacade.getTotalMediaCount()
val result = Result<Void>()
result.addEvents(programsResult.events())
result.addEvents(totalMediaCountResult.events())
if (Status.OK == result.status) {
programs = programsResult.data!!
totalMediaCount = totalMediaCountResult.data!!
} else {
throw IllegalArgumentException("Can't get data. $result")
}
}
}
| mit | dff4fb8c1df1bb5a997e29a2b05d73e6 | 25.72 | 109 | 0.637226 | 4.805755 | false | false | false | false |
MichaelRocks/paranoid | processor/src/main/kotlin/io/michaelrocks/paranoid/processor/ParanoidProcessor.kt | 1 | 4398 | /*
* Copyright 2021 Michael Rozumyanskiy
*
* 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.michaelrocks.paranoid.processor
import com.joom.grip.Grip
import com.joom.grip.GripFactory
import com.joom.grip.io.DirectoryFileSink
import com.joom.grip.io.IoFactory
import com.joom.grip.mirrors.getObjectTypeByInternalName
import io.michaelrocks.paranoid.processor.commons.closeQuietly
import io.michaelrocks.paranoid.processor.logging.getLogger
import io.michaelrocks.paranoid.processor.model.Deobfuscator
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.commons.Method
import java.io.File
class ParanoidProcessor(
private val obfuscationSeed: Int,
private val inputs: List<File>,
private val outputs: List<File>,
private val genPath: File,
private val classpath: Collection<File>,
private val bootClasspath: Collection<File>,
private val projectName: String,
private val asmApi: Int = Opcodes.ASM9,
) {
private val logger = getLogger()
private val grip: Grip = GripFactory.newInstance(asmApi).create(inputs + classpath + bootClasspath)
private val stringRegistry = StringRegistryImpl(obfuscationSeed)
fun process() {
dumpConfiguration()
require(inputs.size == outputs.size) {
"Input collection $inputs and output collection $outputs have different sizes"
}
val analysisResult = Analyzer(grip).analyze(inputs)
analysisResult.dump()
val deobfuscator = createDeobfuscator()
logger.info("Prepare to generate {}", deobfuscator)
val sourcesAndSinks = inputs.zip(outputs) { input, output ->
IoFactory.createFileSource(input) to IoFactory.createFileSink(input, output)
}
try {
Patcher(deobfuscator, stringRegistry, analysisResult, grip.classRegistry, asmApi)
.copyAndPatchClasses(sourcesAndSinks)
DirectoryFileSink(genPath).use { sink ->
val deobfuscatorBytes = DeobfuscatorGenerator(deobfuscator, stringRegistry, grip.classRegistry)
.generateDeobfuscator()
sink.createFile("${deobfuscator.type.internalName}.class", deobfuscatorBytes)
}
} finally {
sourcesAndSinks.forEach { (source, sink) ->
source.closeQuietly()
sink.closeQuietly()
}
}
}
private fun dumpConfiguration() {
logger.info("Starting ParanoidProcessor:")
logger.info(" inputs = {}", inputs)
logger.info(" outputs = {}", outputs)
logger.info(" genPath = {}", genPath)
logger.info(" classpath = {}", classpath)
logger.info(" bootClasspath = {}", bootClasspath)
logger.info(" projectName = {}", projectName)
}
private fun AnalysisResult.dump() {
if (configurationsByType.isEmpty()) {
logger.info("No classes to obfuscate")
} else {
logger.info("Classes to obfuscate:")
configurationsByType.forEach {
val (type, configuration) = it
logger.info(" {}:", type.internalName)
configuration.constantStringsByFieldName.forEach {
val (field, string) = it
logger.info(" {} = \"{}\"", field, string)
}
}
}
}
private fun createDeobfuscator(): Deobfuscator {
val deobfuscatorInternalName = "io/michaelrocks/paranoid/Deobfuscator${composeDeobfuscatorNameSuffix()}"
val deobfuscatorType = getObjectTypeByInternalName(deobfuscatorInternalName)
val deobfuscationMethod = Method("getString", Type.getType(String::class.java), arrayOf(Type.LONG_TYPE))
return Deobfuscator(deobfuscatorType, deobfuscationMethod)
}
private fun composeDeobfuscatorNameSuffix(): String {
val normalizedProjectName = projectName.filter { it.isLetterOrDigit() || it == '_' || it == '$' }
return if (normalizedProjectName.isEmpty() || normalizedProjectName.startsWith('$')) {
normalizedProjectName
} else {
"$$normalizedProjectName"
}
}
}
| apache-2.0 | 1b2fd15320260ad24a39047325c800e7 | 35.04918 | 108 | 0.711005 | 4.11028 | false | false | false | false |
ReepicheepRed/PhotoMark-official | app/src/main/java/me/jessyan/mvparms/photomark/mvp/presenter/SettingPresenter.kt | 1 | 2419 | package me.jessyan.mvparms.photomark.mvp.presenter
import android.app.Application
import android.view.View
import com.jess.arms.base.AppManager
import com.jess.arms.base.DefaultAdapter
import com.jess.arms.di.scope.ActivityScope
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.UiUtils.makeText
import com.jess.arms.widget.imageloader.ImageLoader
import me.jessyan.mvparms.photomark.mvp.contract.SettingContract
import me.jessyan.mvparms.photomark.mvp.ui.adapter.SettingAdapter
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import javax.inject.Inject
/**
* 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
* 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
* 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
* 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
* 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
* 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
*/
/**
* Created by zhiPeng.S on 2017/6/6.
*/
@ActivityScope
class SettingPresenter @Inject
constructor(model: SettingContract.Model, rootView: SettingContract.View, private var mErrorHandler: RxErrorHandler?, private var mApplication: Application?, private var mImageLoader: ImageLoader?, private var mAppManager: AppManager?) : BasePresenter<SettingContract.Model, SettingContract.View>(model, rootView),DefaultAdapter.OnRecyclerViewItemClickListener<String> {
var adapter : DefaultAdapter<*>? = null
val items = listOf("Email Us", "Rate & Review", "Share", "Clean cache", "Facebook", "Instagram", "Twitter")
init {
adapter = SettingAdapter(items)
adapter?.setOnItemClickListener(this)
mRootView.setAdapter(adapter!!)
}
override fun onItemClick(view: View?, data: String?, position: Int) {
makeText(data)
}
override fun onDestroy() {
super.onDestroy()
this.mErrorHandler = null
this.mAppManager = null
this.mImageLoader = null
this.mApplication = null
}
} | apache-2.0 | 2c0d4d518ed7d44fd347a7c7e42fed4b | 35.678571 | 370 | 0.773502 | 3.427379 | false | false | false | false |
microg/android_packages_apps_GmsCore | play-services-maps-core-mapbox/src/main/kotlin/org/microg/gms/maps/mapbox/model/Circle.kt | 1 | 4837 | /*
* Copyright (C) 2019 microG Project Team
*
* 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.microg.gms.maps.mapbox.model
import android.os.Parcel
import android.util.Log
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.internal.ICircleDelegate
import com.mapbox.mapboxsdk.plugins.annotation.Circle
import com.mapbox.mapboxsdk.plugins.annotation.CircleOptions
import com.mapbox.mapboxsdk.utils.ColorUtils
import org.microg.gms.maps.mapbox.GoogleMapImpl
import org.microg.gms.maps.mapbox.utils.toMapbox
import com.google.android.gms.maps.model.CircleOptions as GmsCircleOptions
class CircleImpl(private val map: GoogleMapImpl, private val id: String, options: GmsCircleOptions) : ICircleDelegate.Stub(), Markup<Circle, CircleOptions> {
private var center: LatLng = options.center
private var radius: Double = options.radius
private var strokeWidth: Float = options.strokeWidth
private var strokeColor: Int = options.strokeColor
private var fillColor: Int = options.fillColor
private var visible: Boolean = options.isVisible
override var annotation: Circle? = null
override var removed: Boolean = false
override val annotationOptions: CircleOptions
get() = CircleOptions()
.withLatLng(center.toMapbox())
.withCircleColor(ColorUtils.colorToRgbaString(fillColor))
.withCircleRadius(radius.toFloat())
.withCircleStrokeColor(ColorUtils.colorToRgbaString(strokeColor))
.withCircleStrokeWidth(strokeWidth / map.dpiFactor)
.withCircleOpacity(if (visible) 1f else 0f)
.withCircleStrokeOpacity(if (visible) 1f else 0f)
override fun remove() {
removed = true
map.circleManager?.let { update(it) }
}
override fun getId(): String = id
override fun setCenter(center: LatLng) {
this.center = center
annotation?.latLng = center.toMapbox()
map.circleManager?.let { update(it) }
}
override fun getCenter(): LatLng = center
override fun setRadius(radius: Double) {
this.radius = radius
annotation?.circleRadius = radius.toFloat()
map.circleManager?.let { update(it) }
}
override fun getRadius(): Double = radius
override fun setStrokeWidth(width: Float) {
this.strokeWidth = width
annotation?.circleStrokeWidth = width / map.dpiFactor
map.circleManager?.let { update(it) }
}
override fun getStrokeWidth(): Float = strokeWidth
override fun setStrokeColor(color: Int) {
this.strokeColor = color
annotation?.setCircleStrokeColor(color)
map.circleManager?.let { update(it) }
}
override fun getStrokeColor(): Int = strokeColor
override fun setFillColor(color: Int) {
this.fillColor = color
annotation?.setCircleColor(color)
map.circleManager?.let { update(it) }
}
override fun getFillColor(): Int = fillColor
override fun setZIndex(zIndex: Float) {
Log.d(TAG, "unimplemented Method: setZIndex")
}
override fun getZIndex(): Float {
Log.d(TAG, "unimplemented Method: getZIndex")
return 0f
}
override fun setVisible(visible: Boolean) {
this.visible = visible
annotation?.circleOpacity = if (visible) 1f else 0f
annotation?.circleStrokeOpacity = if (visible) 1f else 0f
map.circleManager?.let { update(it) }
}
override fun isVisible(): Boolean = visible
override fun equalsRemote(other: ICircleDelegate?): Boolean = equals(other)
override fun hashCodeRemote(): Int = hashCode()
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String {
return id
}
override fun equals(other: Any?): Boolean {
if (other is CircleImpl) {
return other.id == id
}
return false
}
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean =
if (super.onTransact(code, data, reply, flags)) {
true
} else {
Log.d(TAG, "onTransact [unknown]: $code, $data, $flags"); false
}
companion object {
val TAG = "GmsMapCircle"
}
} | apache-2.0 | 09d4802b050bb43e75cb99d844f54112 | 32.597222 | 157 | 0.67087 | 4.345912 | false | false | false | false |
weiweiwitch/third-lab | src/main/kotlin/com/ariane/thirdlab/controller/PostTagController.kt | 1 | 5016 | package com.ariane.thirdlab.controller
import com.ariane.thirdlab.controller.resp.TlBaseResp
import com.ariane.thirdlab.domains.PostTag
import com.ariane.thirdlab.repositories.PostRepository
import com.ariane.thirdlab.repositories.PostTagRepository
import com.ariane.thirdlab.rtcode.CANT_DEL_NO_EMPTY_TAG
import com.ariane.thirdlab.rtcode.CANT_DEL_PARENT_TAG
import com.ariane.thirdlab.rtcode.POST_TAG_NOT_FOUND
import com.ariane.thirdlab.rtcode.SUCCESS
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.transaction.Transactional
@RestController
@RequestMapping("/api", produces = ["application/json"])
@Transactional
open class PostTagController() {
@Autowired
lateinit var postRepository: PostRepository
@Autowired
lateinit var postTagRepository: PostTagRepository
data class PostTagResp(
val id: Long,
val tagName: String,
val num: Long,
val parentTagId: Long,
val nodes: MutableList<PostTagResp>
)
data class PostTagContainer(
val tree: List<PostTagResp>,
val list: List<PostTagResp>
)
@GetMapping("tags")
open fun findAllTags(): TlBaseResp<PostTagContainer> {
val postTags = postTagRepository.findAll()
// 建立临时表
val tmpList = mutableListOf<PostTagResp>()
val tmpMap = mutableMapOf<Long, PostTagResp>()
for (eachPostTag in postTags) {
val num = postRepository.countByTagId(eachPostTag.id)
val postTagResp = PostTagResp(
eachPostTag.id,
eachPostTag.tag,
num,
eachPostTag.parentTagId,
mutableListOf<PostTagResp>()
)
tmpList += postTagResp
tmpMap[eachPostTag.id] = postTagResp
}
// 整理出根元素
val rootList = mutableListOf<PostTagResp>()
for (eachResp in tmpList) {
if (eachResp.parentTagId == 0L) {
rootList += eachResp
} else {
val parentTagResp = tmpMap[eachResp.parentTagId]
if (parentTagResp != null) {
parentTagResp.nodes += eachResp
} else {
rootList += eachResp
}
}
}
// 对最上层排序
rootList.sortByDescending {
it.tagName
}
val container = PostTagContainer(rootList, tmpList)
val resp = TlBaseResp<PostTagContainer>(SUCCESS)
resp.data = container
return resp
}
data class AddTagReq(val parentTagId: Long, val name: String)
@PostMapping("/tags")
open fun addPostTag(@RequestBody req: AddTagReq): TlBaseResp<Int?> {
val parentTagId = req.parentTagId
if (parentTagId != 0L) {
val parentTagVal = postTagRepository.findById(parentTagId)
if (!parentTagVal.isPresent) {
return TlBaseResp<Int?>(POST_TAG_NOT_FOUND)
}
}
// 创建新标签
val postTag = PostTag()
postTag.tag = req.name
postTag.parentTagId = req.parentTagId
postTagRepository.save(postTag)
// 将只属于父标签的文章迁移到子标签下
if (parentTagId != 0L) {
val newTagId = postTag.id
val postTagsOwnedByParent = postRepository.findByTagId(parentTagId)
for (eachPostTag in postTagsOwnedByParent) {
eachPostTag.tagId = newTagId
}
}
val resp = TlBaseResp<Int?>(SUCCESS)
return resp
}
data class UpdateTagReq(val parentTagId: Long, val name: String)
data class UpdateTagResp(val id: Long)
@PutMapping("/tags/{id}")
open fun updateTag(@PathVariable id: Long, @RequestBody req: UpdateTagReq): TlBaseResp<UpdateTagResp?> {
val tagVal = postTagRepository.findById(id)
if (!tagVal.isPresent) {
return TlBaseResp<UpdateTagResp?>(POST_TAG_NOT_FOUND)
}
val tag = tagVal.get()
tag.parentTagId = req.parentTagId
tag.tag = req.name
val resp = TlBaseResp<UpdateTagResp?>(SUCCESS)
resp.data = UpdateTagResp(tag.id)
return resp
}
@DeleteMapping("/tags/{id}")
open fun delTag(@PathVariable id: Long): TlBaseResp<Int?> {
val postTagVal = postTagRepository.findById(id)
if (!postTagVal.isPresent) {
return TlBaseResp<Int?>(POST_TAG_NOT_FOUND)
}
val subTags = postTagRepository.findByParentTagId(id)
if (subTags.size > 0) {
return TlBaseResp<Int?>(CANT_DEL_PARENT_TAG)
}
val posts = postRepository.findByTagId(id)
if (posts.size > 0) {
return TlBaseResp<Int?>(CANT_DEL_NO_EMPTY_TAG)
}
val postTag = postTagVal.get()
postTagRepository.delete(postTag)
return TlBaseResp<Int?>(SUCCESS)
}
} | mit | 10649c08cbfeec11be5c2657d1b236bf | 30.259494 | 108 | 0.617051 | 4.132218 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/ui/detail/MediathekDetailActivity.kt | 1 | 1659 | package de.christinecoenen.code.zapp.app.mediathek.ui.detail
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import de.christinecoenen.code.zapp.R
import de.christinecoenen.code.zapp.models.shows.MediathekShow
class MediathekDetailActivity : AppCompatActivity() {
companion object {
private const val EXTRA_SHOW = "de.christinecoenen.code.zapp.EXTRA_SHOW"
@JvmStatic
fun getStartIntent(context: Context?, show: MediathekShow?): Intent {
return Intent(context, MediathekDetailActivity::class.java).apply {
action = Intent.ACTION_VIEW
putExtra(EXTRA_SHOW, show)
}
}
}
private lateinit var show: MediathekShow
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mediathek_detail)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
show = intent.extras!!.getSerializable(EXTRA_SHOW) as MediathekShow
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.add(R.id.container, MediathekDetailFragment.getInstance(show), "MediathekDetailFragment")
.commit()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_mediathek_detail, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_share -> {
show.shareExternally(this)
true
}
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| mit | 29abbcd7823d5e41351b09417dda98ef | 24.921875 | 94 | 0.755274 | 3.796339 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/TagManager.kt | 1 | 4749 | /*
* Copyright (c) 2021 David Allison <[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.libanki
import com.ichi2.libanki.backend.model.TagUsnTuple
import net.ankiweb.rsdroid.RustCleanup
/**
* Manages the tag cache and tags for notes.
*
* This is the public API surface for tags, to unify [Tags] and [TagsV16]
*/
@RustCleanup("remove docs: this exists to unify Tags.java and TagsV16")
abstract class TagManager {
/*
* Registry save/load
* ***********************************************************
*/
@RustCleanup("Tags.java only")
abstract fun load(json: String)
@RustCleanup("Tags.java only")
abstract fun flush()
/*
* Registering and fetching tags
* ***********************************************************
*/
/** Given a list of tags, add any missing ones to tag registry. */
fun register(tags: Iterable<String>) = register(tags, null)
/** Given a list of tags, add any missing ones to tag registry. */
fun register(tags: Iterable<String>, usn: Int? = null) = register(tags, usn, false)
/** Given a list of tags, add any missing ones to tag registry.
* @param clear_first Whether to clear the tags in the database before registering the provided tags
* */
abstract fun register(tags: Iterable<String>, usn: Int? = null, clear_first: Boolean = false)
abstract fun all(): List<String>
/** Add any missing tags from notes to the tags list. The old list is cleared first */
fun registerNotes() = registerNotes(null)
/**
* Add any missing tags from notes to the tags list.
* @param nids The old list is cleared first if this is null
*/
abstract fun registerNotes(nids: kotlin.collections.Collection<Long>? = null)
abstract fun allItems(): Iterable<TagUsnTuple>
@RustCleanup("Tags.java only")
abstract fun save()
/**
* byDeck returns the tags of the cards in the deck
* @param did the deck id
* @param children whether to include the deck's children
* @return a list of the tags
*/
abstract fun byDeck(did: DeckId, children: Boolean = false): List<String>
/*
* Bulk addition/removal from notes
* ***********************************************************
*/
/* Legacy signature, currently only used by unit tests. New code in TagsV16
takes two args. */
abstract fun bulkAdd(ids: List<Long>, tags: String, add: Boolean = true)
/*
* String-based utilities
* ***********************************************************
*/
/** Parse a string and return a list of tags. */
abstract fun split(tags: String): MutableList<String>
/** Join tags into a single string, with leading and trailing spaces. */
abstract fun join(tags: kotlin.collections.Collection<String>): String
/** Delete tags if they exist. */
abstract fun remFromStr(deltags: String, tags: String): String
/*
* List-based utilities
* ***********************************************************
*/
/** Strip duplicates, adjust case to match existing tags, and sort. */
@RustCleanup("List, not Collection")
abstract fun canonify(tagList: List<String>): java.util.AbstractSet<String>
/** @return True if TAG is in TAGS. Ignore case. */
abstract fun inList(tag: String, tags: Iterable<String>): Boolean
/*
* Sync handling
* ***********************************************************
*/
@RustCleanup("Tags.java only")
abstract fun beforeUpload()
/*
* ***********************************************************
* The methods below are not in LibAnki.
* ***********************************************************
*/
/** Add a tag to the collection. We use this method instead of exposing mTags publicly.*/
abstract fun add(tag: String, usn: Int?)
/** Whether any tags have a usn of -1 */
@RustCleanup("not optimised")
open fun minusOneValue(): Boolean {
TODO("obsolete when moving to backend for sync")
// allItems().any { it.usn == -1 }
}
}
| gpl-3.0 | 61366fcdd8c00ff0232330b0d7851074 | 36.101563 | 104 | 0.595704 | 4.531489 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/user/LinksAdapter.kt | 1 | 1338 | package de.westnordost.streetcomplete.user
import android.view.LayoutInflater
import android.view.ViewGroup
import de.westnordost.streetcomplete.data.user.achievements.Link
import de.westnordost.streetcomplete.databinding.RowLinkItemBinding
import de.westnordost.streetcomplete.view.ListAdapter
/** Adapter for a list of links */
class LinksAdapter(links: List<Link>, private val onClickLink: (url: String) -> Unit)
: ListAdapter<Link>(links) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(RowLinkItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
inner class ViewHolder(val binding: RowLinkItemBinding) : ListAdapter.ViewHolder<Link>(binding) {
override fun onBind(with: Link) {
if (with.icon != null) {
binding.linkIconImageView.setImageResource(with.icon)
} else {
binding.linkIconImageView.setImageDrawable(null)
}
binding.linkTitleTextView.text = with.title
if (with.description != null) {
binding.linkDescriptionTextView.setText(with.description)
} else {
binding.linkDescriptionTextView.text = ""
}
itemView.setOnClickListener { onClickLink(with.url) }
}
}
}
| gpl-3.0 | c17a52ee03901689bd894cd36dc7b8fa | 40.8125 | 101 | 0.685351 | 4.727915 | false | false | false | false |
pdvrieze/ProcessManager | java-common/src/commonMain/kotlin/net/devrieze/util/TypecheckingCollection.kt | 1 | 2192 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package net.devrieze.util
import kotlin.reflect.KClass
class TypecheckingCollection<E:Any>(private val type: KClass<out E>, private val delegate: MutableCollection<E>): AbstractMutableCollection<E>() {
override val size: Int get() = delegate.size
override fun add(element: E): Boolean {
if (!type.isInstance(element)) throw ClassCastException("The element $element is not of type $type")
return delegate.add(element)
}
override fun iterator(): MutableIterator<E> = delegate.iterator()
}
class TypecheckingList<E:Any>(private val type: KClass<out E>, private val delegate: MutableList<E>): AbstractMutableList<E>() {
override val size: Int get() = delegate.size
override fun add(element: E): Boolean {
if (!type.isInstance(element)) throw ClassCastException("The element $element is not of type $type")
return delegate.add(element)
}
override fun add(index: Int, element: E) {
if (!type.isInstance(element)) throw ClassCastException("The element $element is not of type $type")
delegate.add(index, element)
}
override fun set(index: Int, element: E): E {
if (!type.isInstance(element)) throw ClassCastException("The element $element is not of type $type")
return delegate.set(index, element)
}
override fun iterator(): MutableIterator<E> = delegate.iterator()
override fun get(index: Int): E = delegate.get(index)
override fun removeAt(index: Int): E = delegate.removeAt(index)
}
| lgpl-3.0 | 5b67291b506a3eada6ccd27b996de216 | 38.854545 | 146 | 0.712591 | 4.264591 | false | false | false | false |
aCoder2013/general | general-gossip/src/main/java/com/song/general/gossip/net/support/ChannelAdapter.kt | 1 | 1219 | package com.song.general.gossip.net.support
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import java.net.SocketAddress
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Created by song on 2017/8/23.
*/
class ChannelAdapter(private val address: SocketAddress) {
@Volatile var channelFuture: ChannelFuture? = null
set(channelFuture) {
field = channelFuture
this.countDownLatch.countDown()
}
private val countDownLatch = CountDownLatch(1)
val isOk: Boolean
get() = this.channelFuture != null && this.channelFuture!!.channel() != null && this.channelFuture!!.channel()
.isActive
fun geChannel(): Channel {
if (!isOk) {
throw RuntimeException(
"Connection to node $address is currently not usable.")
}
return this.channelFuture!!.channel()
}
@Throws(InterruptedException::class)
fun await() {
this.countDownLatch.await()
}
@Throws(InterruptedException::class)
fun await(timeout: Long, timeUnit: TimeUnit): Boolean {
return this.countDownLatch.await(timeout, timeUnit)
}
}
| apache-2.0 | 307e8729a07c8770b78fe0acd11c9425 | 26.704545 | 118 | 0.657096 | 4.582707 | false | false | false | false |
googlesamples/mlkit | android/digitalink/app/src/main/java/com/google/mlkit/samples/vision/digitalink/kotlin/ModelManager.kt | 1 | 4057 | package com.google.mlkit.samples.vision.digitalink.kotlin
import android.util.Log
import com.google.android.gms.tasks.SuccessContinuation
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.mlkit.common.MlKitException
import com.google.mlkit.common.model.DownloadConditions
import com.google.mlkit.common.model.RemoteModelManager
import com.google.mlkit.vision.digitalink.DigitalInkRecognition
import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModel
import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModelIdentifier
import com.google.mlkit.vision.digitalink.DigitalInkRecognizer
import com.google.mlkit.vision.digitalink.DigitalInkRecognizerOptions
import java.util.HashSet
/** Class to manage model downloading, deletion, and selection. */
class ModelManager {
private var model: DigitalInkRecognitionModel? = null
var recognizer: DigitalInkRecognizer? = null
val remoteModelManager = RemoteModelManager.getInstance()
fun setModel(languageTag: String): String {
// Clear the old model and recognizer.
model = null
recognizer?.close()
recognizer = null
// Try to parse the languageTag and get a model from it.
val modelIdentifier: DigitalInkRecognitionModelIdentifier?
modelIdentifier = try {
DigitalInkRecognitionModelIdentifier.fromLanguageTag(languageTag)
} catch (e: MlKitException) {
Log.e(
TAG,
"Failed to parse language '$languageTag'"
)
return ""
} ?: return "No model for language: $languageTag"
// Initialize the model and recognizer.
model = DigitalInkRecognitionModel.builder(modelIdentifier).build()
recognizer = DigitalInkRecognition.getClient(
DigitalInkRecognizerOptions.builder(model!!).build()
)
Log.i(
TAG, "Model set for language '$languageTag' ('$modelIdentifier.languageTag')."
)
return "Model set for language: $languageTag"
}
fun checkIsModelDownloaded(): Task<Boolean?> {
return remoteModelManager.isModelDownloaded(model!!)
}
fun deleteActiveModel(): Task<String?> {
if (model == null) {
Log.i(TAG, "Model not set")
return Tasks.forResult("Model not set")
}
return checkIsModelDownloaded()
.onSuccessTask { result: Boolean? ->
if (!result!!) {
return@onSuccessTask Tasks.forResult("Model not downloaded yet")
}
remoteModelManager
.deleteDownloadedModel(model!!)
.onSuccessTask { _: Void? ->
Log.i(
TAG,
"Model successfully deleted"
)
Tasks.forResult(
"Model successfully deleted"
)
}
}
.addOnFailureListener { e: Exception ->
Log.e(
TAG,
"Error while model deletion: $e"
)
}
}
val downloadedModelLanguages: Task<Set<String>>
get() = remoteModelManager
.getDownloadedModels(DigitalInkRecognitionModel::class.java)
.onSuccessTask(
SuccessContinuation { remoteModels: Set<DigitalInkRecognitionModel>? ->
val result: MutableSet<String> = HashSet()
for (model in remoteModels!!) {
result.add(model.modelIdentifier.languageTag)
}
Log.i(
TAG,
"Downloaded models for languages:$result"
)
Tasks.forResult<Set<String>>(result.toSet())
}
)
fun download(): Task<String?> {
return if (model == null) {
Tasks.forResult("Model not selected.")
} else remoteModelManager
.download(model!!, DownloadConditions.Builder().build())
.onSuccessTask { _: Void? ->
Log.i(
TAG,
"Model download succeeded."
)
Tasks.forResult("Downloaded model successfully")
}
.addOnFailureListener { e: Exception ->
Log.e(
TAG,
"Error while downloading the model: $e"
)
}
}
companion object {
private const val TAG = "MLKD.ModelManager"
}
}
| apache-2.0 | 1cbbdee1f137c33bcaf4bc1dcb2c6586 | 31.456 | 84 | 0.659601 | 4.362366 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/dialogs/WhatsNewDialog.kt | 1 | 1588 | package org.tasks.dialogs
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import androidx.fragment.app.DialogFragment
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.billing.PurchaseActivity
import org.tasks.databinding.DialogWhatsNewBinding
import org.tasks.extensions.Context.openUri
import org.tasks.markdown.MarkdownProvider
import java.io.BufferedReader
import javax.inject.Inject
@AndroidEntryPoint
class WhatsNewDialog : DialogFragment() {
@Inject lateinit var dialogBuilder: DialogBuilder
@Inject lateinit var markdownProvider: MarkdownProvider
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogWhatsNewBinding.inflate(layoutInflater)
val textStream = requireContext().assets.open("CHANGELOG.md")
val text = BufferedReader(textStream.reader()).readText()
binding.changelog.movementMethod = LinkMovementMethod.getInstance()
markdownProvider
.markdown(linkify = true, force = true)
.setMarkdown(binding.changelog, text)
binding.dismissButton.setOnClickListener {
dismiss()
}
return dialogBuilder.newDialog()
.setView(binding.root)
.show()
}
private fun onSubscribeClick() {
dismiss()
startActivity(Intent(context, PurchaseActivity::class.java))
}
private fun onDonateClick() {
dismiss()
context?.openUri(R.string.url_donate)
}
} | gpl-3.0 | 4ccc9ecde2c68cc70a70c2a07f9cf0f4 | 30.156863 | 75 | 0.723552 | 4.886154 | false | false | false | false |
demmonic/KInject | src/main/java/info/demmonic/kinject/GetterTransformer.kt | 1 | 2690 | package info.demmonic.kinject
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.MethodNode
/**
* Represents a [Transformer] that adds a getter method
* to a specific class, for a specific field.
*
* @author Demmonic
*/
class GetterTransformer : Transformer {
var fieldClassName: String? = ""
var fieldName: String? = ""
var fieldDesc: String? = ""
var staticGetter: Boolean = false
var getterClassName: String? = ""
var getterName: String? = ""
var getterDesc: String? = ""
constructor() {
}
constructor(fieldClassName: String?,
fieldName: String?,
fieldDesc: String?,
staticGetter: Boolean = false,
getterClassName: String?,
getterName: String?,
getterDesc: String?) {
this.fieldClassName = fieldClassName
this.fieldName = fieldName
this.fieldDesc = fieldDesc
this.staticGetter = staticGetter
this.getterClassName = getterClassName
this.getterName = getterName
this.getterDesc = getterDesc
}
override fun transform(cl: NodeClassLoader) {
val fieldParent = cl.raw.values.findLast { n -> n.name.equals(fieldClassName) } ?:
throw IllegalArgumentException("Unable to find field node with name $fieldClassName")
val getterParent = cl.raw.values.findLast { n -> n.name.equals(getterClassName) } ?:
throw IllegalArgumentException("Unable to find getter node with name $getterClassName")
val field = fieldParent.typedFields.findLast { f -> f.name.equals(fieldName) && f.desc.equals(fieldDesc) } ?:
throw IllegalArgumentException("Unable to find field with the name $fieldName and the desc $fieldDesc")
val isStatic = (field.access and Opcodes.ACC_STATIC) != 0
if (!isStatic && staticGetter) {
throw IllegalArgumentException("Can't access instanced field from static getter...")
}
val mn = MethodNode(Opcodes.ACC_PUBLIC or (if (staticGetter) Opcodes.ACC_STATIC else 0), getterName, getterDesc, null, null)
if (!isStatic) {
// the field isn't static, so we need to reference our self (push 'this' onto stack)
mn.visitVarInsn(Opcodes.ALOAD, 0)
}
// push contents of the field onto the stack
mn.visitFieldInsn(if (isStatic) Opcodes.GETSTATIC else Opcodes.GETFIELD, fieldParent.name, field.name, field.desc)
// return the value of the field
mn.visitInsn(Type.getType(field.desc).getOpcode(Opcodes.IRETURN))
getterParent.methods.add(mn)
}
} | mit | 78528d0ce17908f0d00b3ff3a6781c28 | 35.863014 | 132 | 0.648327 | 4.543919 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/integration/crafttweaker/Thermopile.kt | 1 | 2567 | package com.cout970.magneticraft.systems.integration.crafttweaker
import com.cout970.magneticraft.api.internal.registries.generators.thermopile.ThermopileRecipeManager
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.item.IItemStack
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemBlock
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@ZenClass("mods.magneticraft.Thermopile")
@ZenRegister
object Thermopile {
@Suppress("DEPRECATION")
@ZenMethod
@JvmStatic
fun addRecipe(block: IItemStack, temperature: Float, conductivity: Float) {
CraftTweakerPlugin.delayExecution {
val stack = block.toStack()
val itemblock = stack.item as? ItemBlock
if (itemblock == null) {
ctLogError("[Thermopile] Invalid input stack: $block, not a block")
return@delayExecution
}
val state = itemblock.block.getStateFromMeta(stack.metadata)
addRecipe(state, temperature, conductivity)
}
}
@ZenMethod
@JvmStatic
fun addRecipe(blockstate: IBlockState, temperature: Float, conductivity: Float) {
CraftTweakerPlugin.delayExecution {
if (conductivity <= 0) {
ctLogError("[Thermopile] Invalid conductivity value: $conductivity")
return@delayExecution
}
val recipe = ThermopileRecipeManager.createRecipe(blockstate, temperature, conductivity)
applyAction("Adding $recipe") {
ThermopileRecipeManager.registerRecipe(recipe)
}
}
}
@Suppress("DEPRECATION")
@ZenMethod
@JvmStatic
fun removeRecipe(block: IItemStack) {
CraftTweakerPlugin.delayExecution {
val stack = block.toStack()
val itemblock = stack.item as? ItemBlock
if (itemblock == null) {
ctLogError("[Thermopile] Invalid input stack: $block, not a block")
return@delayExecution
}
val state = itemblock.block.getStateFromMeta(stack.metadata)
val recipe = ThermopileRecipeManager.findRecipe(state)
if (recipe == null) {
ctLogError("[Thermopile] Cannot remove recipe: No recipe found for $block ($state)")
return@delayExecution
}
applyAction("Removing $recipe") {
ThermopileRecipeManager.removeRecipe(recipe)
}
}
}
} | gpl-2.0 | 7bea4347d44d29ce03ffef3d155f417a | 31.506329 | 101 | 0.641995 | 4.780261 | false | false | false | false |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/explorer/fragments/ExplorerFragment.kt | 1 | 9045 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.feature.explorer.fragments
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.brackeys.ui.R
import com.brackeys.ui.data.utils.FileSorter
import com.brackeys.ui.databinding.FragmentExplorerBinding
import com.brackeys.ui.feature.explorer.adapters.DirectoryAdapter
import com.brackeys.ui.feature.explorer.viewmodel.ExplorerViewModel
import com.brackeys.ui.feature.main.adapters.TabAdapter
import com.brackeys.ui.feature.main.utils.OnBackPressedHandler
import com.brackeys.ui.filesystem.base.model.FileModel
import com.brackeys.ui.utils.extensions.*
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ExplorerFragment : Fragment(R.layout.fragment_explorer), OnBackPressedHandler {
private val viewModel: ExplorerViewModel by activityViewModels()
private lateinit var binding: FragmentExplorerBinding
private lateinit var navController: NavController
private lateinit var adapter: DirectoryAdapter
private var isClosing = false // TODO remove
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentExplorerBinding.bind(view)
navController = childFragmentManager
.fragment<NavHostFragment>(R.id.nav_host).navController
observeViewModel()
setSupportActionBar(binding.toolbar)
binding.swipeRefresh.setOnRefreshListener {
viewModel.filesUpdateEvent.call()
binding.swipeRefresh.isRefreshing = false
}
binding.directoryRecyclerView.setHasFixedSize(true)
binding.directoryRecyclerView.adapter = DirectoryAdapter().also {
adapter = it
}
adapter.setOnTabSelectedListener(object : TabAdapter.OnTabSelectedListener {
override fun onTabSelected(position: Int) {
if (!isClosing) {
isClosing = true
navigateBreadcrumb(adapter.currentList[position])
isClosing = false
}
}
})
binding.actionHome.setOnClickListener {
navigateBreadcrumb(adapter.currentList.first())
}
binding.actionPaste.setOnClickListener {
viewModel.pasteEvent.call()
}
binding.actionCreate.setOnClickListener {
viewModel.createEvent.call()
}
adapter.submitList(viewModel.tabsList)
}
override fun handleOnBackPressed(): Boolean {
return if (!viewModel.selectionEvent.value.isNullOrEmpty()) {
stopActionMode()
true
} else {
val target = adapter.currentList.lastIndex - 1
if (target > 0) {
navigateBreadcrumb(adapter.currentList[target])
} else {
navigateBreadcrumb(adapter.currentList.first())
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_explorer_default, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem?.actionView as? SearchView
searchView?.debounce(viewLifecycleOwner.lifecycleScope) {
viewModel.searchFile(it)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
val actionShowHidden = menu.findItem(R.id.action_show_hidden)
val actionOpenAs = menu.findItem(R.id.action_open_as)
val actionRename = menu.findItem(R.id.action_rename)
val actionProperties = menu.findItem(R.id.action_properties)
val actionCopyPath = menu.findItem(R.id.action_copy_path)
val sortByName = menu.findItem(R.id.sort_by_name)
val sortBySize = menu.findItem(R.id.sort_by_size)
val sortByDate = menu.findItem(R.id.sort_by_date)
actionShowHidden?.isChecked = viewModel.showHidden
val selectionSize = viewModel.selectionEvent.value?.size ?: 0
if (selectionSize > 1) { // if more than 1 file selected
actionOpenAs?.isVisible = false
actionRename?.isVisible = false
actionProperties?.isVisible = false
actionCopyPath?.isVisible = false
}
when (viewModel.sortMode) {
FileSorter.SORT_BY_NAME -> sortByName?.isChecked = true
FileSorter.SORT_BY_SIZE -> sortBySize?.isChecked = true
FileSorter.SORT_BY_DATE -> sortByDate?.isChecked = true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_copy -> viewModel.copyEvent.call()
R.id.action_cut -> viewModel.cutEvent.call()
R.id.action_delete -> viewModel.deleteEvent.call()
R.id.action_select_all -> viewModel.selectAllEvent.call()
R.id.action_open_as -> viewModel.openAsEvent.call()
R.id.action_rename -> viewModel.renameEvent.call()
R.id.action_properties -> viewModel.propertiesEvent.call()
R.id.action_copy_path -> viewModel.copyPathEvent.call()
R.id.action_create_zip -> viewModel.archiveEvent.call()
R.id.action_show_hidden -> viewModel.showHidden = !item.isChecked
R.id.sort_by_name -> viewModel.sortMode = FileSorter.SORT_BY_NAME
R.id.sort_by_size -> viewModel.sortMode = FileSorter.SORT_BY_SIZE
R.id.sort_by_date -> viewModel.sortMode = FileSorter.SORT_BY_DATE
}
return super.onOptionsItemSelected(item)
}
private fun observeViewModel() {
viewModel.toastEvent.observe(viewLifecycleOwner) {
context?.showToast(it)
}
viewModel.showAppBarEvent.observe(viewLifecycleOwner) {
binding.appBar.isVisible = it
}
viewModel.allowPasteFiles.observe(viewLifecycleOwner) {
binding.actionPaste.isVisible = it
binding.actionCreate.isVisible = !it
}
viewModel.tabEvent.observe(viewLifecycleOwner) {
navigateBreadcrumb(it)
}
viewModel.selectionEvent.observe(viewLifecycleOwner) {
if (it.isNotEmpty()) {
viewModel.allowPasteFiles.value = false
viewModel.tempFiles.clear()
startActionMode(it)
} else {
stopActionMode()
}
}
}
private fun startActionMode(list: List<FileModel>) {
binding.toolbar.title = list.size.toString()
binding.toolbar.replaceMenu(R.menu.menu_explorer_actions)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.toolbar.setNavigationOnClickListener {
stopActionMode()
}
}
private fun stopActionMode() {
viewModel.deselectAllEvent.call()
binding.toolbar.setTitle(R.string.label_local_storage)
binding.toolbar.replaceMenu(R.menu.menu_explorer_default)
supportActionBar?.setDisplayHomeAsUpEnabled(false)
}
private fun navigateBreadcrumb(tab: FileModel): Boolean {
return if (adapter.currentList.contains(tab)) {
val position = adapter.currentList.indexOf(tab)
val howMany = adapter.itemCount - 1 - position
val shouldPop = howMany > 0
if (shouldPop) {
navController.popBackStack(howMany)
for (i in 0 until howMany) {
adapter.close(adapter.itemCount - 1)
}
} else {
adapter.select(adapter.itemCount - 1)
}
shouldPop
} else {
viewModel.tabsList.replaceList(adapter.currentList + tab)
adapter.submitList(adapter.currentList + tab)
adapter.select(adapter.itemCount - 1)
false
}
}
} | apache-2.0 | a053fdaaf54476405b8063e6ab5997ce | 37.493617 | 85 | 0.661028 | 4.728176 | false | false | false | false |
nemerosa/ontrack | ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/general/AutoValidationStampPropertyExtensions.kt | 1 | 881 | package net.nemerosa.ontrack.kdsl.spec.extension.general
import net.nemerosa.ontrack.json.parse
import net.nemerosa.ontrack.kdsl.spec.Project
import net.nemerosa.ontrack.kdsl.spec.deleteProperty
import net.nemerosa.ontrack.kdsl.spec.getProperty
import net.nemerosa.ontrack.kdsl.spec.setProperty
var Project.autoValidationStampProperty: AutoValidationStampProperty?
get() = getProperty(AUTO_VALIDATION_STAMP_PROPERTY)?.parse()
set(value) {
if (value != null) {
setProperty(AUTO_VALIDATION_STAMP_PROPERTY, value)
} else {
deleteProperty(AUTO_VALIDATION_STAMP_PROPERTY)
}
}
const val AUTO_VALIDATION_STAMP_PROPERTY = "net.nemerosa.ontrack.extension.general.AutoValidationStampPropertyType"
data class AutoValidationStampProperty(
val autoCreate: Boolean = true,
val autoCreateIfNotPredefined: Boolean = false,
)
| mit | fb0b61028565cfd8a9e46f696bf411e8 | 35.708333 | 115 | 0.760499 | 4.13615 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/helper/VideoSettingsHelper.kt | 1 | 13628 | package de.xikolo.controllers.helper
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import de.xikolo.R
import de.xikolo.config.Config
import de.xikolo.config.Feature
import de.xikolo.managers.PermissionManager
import de.xikolo.models.VideoSubtitles
import de.xikolo.storages.ApplicationPreferences
import de.xikolo.utils.LanguageUtil
import de.xikolo.views.CustomFontTextView
class VideoSettingsHelper(private val context: Context, private val subtitles: List<VideoSubtitles>?, private val changeListener: OnSettingsChangeListener, private val clickListener: OnSettingsClickListener, private val videoInfoCallback: VideoInfoCallback) {
enum class VideoMode(val title: String) {
SD("SD"), HD("HD"), AUTO("Auto")
}
enum class PlaybackSpeed(val value: Float) {
X07(0.7f), X10(1.0f), X13(1.3f), X15(1.5f), X18(1.8f), X20(2.0f);
override fun toString(): String {
return "x$value"
}
companion object {
fun get(str: String?): PlaybackSpeed {
return when (str) {
"x0.7" -> X07
"x1.0" -> X10
"x1.3" -> X13
"x1.5" -> X15
"x1.8" -> X18
"x2.0" -> X20
else -> X10
}
}
}
}
private val inflater: LayoutInflater = LayoutInflater.from(context)
private val applicationPreferences: ApplicationPreferences = ApplicationPreferences()
var currentQuality: VideoMode = VideoMode.HD
var currentSpeed: PlaybackSpeed = PlaybackSpeed.X10
var currentVideoSubtitles: VideoSubtitles? = null
var isImmersiveModeEnabled: Boolean = false
init {
currentSpeed = applicationPreferences.videoPlaybackSpeed
currentQuality = when {
videoInfoCallback.isAvailable(VideoMode.HD) -> VideoMode.HD
videoInfoCallback.isAvailable(VideoMode.SD) -> VideoMode.SD
videoInfoCallback.isAvailable(VideoMode.AUTO) -> VideoMode.AUTO
else -> throw IllegalArgumentException("No video available")
}
subtitles?.let {
for (videoSubtitles in it) {
if (videoSubtitles.language == applicationPreferences.videoSubtitlesLanguage) {
currentVideoSubtitles = videoSubtitles
}
}
}
isImmersiveModeEnabled = applicationPreferences.isVideoShownImmersive
}
fun buildSettingsView(): ViewGroup {
val list = buildSettingsPanel(null)
list.addView(
buildSettingsItem(
R.string.icon_quality,
context.getString(R.string.video_settings_quality) + " " + context.getString(R.string.video_settings_separator) + " " + currentQuality.title +
if (videoInfoCallback.isOfflineAvailable(currentQuality)) " " + context.getString(R.string.video_settings_quality_offline) else "",
View.OnClickListener { clickListener.onQualityClick() },
false,
Config.FONT_MATERIAL
)
)
list.addView(
buildSettingsItem(
R.string.icon_speed,
context.getString(R.string.video_settings_speed) + " " + context.getString(R.string.video_settings_separator) + " " + currentSpeed.toString(),
View.OnClickListener { clickListener.onPlaybackSpeedClick() },
false,
Config.FONT_MATERIAL
)
)
if (subtitles?.isNotEmpty() == true) {
list.addView(
buildSettingsItem(
R.string.icon_subtitles,
context.getString(R.string.video_settings_subtitles) + currentVideoSubtitles?.let {
" " + context.getString(R.string.video_settings_separator) + " " + LanguageUtil.toNativeName(
it.language
)
} ?: "",
View.OnClickListener { clickListener.onSubtitleClick() },
false,
Config.FONT_MATERIAL
)
)
}
if (videoInfoCallback.isImmersiveModeAvailable()) {
list.addView(
buildImmersiveSettingsItem(list)
)
}
if (Feature.PIP && PermissionManager.hasPipPermission(context)) {
list.addView(
buildSettingsItem(
R.string.icon_pip,
context.getString(R.string.video_settings_pip),
View.OnClickListener { clickListener.onPipClick() },
false,
Config.FONT_MATERIAL
)
)
}
return list.parent as ViewGroup
}
fun buildQualityView(): ViewGroup {
val list = buildSettingsPanel(context.getString(R.string.video_settings_quality))
if (videoInfoCallback.isAvailable(VideoMode.AUTO)) {
list.addView(
buildSettingsItem(
null,
VideoMode.AUTO.title +
if (videoInfoCallback.isOfflineAvailable(VideoMode.AUTO)) " " + context.getString(R.string.video_settings_quality_offline) else "",
View.OnClickListener {
val oldQuality = currentQuality
currentQuality = VideoMode.AUTO
changeListener.onQualityChanged(oldQuality, currentQuality)
},
currentQuality == VideoMode.AUTO
)
)
}
if (videoInfoCallback.isAvailable(VideoMode.HD)) {
list.addView(
buildSettingsItem(
null,
VideoMode.HD.title +
if (videoInfoCallback.isOfflineAvailable(VideoMode.HD)) " " + context.getString(R.string.video_settings_quality_offline) else "",
View.OnClickListener {
val oldQuality = currentQuality
currentQuality = VideoMode.HD
changeListener.onQualityChanged(oldQuality, currentQuality)
},
currentQuality == VideoMode.HD
)
)
}
if (videoInfoCallback.isAvailable(VideoMode.SD)) {
list.addView(
buildSettingsItem(
null,
VideoMode.SD.title +
if (videoInfoCallback.isOfflineAvailable(VideoMode.SD)) " " + context.getString(R.string.video_settings_quality_offline) else "",
View.OnClickListener {
val oldQuality = currentQuality
currentQuality = VideoMode.SD
changeListener.onQualityChanged(oldQuality, currentQuality)
},
currentQuality == VideoMode.SD
)
)
}
return list.parent as ViewGroup
}
fun buildPlaybackSpeedView(): ViewGroup {
val list = buildSettingsPanel(context.getString(R.string.video_settings_speed))
for (speed in PlaybackSpeed.values()) {
list.addView(
buildSettingsItem(
null,
speed.toString(),
View.OnClickListener {
val oldSpeed = currentSpeed
currentSpeed = speed
changeListener.onPlaybackSpeedChanged(oldSpeed, currentSpeed)
},
currentSpeed == speed
)
)
}
return list.parent as ViewGroup
}
fun buildSubtitleView(): ViewGroup {
val list = buildSettingsPanel(
context.getString(R.string.video_settings_subtitles),
context.getString(R.string.icon_settings),
View.OnClickListener {
ContextCompat.startActivity(context, Intent(Settings.ACTION_CAPTIONING_SETTINGS), null)
}
)
list.addView(
buildSettingsItem(
null,
context.getString(R.string.video_settings_subtitles_none),
View.OnClickListener {
val oldVideoSubtitles = currentVideoSubtitles
currentVideoSubtitles = null
applicationPreferences.videoSubtitlesLanguage = null
changeListener.onSubtitleChanged(oldVideoSubtitles, currentVideoSubtitles)
},
currentVideoSubtitles == null
)
)
for (videoSubtitles in subtitles!!) {
list.addView(
buildSettingsItem(
null,
LanguageUtil.toNativeName(videoSubtitles.language) +
if (videoSubtitles.createdByMachine) " " + context.getString(R.string.video_settings_subtitles_generated) else "",
View.OnClickListener {
val oldVideoSubtitles = currentVideoSubtitles
currentVideoSubtitles = videoSubtitles
applicationPreferences.videoSubtitlesLanguage = videoSubtitles.language
changeListener.onSubtitleChanged(oldVideoSubtitles, currentVideoSubtitles)
},
currentVideoSubtitles == videoSubtitles
)
)
}
return list.parent as ViewGroup
}
@SuppressLint("InflateParams")
private fun buildSettingsPanel(title: String?): ViewGroup {
val list = inflater
.inflate(R.layout.container_video_settings, null)
.findViewById(R.id.content_settings) as LinearLayout
val titleView = list.findViewById(R.id.content_settings_title) as TextView
if (title != null) {
titleView.text = title
} else {
titleView.visibility = View.GONE
}
return list
}
private fun buildSettingsPanel(title: String?, icon: String, iconClickListener: View.OnClickListener): ViewGroup {
val panel = buildSettingsPanel(title)
val iconView = panel.findViewById(R.id.content_settings_icon) as TextView
iconView.text = icon
iconView.setOnClickListener(iconClickListener)
iconView.visibility = View.VISIBLE
return panel
}
@SuppressLint("InflateParams")
private fun buildSettingsItem(@StringRes icon: Int?, title: String, clickListener: View.OnClickListener, active: Boolean, font: String = Config.FONT_XIKOLO): ViewGroup {
val item = inflater.inflate(R.layout.item_video_settings, null) as LinearLayout
val iconView = item.findViewById(R.id.item_settings_icon) as CustomFontTextView
val titleView = item.findViewById(R.id.item_settings_title) as TextView
if (icon != null) {
iconView.setCustomFont(context, font)
iconView.setText(icon)
} else {
iconView.setText(R.string.icon_settings)
iconView.visibility = View.INVISIBLE
}
titleView.text = title
if (active) {
val activeColor = ContextCompat.getColor(context, R.color.apptheme_secondary)
iconView.setTextColor(activeColor)
titleView.setTextColor(activeColor)
}
item.setOnClickListener(clickListener)
return item
}
private fun buildImmersiveSettingsItem(parent: ViewGroup): View {
return buildSettingsItem(
if (isImmersiveModeEnabled) R.string.icon_show_fitting else R.string.icon_show_immersive,
if (isImmersiveModeEnabled) context.getString(R.string.video_settings_show_fitting) else context.getString(R.string.video_settings_show_immersive),
View.OnClickListener {
isImmersiveModeEnabled = !isImmersiveModeEnabled
applicationPreferences.isVideoShownImmersive = isImmersiveModeEnabled
changeListener.onImmersiveModeChanged(!isImmersiveModeEnabled, isImmersiveModeEnabled)
val index = parent.indexOfChild(it)
parent.removeViewAt(index)
parent.addView(buildImmersiveSettingsItem(parent), index)
},
false,
Config.FONT_MATERIAL
)
}
interface OnSettingsClickListener {
fun onQualityClick()
fun onPlaybackSpeedClick()
fun onSubtitleClick()
fun onPipClick()
}
// also invoked when old value equal to new value
interface OnSettingsChangeListener {
fun onQualityChanged(old: VideoMode, new: VideoMode)
fun onPlaybackSpeedChanged(old: PlaybackSpeed, new: PlaybackSpeed)
// subtitle is null if 'None' is selected
fun onSubtitleChanged(old: VideoSubtitles?, new: VideoSubtitles?)
fun onImmersiveModeChanged(old: Boolean, new: Boolean)
}
interface VideoInfoCallback {
fun isAvailable(videoMode: VideoMode): Boolean
fun isOfflineAvailable(videoMode: VideoMode): Boolean
fun isImmersiveModeAvailable(): Boolean
}
}
| bsd-3-clause | e4c80befa2b872887be51828227e07a4 | 37.173669 | 259 | 0.587027 | 5.239523 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | app/src/main/java/home/smart/fly/animations/utils/GenBitmapDelegate.kt | 1 | 2604 | package home.smart.fly.animations.utils
import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.view.PixelCopy
import android.view.SurfaceView
import android.view.View
/**
* @author rookie
* @since 12-14-2019
*/
class GenBitmapDelegate(private val activity: Activity) {
fun composeBitmap(background: Bitmap, foreground: Bitmap, left: Float, top: Float): Bitmap {
val result =
Bitmap.createBitmap(background.width, background.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(result)
canvas.drawBitmap(background, 0f, 0f, null)
canvas.drawBitmap(foreground, left, top, null)
canvas.save()
canvas.restore()
return result
}
@SuppressLint("NewApi")
fun getBitmapFromSurfaceView(surfaceView: SurfaceView, callback: (bitmap: Bitmap) -> Unit) {
val result = Bitmap.createBitmap(surfaceView.width,
surfaceView.height, Bitmap.Config.ARGB_8888)
if (SysUtil.Android8OrLater()) {
PixelCopy.request(surfaceView, result, { copyResult: Int ->
if (copyResult == PixelCopy.SUCCESS) {
callback(result)
}
}, Handler(Looper.getMainLooper()))
} else {
callback(result)
}
}
fun getBitmapOfScreenExclueSystemBar(viewRoot: View): Bitmap {
viewRoot.isDrawingCacheEnabled = true
val temp = viewRoot.drawingCache
val screenInfo: ScreenParam = getScreenInfo(activity)
val statusBarHeight: Int = getStatusBarHeight(activity)
val bitmap = Bitmap.createBitmap(temp, 0, statusBarHeight, screenInfo.width, screenInfo.height - statusBarHeight)
return bitmap
}
fun getBitmapByDrawCache(viewRoot: View): Bitmap {
viewRoot.isDrawingCacheEnabled = true
val bitmap = viewRoot.drawingCache
return bitmap
}
private fun getStatusBarHeight(activity: Activity): Int {
val rect = Rect()
activity.window.decorView.getWindowVisibleDisplayFrame(rect)
return rect.top
}
private fun getScreenInfo(activity: Activity): ScreenParam {
val dm = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(dm)
return ScreenParam(dm.widthPixels, dm.heightPixels)
}
private class ScreenParam internal constructor(var width: Int, var height: Int)
} | apache-2.0 | 0ce18e0d87c6b1e3fe4c308078114ab3 | 31.160494 | 121 | 0.680876 | 4.641711 | false | false | false | false |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/models/collections/Shuntsu.kt | 1 | 5020 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmahjan.models.collections
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.kotmahjan.models.IllegalShuntsuIdentifierException
/**
* Created by yuriel on 8/13/16.
* 順子に関するクラスです
* 暗順子と明順子の両方を扱います
*/
class Shuntsu(override var identifierTile: Hai?) : Mentsu() {
/**
* 順子であることがわかっている場合に利用します
* @param isOpen 明順子ならばtrue 暗順子ならばfalse
* @param identifierTile 順子の組の二番目
*/
@Throws(IllegalShuntsuIdentifierException::class)
constructor(isOpen: Boolean, identifierTile: Hai): this(identifierTile) {
setIdTile(identifierTile)
this.isOpen = isOpen
this.isMentsu = true
}
/**
* 順子であるかの判定も伴います
* @param isOpen 明順子ならばtrue 暗順子ならばfalseを入力して下さい
* @param tile1 1枚目
* @param tile2 2枚目
* @param tile3 3枚目
*/
constructor(isOpen: Boolean, tile1: Hai, tile2: Hai, tile3: Hai): this(tile2) {
var t1 = tile1
var t2 = tile2
var t3 = tile3
this.isOpen = isOpen
// TODO: 共通化
//ソートする
var s: Hai
if (t1.num > t2.num) {
s = t1
t1 = t2
t2 = s
}
if (t1.num > t3.num) {
s = t1
t1 = t3
t3 = s
}
if (t2.num > t3.num) {
s = t2
t2 = t3
t3 = s
}
this.isMentsu = check(t1, t2, t3)
if (!isMentsu) {
identifierTile = null
}
}
@Throws(IllegalShuntsuIdentifierException::class)
private fun setIdTile(identifierTile: Hai) {
if (identifierTile.isYaochu()) {
throw IllegalShuntsuIdentifierException(identifierTile)
}
this.identifierTile = identifierTile
}
override val fu: Int
get() = 0
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o !is Shuntsu) return false
if (isMentsu !== o.isMentsu) return false
if (isOpen !== o.isOpen) return false
return identifierTile === o.identifierTile
}
override fun hashCode(): Int {
var result: Int = if (identifierTile != null) identifierTile!!.hashCode() else 0
result = 31 * result + if (isMentsu) 1 else 0
result = 31 * result + if (isOpen) 1 else 0
return result
}
companion object {
/**
* 順子かどうかの判定を行ないます
* @param t1 1枚目
* @param t2 2枚目
* @param t3 3枚目
* @return 順子であればtrue 順子でなければfalse
*/
fun check(t1: Hai, t2: Hai, t3: Hai): Boolean {
var tile1 = t1
var tile2 = t2
var tile3 = t3
//Typeが違う場合false
if (tile1.type != tile2.type || tile2.type != tile3.type) {
return false
}
//字牌だった場合false
if (tile1.num == -1 || tile2.num == -1 || tile3.num == -1) {
return false
}
//ソートする
var s: Hai
if (tile1.num > tile2.num) {
s = tile1
tile1 = tile2
tile2 = s
}
if (tile1.num > tile3.num) {
s = tile1
tile1 = tile3
tile3 = s
}
if (tile2.num > tile3.num) {
s = tile2
tile2 = tile3
tile3 = s
}
//判定
return tile1.num + 1 == tile2.num && tile2.num + 1 == tile3.num
}
}
} | mit | 5a3d1f46cfc2b4aad62fd88a939b5095 | 28.26875 | 88 | 0.563434 | 3.568598 | false | false | false | false |
apixandru/intellij-community | python/openapi/src/com/jetbrains/python/packaging/requirement/PyRequirementVersion.kt | 8 | 1640 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.packaging.requirement
data class PyRequirementVersion(val epoch: String? = null,
val release: String,
val pre: String? = null,
val post: String? = null,
val dev: String? = null,
val local: String? = null) {
companion object {
@JvmStatic
fun release(release: String): PyRequirementVersion = PyRequirementVersion(release = release)
}
val presentableText: String
get() =
sequenceOf(epochPresentable(), release, pre, postPresentable(), devPresentable(), localPresentable())
.filterNotNull()
.joinToString(separator = "") { it }
private fun epochPresentable() = if (epoch == null) null else "$epoch!"
private fun postPresentable() = if (post == null) null else ".$post"
private fun devPresentable() = if (dev == null) null else ".$dev"
private fun localPresentable() = if (local == null) null else "+$local"
} | apache-2.0 | 15ce3ea89806dd139f691042ba2c2893 | 40.025 | 105 | 0.643902 | 4.581006 | false | false | false | false |
cashapp/sqldelight | extensions/coroutines-extensions/src/commonTest/kotlin/app/cash/sqldelight/coroutines/QueryAsFlowTest.kt | 1 | 3543 | package app.cash.sqldelight.coroutines
import app.cash.sqldelight.coroutines.Employee.Companion.MAPPER
import app.cash.sqldelight.coroutines.Employee.Companion.SELECT_EMPLOYEES
import app.cash.sqldelight.coroutines.Employee.Companion.USERNAME
import app.cash.sqldelight.coroutines.TestDb.Companion.TABLE_EMPLOYEE
import app.cash.turbine.test
import co.touchlab.stately.concurrency.AtomicInt
import co.touchlab.stately.concurrency.value
import kotlinx.coroutines.CoroutineStart.UNDISPATCHED
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class QueryAsFlowTest : DbTest {
override suspend fun setupDb(): TestDb = TestDb(testDriver())
@Test fun query() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asFlow()
.test {
awaitItem().assert {
hasRow("alice", "Alice Allison")
hasRow("bob", "Bob Bobberson")
hasRow("eve", "Eve Evenson")
}
cancel()
}
}
@Test fun queryEmitsWithoutSuspending() = runTest { db ->
val flow = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER).asFlow()
var seenValue = false
val collectJob = launch(start = UNDISPATCHED) {
flow.collect {
seenValue = true
}
}
assertTrue(seenValue)
collectJob.cancel()
}
@Test fun queryObservesNotification() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asFlow()
.test {
awaitItem().assert {
hasRow("alice", "Alice Allison")
hasRow("bob", "Bob Bobberson")
hasRow("eve", "Eve Evenson")
}
db.employee(Employee("john", "John Johnson"))
awaitItem().assert {
hasRow("alice", "Alice Allison")
hasRow("bob", "Bob Bobberson")
hasRow("eve", "Eve Evenson")
hasRow("john", "John Johnson")
}
cancel()
}
}
@Test fun queryNotNotifiedAfterCancel() = runTest { db ->
db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asFlow()
.test {
awaitItem().assert {
hasRow("alice", "Alice Allison")
hasRow("bob", "Bob Bobberson")
hasRow("eve", "Eve Evenson")
}
cancel()
db.employee(Employee("john", "John Johnson"))
yield() // Ensure any events can be delivered.
expectNoEvents()
}
}
@Test fun queryOnlyNotifiedAfterCollect() = runTest { db ->
val flow = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES, MAPPER)
.asFlow()
db.employee(Employee("john", "John Johnson"))
flow.test {
awaitItem().assert {
hasRow("alice", "Alice Allison")
hasRow("bob", "Bob Bobberson")
hasRow("eve", "Eve Evenson")
hasRow("john", "John Johnson")
}
cancel()
}
}
@Test fun queryCanBeCollectedMoreThanOnce() = runTest { db ->
val flow = db.createQuery(TABLE_EMPLOYEE, "$SELECT_EMPLOYEES WHERE $USERNAME = 'john'", MAPPER)
.asFlow()
.mapToOneNotNull(Dispatchers.Default)
val employee = Employee("john", "John Johnson")
val timesCancelled = AtomicInt(0)
repeat(5) {
launch {
flow.test {
assertEquals(employee, awaitItem())
cancel()
timesCancelled.incrementAndGet()
}
}
}
db.employee(employee)
while (timesCancelled.value != 5) {
yield()
}
}
}
| apache-2.0 | 8af2a5d07b3bbd2d5ab00a26d685080e | 26.465116 | 99 | 0.627999 | 4.039909 | false | true | false | false |
UnsignedInt8/d.Wallet-Core | android/lib/src/test/java/dWallet/u8/ScriptTests.kt | 1 | 4589 | package dwallet.u8
import dwallet.core.bitcoin.application.wallet.Address
import dwallet.core.bitcoin.application.wallet.Coins
import dwallet.core.bitcoin.script.*
import dwallet.core.extensions.*
import org.junit.Test
import java.util.*
import org.junit.Assert.*
/**
* Created by unsignedint8 on 8/22/17.
*/
class ScriptTests {
@Test
fun testStack() {
val s = Stack<Int>()
kotlin.repeat(5) { s.push(it) }
assertArrayEquals(arrayOf(2, 1, 0), s.take(3).reversed().toTypedArray())
}
@Test
fun testPuzzle() {
// answer https://blockchain.info/rawtx/09f691b2263260e71f363d1db51ff3100d285956a40cc0e4f8c8c2c4a80559b1
var signScript = "4c500100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c"
val ops3 = Interpreter.scriptToOps(signScript.hexToByteArray())
assertEquals("0100000000000000000000000000000000000000000000000000000000000000000000003BA3EDFD7A7B12B27AC72C3E67768F617FC81BC3888A51323A9FB8AA4B1E5E4A29AB5F49FFFF001D1DAC2B7C".toLowerCase(), ops3[0].second!!.toHexString())
assertEquals(1, ops3.size)
// puzzle https://blockchain.info/rawtx/a4bfa8ab6435ae5f25dae9d89e4eb67dfa94283ca751f393c1ddc5a837bbc31b
signScript = "493046022100bc4add188fd3f3857b66b71f83c558b84ccae792aa549c90a93dc7b0842ac2d1022100e2648f9998a32a01a6d6c25e62d6f385b42b6bed896539ce95547a9ee76473d101210368e828b31aeddf82a53bdf803065aac378b7c330299189d277c1ff182724c967"
val ops2 = Interpreter.scriptToOps(signScript.hexToByteArray())
assertEquals("3046022100bc4add188fd3f3857b66b71f83c558b84ccae792aa549c90a93dc7b0842ac2d1022100e2648f9998a32a01a6d6c25e62d6f385b42b6bed896539ce95547a9ee76473d101", ops2.first().second!!.toHexString())
assertEquals("1FMb8Jnn1jSh7yjDFfonC8xCCH3ittoEzB", Address(ops2.last().second!!, Coins.Bitcoin.pubkeyHashId).toString())
assertEquals(true, Interpreter.checkOpsValidity(ops2.map { it.first }))
val pubkeyScript = "aa206fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000087".hexToByteArray()
val ops = Interpreter.scriptToOps(pubkeyScript)
assertEquals(3, ops.size)
assertArrayEquals(arrayOf(Words.Crypto.OP_HASH256.raw, 32.toByte(), Words.Bitwise.OP_EQUAL.raw), ops.map { it.first }.toTypedArray())
}
@Test
fun testStandardP2PKH() {
var script = "48304502207fba64e8b5a5027ecc3acb6df9a666bc72feb668622b3b49f120967fd4b67a26022100978e3954c8ac40f19a80f787ad3ecce4f54b9a6155c7720246cfbf43c66e9a5f01410453e4880d737f41e8ece50b99f4524bad7ac10a6403fad016b7f606a09d0574bb13d5ae3ef3993f2c5f130987ce85a7796804f314b64a642a224c0c525b389dac"
var ops = Interpreter.scriptToOps(script.hexToByteArray())
assertEquals("19c7JHZoNK2XmvB1rznrjgpDfmxMvx2EWc", Address(ops.last().second!!, Coins.Bitcoin.pubkeyHashId).toString())
script = "76a914494294730abf03c846988654f15d1864469c737a88ac"
ops = Interpreter.scriptToOps(script.hexToByteArray())
assertArrayEquals(arrayOf(Words.Stack.OP_DUP.raw, Words.Crypto.OP_HASH160.raw, 20.toByte(), Words.Bitwise.OP_EQUALVERIFY.raw, Words.Crypto.OP_CHECKSIG.raw), ops.map { it.first }.toTypedArray())
assertEquals(true, Interpreter.isP2PKHOutScript(ops.map { it.first }))
}
@Test
fun testStandardP2SH() {
var script = "a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87"
var ops = Interpreter.scriptToOps(script.hexToByteArray())
assertEquals(3, ops.size)
assertEquals(true, Interpreter.isP2SHOutScript(ops.map { it.first }))
assertEquals("342ftSRCvFHfCeFFBuz4xwbeqnDw6BGUey", Address.pubkeyHashToMultisignatureAddress("19a7d869032368fd1f1e26e5e73a4ad0e474960e".hexToByteArray(), Coins.Bitcoin.scriptHashId))
}
@Test
fun testP2SHSignScript() {
// answer https://blockchain.info/tx/6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192
// question https://blockchain.info/tx/9c08a4d78931342b37fd5f72900fb9983087e6f46c4a097d8a1f52c74e28eaf6
val pubkeyScript = "a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87"
val pubkeyOps = Interpreter.scriptToOps(pubkeyScript.hexToByteArray())
val signScript = "5121029b6d2c97b8b7c718c325d7be3ac30f7c9d67651bce0c929f55ee77ce58efcf8451ae"
val signOps = Interpreter.scriptToOps(signScript.hexToByteArray())
println(signOps[1].second!!.toHexString())
println(Address(signOps[1].second!!, Coins.Bitcoin.pubkeyHashId).toString())
}
} | gpl-3.0 | ec456ebb68e4e11d6692f104db8380ea | 54.301205 | 301 | 0.784267 | 2.774486 | false | true | false | false |
codeka/wwmmo | common/src/main/kotlin/au/com/codeka/warworlds/common/sim/DesignHelper.kt | 1 | 2651 | package au.com.codeka.warworlds.common.sim
import au.com.codeka.warworlds.common.proto.Colony
import au.com.codeka.warworlds.common.proto.Design
import com.google.common.collect.Iterables
/**
* Helper class for working with ship and building designs.
*/
object DesignHelper {
/** Gets a list of all the [Design]s we have. */
val designs: List<Design>
get() = DesignDefinitions.designs.designs
/** Gets a list of all the [Design]s of the given [Design.DesignKind] we have. */
fun getDesigns(kind: Design.DesignKind): Iterable<Design> {
return Iterables.filter(designs) {
design -> design != null && design.design_kind == kind
}
}
/** Gets the [Design] with the given identifier. */
fun getDesign(type: Design.DesignType): Design {
for (design in designs) {
if (design.type == type) {
return design
}
}
throw IllegalStateException("No design with id=$type found.")
}
/** Gets the display name of the given design, correctly pluralized. */
fun getDesignName(design: Design, plural: Boolean): String {
return design.display_name.toString() + if (plural) "s" else ""
}
fun getDependenciesHtml(colony: Colony, design: Design): String {
return getDependenciesHtml(colony, design, 0)
}
/**
* Returns the dependencies of the given design a string for display to the user. Dependencies
* that we don't meet will be coloured red, those that we meet with be green.
*/
// TODO: localize this string
fun getDependenciesHtml(colony: Colony, design: Design, level: Int): String {
val required = StringBuilder()
required.append("Required: ")
var dependencies: List<Design.Dependency> = design.dependencies
if (level > 1) {
dependencies = design.upgrades[level - 2].dependencies
}
if (dependencies.isEmpty()) {
required.append("none")
} else {
for ((n, dep) in dependencies.withIndex()) {
if (n > 0) {
required.append(", ")
}
var isMet = false
for (building in colony.buildings) {
if (building.design_type == dep.type && building.level >= dep.level!!) {
isMet = true
break
}
}
val dependentDesign: Design = getDesign(dep.type!!)
required.append("<font color=\"")
required.append(if (isMet) "green" else "red")
required.append("\">")
required.append(dependentDesign.display_name)
if (dep.level!! > 1) {
required.append(" lvl ")
required.append(dep.level)
}
required.append("</font>")
}
}
return required.toString()
}
} | mit | c12703a48fd7a69d606fd57a178c199d | 31.740741 | 96 | 0.632591 | 4.016667 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.