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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/wizard/UIWizardUtil.kt | 1 | 4397 | // 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.
@file:JvmName("UIWizardUtil")
package com.intellij.ide.wizard
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.application.Experiments
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.UIBundle
import com.intellij.ui.dsl.builder.DslComponentProperty
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.gridLayout.GridLayout
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
import javax.swing.JLabel
val WizardContext.projectOrDefault get() = project ?: ProjectManager.getInstance().defaultProject
fun <T1, T2> T1.chain(f1: (T1) -> T2): NewProjectWizardStep
where T1 : NewProjectWizardStep, T2 : NewProjectWizardStep {
val s1 = f1(this)
return stepSequence(this, s1)
}
fun <T1, T2, T3> T1.chain(f1: (T1) -> T2, f2: (T2) -> T3): NewProjectWizardStep
where T1 : NewProjectWizardStep, T2 : NewProjectWizardStep, T3 : NewProjectWizardStep {
val s1 = f1(this)
val s2 = f2(s1)
return stepSequence(this, s1, s2)
}
fun <T1, T2, T3, T4> T1.chain(f1: (T1) -> T2, f2: (T2) -> T3, f3: (T3) -> T4): NewProjectWizardStep
where T1 : NewProjectWizardStep, T2 : NewProjectWizardStep, T3 : NewProjectWizardStep, T4 : NewProjectWizardStep {
val s1 = f1(this)
val s2 = f2(s1)
val s3 = f3(s2)
return stepSequence(this, s1, s2, s3)
}
fun <T1, T2, T3, T4, T5> T1.chain(f1: (T1) -> T2, f2: (T2) -> T3, f3: (T3) -> T4, f4: (T4) -> T5): NewProjectWizardStep
where T1 : NewProjectWizardStep, T2 : NewProjectWizardStep, T3 : NewProjectWizardStep, T4 : NewProjectWizardStep, T5 : NewProjectWizardStep {
val s1 = f1(this)
val s2 = f2(s1)
val s3 = f3(s2)
val s4 = f4(s3)
return stepSequence(this, s1, s2, s3, s4)
}
fun stepSequence(first: NewProjectWizardStep, vararg rest: NewProjectWizardStep): NewProjectWizardStep {
val steps = listOf(first) + rest
return object : AbstractNewProjectWizardStep(first) {
override fun setupUI(builder: Panel) {
for (step in steps) {
step.setupUI(builder)
}
}
override fun setupProject(project: Project) {
for (step in steps) {
step.setupProject(project)
}
}
}
}
fun DialogPanel.setMinimumWidthForAllRowLabels(width: Int) {
UIUtil.uiTraverser(this).asSequence()
.filterIsInstance<JLabel>()
.filter { isRowLabel(it) }
.forEach { it.setMinimumWidth(width) }
}
private fun isRowLabel(label: JLabel): Boolean {
val layout = (label.parent as? DialogPanel)?.layout as? GridLayout
if (layout == null) {
return false
}
val constraints = layout.getConstraints(label)
return label.getClientProperty(DslComponentProperty.ROW_LABEL) == true && constraints != null && constraints.gaps.left == 0
}
private fun JComponent.setMinimumWidth(width: Int) {
minimumSize = minimumSize.apply { this.width = width }
}
fun DialogPanel.withVisualPadding(topField: Boolean = false): DialogPanel {
if (Experiments.getInstance().isFeatureEnabled("new.project.wizard")) {
val top = if (topField) 20 else 15
border = IdeBorderFactory.createEmptyBorder(JBInsets(top, 20, 20, 20))
}
else {
val top = if (topField) 15 else 5
border = IdeBorderFactory.createEmptyBorder(JBInsets(top, 5, 0, 5))
}
return this
}
/**
* Notifies user-visible error if [execution] is failed.
*/
@ApiStatus.Experimental
fun NewProjectWizardStep.setupProjectSafe(
project: Project,
errorMessage: @NlsContexts.DialogMessage String,
execution: () -> Unit
) {
try {
execution()
}
catch (ex: Exception) {
logger<NewProjectWizardStep>().error(errorMessage, ex)
invokeAndWaitIfNeeded {
Messages.showErrorDialog(
project,
errorMessage + "\n" + ex.message.toString(),
UIBundle.message("error.project.wizard.new.project.title", context.isCreatingNewProjectInt)
)
}
}
}
| apache-2.0 | 0d2fcfe702af784beeb18bf8980d9be7 | 31.330882 | 158 | 0.723675 | 3.583537 | false | false | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMlSearchState.kt | 2 | 2771 | // 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.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.SearchRestartReason
import com.intellij.ide.actions.searcheverywhere.ml.features.FeaturesProviderCache
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereElementFeaturesProvider
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereStateFeaturesProvider
import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereModelProvider
import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereRankingModel
import com.intellij.internal.statistic.eventLog.events.EventPair
internal class SearchEverywhereMlSearchState(
private val sessionStartTime: Long, val searchStartTime: Long,
val searchIndex: Int, val searchStartReason: SearchRestartReason,
val tabId: String, val experimentGroup: Int, val orderByMl: Boolean,
val keysTyped: Int, val backspacesTyped: Int, private val searchQuery: String,
private val modelProvider: SearchEverywhereModelProvider,
private val providersCache: FeaturesProviderCache?
) {
val searchStateFeatures = SearchEverywhereStateFeaturesProvider().getSearchStateFeatures(tabId, searchQuery)
private val model: SearchEverywhereRankingModel by lazy {
SearchEverywhereRankingModel(modelProvider.getModel(tabId))
}
fun getElementFeatures(elementId: Int?,
element: Any,
contributor: SearchEverywhereContributor<*>,
priority: Int): SearchEverywhereMLItemInfo {
val features = arrayListOf<EventPair<*>>()
val contributorId = contributor.searchProviderId
SearchEverywhereElementFeaturesProvider.getFeatureProvidersForContributor(contributorId).forEach { provider ->
features.addAll(provider.getElementFeatures(element, sessionStartTime, searchQuery, priority, providersCache))
}
return SearchEverywhereMLItemInfo(elementId, contributorId, features)
}
fun getMLWeight(context: SearchEverywhereMLContextInfo,
elementFeatures: List<EventPair<*>>): Double {
val features = (context.features + elementFeatures + searchStateFeatures).associate { it.field.name to it.data }
return model.predict(features)
}
}
internal data class SearchEverywhereMLItemInfo(val id: Int?, val contributorId: String, val features: List<EventPair<*>>) {
fun featuresAsMap(): Map<String, Any> = features.mapNotNull {
val data = it.data
if (data == null) null else it.field.name to data
}.toMap()
} | apache-2.0 | bedca6d066205bc6fffd659c0d7dabd9 | 52.307692 | 158 | 0.786359 | 5.038182 | false | false | false | false |
AsamK/TextSecure | app/src/test/java/org/thoughtcrime/securesms/registration/secondary/SecondaryProvisioningCipherTest.kt | 2 | 2565 | package org.thoughtcrime.securesms.registration.secondary
import com.google.protobuf.ByteString
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.instanceOf
import org.hamcrest.Matchers.`is`
import org.junit.Test
import org.thoughtcrime.securesms.crypto.IdentityKeyUtil
import org.thoughtcrime.securesms.crypto.ProfileKeyUtil
import org.whispersystems.signalservice.internal.crypto.PrimaryProvisioningCipher
import org.whispersystems.signalservice.internal.push.ProvisioningProtos
import org.whispersystems.signalservice.internal.push.ProvisioningProtos.ProvisionMessage
import org.whispersystems.signalservice.internal.push.ProvisioningProtos.ProvisioningVersion
import java.util.UUID
class SecondaryProvisioningCipherTest {
@Test
fun decrypt() {
val provisioningCipher = SecondaryProvisioningCipher.generate()
val primaryIdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair()
val primaryProfileKey = ProfileKeyUtil.createNew()
val primaryProvisioningCipher = PrimaryProvisioningCipher(provisioningCipher.secondaryDevicePublicKey.publicKey)
val message = ProvisionMessage.newBuilder()
.setAciIdentityKeyPublic(ByteString.copyFrom(primaryIdentityKeyPair.publicKey.serialize()))
.setAciIdentityKeyPrivate(ByteString.copyFrom(primaryIdentityKeyPair.privateKey.serialize()))
.setProvisioningCode("code")
.setProvisioningVersion(ProvisioningVersion.CURRENT_VALUE)
.setNumber("+14045555555")
.setAci(UUID.randomUUID().toString())
.setProfileKey(ByteString.copyFrom(primaryProfileKey.serialize()))
val provisionMessage = ProvisioningProtos.ProvisionEnvelope.parseFrom(primaryProvisioningCipher.encrypt(message.build()))
val result = provisioningCipher.decrypt(provisionMessage)
assertThat(result, instanceOf(SecondaryProvisioningCipher.ProvisionDecryptResult.Success::class.java))
val success = result as SecondaryProvisioningCipher.ProvisionDecryptResult.Success
assertThat(success.uuid.toString(), `is`(message.aci))
assertThat(success.e164, `is`(message.number))
assertThat(success.identityKeyPair.serialize(), `is`(primaryIdentityKeyPair.serialize()))
assertThat(success.profileKey.serialize(), `is`(primaryProfileKey.serialize()))
assertThat(success.areReadReceiptsEnabled, `is`(message.readReceipts))
assertThat(success.primaryUserAgent, `is`(message.userAgent))
assertThat(success.provisioningCode, `is`(message.provisioningCode))
assertThat(success.provisioningVersion, `is`(message.provisioningVersion))
}
}
| gpl-3.0 | dfc688305bd5a0a28e7d67f493303781 | 49.294118 | 125 | 0.818324 | 4.794393 | false | true | false | false |
AsamK/TextSecure | app/src/test/java/org/thoughtcrime/securesms/database/model/MessageRecordTest_createNewContextWithAppendedDeleteJoinRequest.kt | 2 | 2951 | package org.thoughtcrime.securesms.database.model
import com.google.protobuf.ByteString
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is`
import org.junit.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.thoughtcrime.securesms.database.model.databaseprotos.DecryptedGroupV2Context
import org.thoughtcrime.securesms.groups.v2.ChangeBuilder
import org.thoughtcrime.securesms.util.Base64
import org.whispersystems.signalservice.api.util.UuidUtil
import org.whispersystems.signalservice.internal.push.SignalServiceProtos
import java.util.Random
import java.util.UUID
@Suppress("ClassName")
class MessageRecordTest_createNewContextWithAppendedDeleteJoinRequest {
/**
* Given a non-gv2 message, when I append, then I expect an assertion error
*/
@Test(expected = AssertionError::class)
fun throwOnNonGv2() {
val messageRecord = mock<MessageRecord> {
on { decryptedGroupV2Context } doReturn null
}
MessageRecord.createNewContextWithAppendedDeleteJoinRequest(messageRecord, 0, ByteString.EMPTY)
}
/**
* Given a gv2 empty change, when I append, then I expect an assertion error.
*/
@Test(expected = AssertionError::class)
fun throwOnEmptyGv2Change() {
val groupContext = DecryptedGroupV2Context.getDefaultInstance()
val messageRecord = mock<MessageRecord> {
on { decryptedGroupV2Context } doReturn groupContext
}
MessageRecord.createNewContextWithAppendedDeleteJoinRequest(messageRecord, 0, ByteString.EMPTY)
}
/**
* Given a gv2 requesting member change, when I append, then I expect new group context including the change with a new delete.
*/
@Test
fun appendDeleteToExistingContext() {
val alice = UUID.randomUUID()
val aliceByteString = UuidUtil.toByteString(alice)
val change = ChangeBuilder.changeBy(alice)
.requestJoin(alice)
.build()
.toBuilder()
.setRevision(9)
.build()
val context = DecryptedGroupV2Context.newBuilder()
.setContext(SignalServiceProtos.GroupContextV2.newBuilder().setMasterKey(ByteString.copyFrom(randomBytes())))
.setChange(change)
.build()
val messageRecord = mock<MessageRecord> {
on { decryptedGroupV2Context } doReturn context
}
val newEncodedBody = MessageRecord.createNewContextWithAppendedDeleteJoinRequest(messageRecord, 10, aliceByteString)
val newContext = DecryptedGroupV2Context.parseFrom(Base64.decode(newEncodedBody))
assertThat("revision updated to 10", newContext.change.revision, `is`(10))
assertThat("change should retain join request", newContext.change.newRequestingMembersList[0].uuid, `is`(aliceByteString))
assertThat("change should add delete request", newContext.change.deleteRequestingMembersList[0], `is`(aliceByteString))
}
private fun randomBytes(): ByteArray {
val bytes = ByteArray(32)
Random().nextBytes(bytes)
return bytes
}
}
| gpl-3.0 | c56f6dd7a90f0e27395ddfce90b633f3 | 34.554217 | 129 | 0.762453 | 4.333333 | false | true | false | false |
issuETH/issuETH | src/main/kotlin/kontinuum/ChainWatcher.kt | 1 | 3980 | package kontinuum
import kontinuum.model.config.Chain
import org.kethereum.ETH_IN_WEI
import org.kethereum.extensions.clean0xPrefix
import org.kethereum.extensions.prepend0xPrefix
import org.kethereum.functions.getTokenTransferTo
import org.kethereum.functions.getTokenTransferValue
import org.kethereum.functions.isTokenTransfer
import org.kethereum.rpc.EthereumRPC
import org.kethereum.rpc.toKethereumTransaction
import java.math.BigDecimal
import java.math.BigInteger
class StatefulChain(val chain: Chain, val ethereumRPC: EthereumRPC, var lastBlock: String)
fun watchChain() {
val statefulChains = ConfigProvider.config.chains.map {
StatefulChain(it, EthereumRPC(it.eth_rpc_url, okhttp = okhttp), "0x0")
}
while (true) {
Thread.sleep(1000)
for (statefulChain in statefulChains) {
try {
val newBlock = statefulChain.ethereumRPC.getBlockNumberString()
if (newBlock != null && newBlock != statefulChain.lastBlock) {
statefulChain.lastBlock = newBlock
processBlockNumber(newBlock, statefulChain)
}
} catch (e: Exception) {
println("problem at block ${statefulChain.lastBlock} " + e.message)
e.printStackTrace()
}
}
}
}
fun processBlockNumber(newBlock: String, statefulChain: StatefulChain) {
val transactions = statefulChain.ethereumRPC.getBlockByNumber(newBlock)?.transactions
println("New Block $newBlock on " + statefulChain.chain.name + " " + transactions?.size + " txs")
transactions?.forEach { tx ->
tx.to?.let { to ->
val kethereumTransaction = tx.toKethereumTransaction()
if (kethereumTransaction.isTokenTransfer()) {
activeIssues.filter { kethereumTransaction.getTokenTransferTo().cleanHex.toLowerCase() == it.address.clean0xPrefix().toLowerCase() }.forEach {
val value = kethereumTransaction.getTokenTransferValue()
val token = tokenMap[statefulChain.chain.networkId.toString()]!![to.clean0xPrefix().toLowerCase()]
if (token != null) {
val scaledValue = BigDecimal(value).divide(BigDecimal(BigInteger("10").pow(BigInteger(token.decimals).toInt())))
githubInteractor.addIssueComment(it.project, it.issue,
"new token-transfer [transaction on " + statefulChain.chain.name + "](" + statefulChain.chain.tx_base_url.replace("TXHASH", tx.hash.prepend0xPrefix()) + ")" +
" with value " + scaledValue + token.symbol,
it.installation)
} else {
githubInteractor.addIssueComment(it.project, it.issue,
"new unknown token-transfer [transaction on " + statefulChain.chain.name + "](" + statefulChain.chain.tx_base_url.replace("TXHASH", tx.hash.prepend0xPrefix()) + ")" +
" with value " + value + "<br/>The token must be registered here: [https://github.com/MyEtherWallet/ethereum-lists](https://github.com/MyEtherWallet/ethereum-lists)",
it.installation)
}
}
} else {
activeIssues.filter { it.address.clean0xPrefix() == to.clean0xPrefix() }.forEach {
val value = BigDecimal(BigInteger(tx.value.clean0xPrefix(), 16)).divide(BigDecimal(ETH_IN_WEI))
githubInteractor.addIssueComment(it.project, it.issue,
"new [transaction on " + statefulChain.chain.name + "](" + statefulChain.chain.tx_base_url.replace("TXHASH", tx.hash.prepend0xPrefix()) + ")" +
" with value " + value + "ETH",
it.installation)
}
}
}
}
}
| agpl-3.0 | 4611ab1d73681ec028588af60c724373 | 44.227273 | 206 | 0.601508 | 4.517594 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/nfd/src/templates/kotlin/nfd/templates/nativefiledialog.kt | 4 | 5281 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package nfd.templates
import org.lwjgl.generator.*
import nfd.*
val nativefiledialog = "NativeFileDialog".nativeClass(Module.NFD, prefix = "NFD_", prefixMethod = "NFD_") {
nativeImport("lwjgl_malloc.h")
nativeImport("include/nfd.h")
documentation =
"""
Bindings to ${url("https://github.com/mlabbe/nativefiledialog", "Native File Dialog")}, a tiny, neat C library that portably invokes native file open
and save dialogs. Write dialog code once and have it pop up native dialogs on all supported platforms.
<h3>Usage</h3>
${ul(
"<a href=\"https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/util/nfd/HelloNFD.java\\#L97\">Single file open dialog</a>",
"<a href=\"https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/util/nfd/HelloNFD.java\\#L119\">Multiple file open dialog</a>",
"<a href=\"https://github.com/LWJGL/lwjgl3/blob/master/modules/samples/src/test/java/org/lwjgl/demo/util/nfd/HelloNFD.java\\#L140\">Save dialog</a>"
)}
<h3>File Filter Syntax</h3>
There is a form of file filtering in every file dialog, but no consistent means of supporting it. NFD provides support for filtering files by groups of
extensions, providing its own descriptions (where applicable) for the extensions.
A wildcard filter is always added to every dialog.
Separators:
${ul(
"<i>;</i> Begin a new filter.",
"<i>,</i> Add a separate type to the filter."
)}
Examples:
${ul(
"<i>txt</i> The default filter is for text files. There is a wildcard option in a dropdown.",
"<i>png,jpg;psd</i> The default filter is for png and jpg files. A second filter is available for psd files. There is a wildcard option in a dropdown.",
"#NULL Wildcard only."
)}
<h3>Known Limitations</h3>
${ul(
"No support for Windows XP's legacy dialogs such as GetOpenFileName.",
"No support for file filter names -- ex: \"Image Files\" (*.png, *.jpg). Nameless filters are supported, though.",
"No support for selecting folders instead of files.",
"On Linux, GTK+ cannot be uninitialized to save memory. Launching a file dialog costs memory."
)}
"""
EnumConstant(
"Result values.",
"ERROR" enum "Programmatic error.",
"OKAY" enum "User pressed okay, or successful return.",
"CANCEL" enum "User pressed cancel."
)
val OpenDialog = nfdresult_t(
"OpenDialog",
"""
Launches a single file open dialog.
If #OKAY is returned, {@code outPath} will contain a pointer to a UTF-8 encoded string. The user must free the string with #Free() when it is no longer
needed.
""",
nullable..nfdchar_t.const.p("filterList", "an optional filter list"),
nullable..nfdchar_t.const.p("defaultPath", "an optional default path"),
Check(1)..nfdchar_t.p.p("outPath", "returns the selected file path")
)
nfdresult_t(
"OpenDialogMultiple",
"""
Launches a multiple file open dialog.
If #OKAY is returned, {@code outPaths} will be filled with information about the selected file or files. The user must free that information with
#PathSet_Free() when it is no longer needed.
""",
OpenDialog["filterList"],
OpenDialog["defaultPath"],
nfdpathset_t.p("outPaths", "a path set that will be filled with the selected files")
)
nfdresult_t(
"SaveDialog",
"""
Launches a save dialog.
If #OKAY is returned, {@code outPath} will contain a pointer to a UTF-8 encoded string. The user must free the string with #Free() when it is no longer
needed.
""",
OpenDialog["filterList"],
OpenDialog["defaultPath"],
OpenDialog["outPath"]
)
nfdresult_t(
"PickFolder",
"""
Launches a select folder dialog.
If #OKAY is returned, {@code outPath} will contain a pointer to a UTF-8 encoded string. The user must free the string with #Free() when it is no longer
needed.
""",
OpenDialog["defaultPath"],
OpenDialog["outPath"]
)
charASCII.const.p(
"GetError",
"Returns the last error.",
void()
)
size_t(
"PathSet_GetCount",
"Returns the number of entries stored in {@code pathSet}.",
nfdpathset_t.const.p("pathSet", "the path set to query")
)
nfdchar_t.p(
"PathSet_GetPath",
"Returns the UTF-8 path at offset {@code index}.",
nfdpathset_t.const.p("pathSet", "the path set to query"),
size_t("index", "the path offset")
)
void(
"PathSet_Free",
"Frees the contents of the specified path set.",
nfdpathset_t.p("pathSet", "the path set")
)
void(
"Free",
"Frees memory allocated by NativeFileDialog.",
Check(1)..void.p("outPath", "the string to free")
)
} | bsd-3-clause | 25989b2e7b05f34e3e686233523eb23e | 33.75 | 175 | 0.612005 | 3.991686 | false | false | false | false |
cmzy/okhttp | okhttp/src/main/kotlin/okhttp3/internal/http/RequestLine.kt | 4 | 1951 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.http
import java.net.HttpURLConnection
import java.net.Proxy
import okhttp3.HttpUrl
import okhttp3.Request
object RequestLine {
/**
* Returns the request status line, like "GET / HTTP/1.1". This is exposed to the application by
* [HttpURLConnection.getHeaderFields], so it needs to be set even if the transport is
* HTTP/2.
*/
fun get(request: Request, proxyType: Proxy.Type): String = buildString {
append(request.method)
append(' ')
if (includeAuthorityInRequestLine(request, proxyType)) {
append(request.url)
} else {
append(requestPath(request.url))
}
append(" HTTP/1.1")
}
/**
* Returns true if the request line should contain the full URL with host and port (like "GET
* http://android.com/foo HTTP/1.1") or only the path (like "GET /foo HTTP/1.1").
*/
private fun includeAuthorityInRequestLine(request: Request, proxyType: Proxy.Type): Boolean {
return !request.isHttps && proxyType == Proxy.Type.HTTP
}
/**
* Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, even if the request
* URL is. Includes the query component if it exists.
*/
fun requestPath(url: HttpUrl): String {
val path = url.encodedPath
val query = url.encodedQuery
return if (query != null) "$path?$query" else path
}
}
| apache-2.0 | 2fe2a118a8d137561dd4693ddbf356a4 | 32.637931 | 100 | 0.696566 | 3.871032 | false | false | false | false |
kdwink/intellij-community | platform/configuration-store-impl/src/StateMap.kt | 1 | 7304 | /*
* 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.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.ArrayUtil
import com.intellij.util.SystemProperties
import gnu.trove.THashMap
import org.iq80.snappy.SnappyInputStream
import org.iq80.snappy.SnappyOutputStream
import org.jdom.Element
import org.jdom.output.Format
import java.io.ByteArrayInputStream
import java.io.OutputStreamWriter
import java.util.*
import java.util.concurrent.atomic.AtomicReferenceArray
class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any?>) {
override fun toString(): String =
if (this == EMPTY) "EMPTY" else states.toString();
companion object {
private val XML_FORMAT = Format.getRawFormat().setTextMode(Format.TextMode.TRIM).setOmitEncoding(true).setOmitDeclaration(true)
val EMPTY = StateMap(emptyArray(), AtomicReferenceArray(0))
public fun fromMap(map: Map<String, Any>): StateMap {
if (map.isEmpty()) {
return EMPTY
}
val names = map.keys.toTypedArray()
if (map !is TreeMap) {
Arrays.sort(names)
}
val states = AtomicReferenceArray<Any?>(names.size)
for (i in names.indices) {
states.set(i, map.get(names[i]))
}
return StateMap(names, states)
}
public fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element {
if (state is Element) {
return state.clone()
}
else {
return newLiveStates?.get(key) ?: unarchiveState(state as ByteArray)
}
}
public fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? {
val newBytes = if (newState is Element) archiveState(newState) else newState as ByteArray
if (Arrays.equals(newBytes, oldState)) {
return null
}
else if (SystemProperties.getBooleanProperty("idea.log.changed.components", false)) {
fun stateToString(state: Any) = JDOMUtil.writeParent(state as? Element ?: unarchiveState(state as ByteArray), "\n")
val before = stateToString(oldState)
val after = stateToString(newState)
if (before == after) {
LOG.info("Serialization error: serialized are different, but unserialized are equal")
}
else {
LOG.info("$key ${StringUtil.repeat("=", 80 - key.length)}\nBefore:\n$before\nAfter:\n$after")
}
}
return newBytes
}
private fun archiveState(state: Element): ByteArray {
val byteOut = BufferExposingByteArrayOutputStream()
OutputStreamWriter(SnappyOutputStream(byteOut), CharsetToolkit.UTF8_CHARSET).use {
val xmlOutputter = JDOMUtil.MyXMLOutputter()
xmlOutputter.format = XML_FORMAT
xmlOutputter.output(state, it)
}
return ArrayUtil.realloc(byteOut.internalBuffer, byteOut.size())
}
private fun unarchiveState(state: ByteArray) = JDOMUtil.load(SnappyInputStream(ByteArrayInputStream(state)))
}
public fun toMutableMap(): MutableMap<String, Any> {
val map = THashMap<String, Any>(names.size)
for (i in names.indices) {
map.put(names[i], states.get(i))
}
return map
}
/**
* Sorted by name.
*/
fun keys() = names
public fun get(key: String): Any? {
val index = Arrays.binarySearch(names, key)
return if (index < 0) null else states.get(index)
}
fun getElement(key: String, newLiveStates: Map<String, Element>? = null) = stateToElement(key, get(key), newLiveStates)
fun isEmpty(): Boolean = names.isEmpty()
fun hasState(key: String) = get(key) is Element
public fun hasStates(): Boolean {
if (isEmpty()) {
return false
}
for (i in names.indices) {
if (states.get(i) is Element) {
return true
}
}
return false
}
public fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) {
val oldState = get(key)
val newState = newStates.get(key)
if (oldState is Element) {
if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) {
diffs.add(key)
}
}
else if (getNewByteIfDiffers(key, newState!!, oldState as ByteArray) != null) {
diffs.add(key)
}
}
fun getState(key: String, archive: Boolean = false): Element? {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return null
}
val state = states.get(index) as? Element ?: return null
if (!archive) {
return state
}
return if (states.compareAndSet(index, state, archiveState(state))) state else getState(key, true)
}
public fun archive(key: String, state: Element?) {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return
}
val currentState = states.get(index)
LOG.assertTrue(currentState is Element)
states.set(index, if (state == null) null else archiveState(state))
}
}
fun setStateAndCloneIfNeed(key: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>? = null): MutableMap<String, Any>? {
val oldState = oldStates.get(key)
if (newState == null || JDOMUtil.isEmpty(newState)) {
if (oldState == null) {
return null
}
val newStates = oldStates.toMutableMap()
newStates.remove(key)
return newStates
}
newLiveStates?.put(key, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(key, newState, oldState as ByteArray)
if (newBytes == null) {
return null
}
}
val newStates = oldStates.toMutableMap()
newStates.put(key, newBytes ?: newState)
return newStates
}
// true if updated (not equals to previous state)
internal fun updateState(states: MutableMap<String, Any>, key: String, newState: Element?, newLiveStates: MutableMap<String, Element>? = null): Boolean {
if (newState == null || JDOMUtil.isEmpty(newState)) {
states.remove(key)
return true
}
newLiveStates?.put(key, newState)
val oldState = states.get(key)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return false
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return false
}
states.put(key, newBytes ?: newState)
return true
} | apache-2.0 | 16f1586e5d796ff0f30a0791016e0829 | 30.487069 | 160 | 0.681407 | 4.066815 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/checklist/view/controller/ChecklistCustomController.kt | 1 | 4850 | package org.secfirst.umbrella.feature.checklist.view.controller
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.checklist_custom_view.*
import kotlinx.android.synthetic.main.checklist_custom_view.view.*
import org.secfirst.umbrella.R
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.component.SwipeToDeleteCallback
import org.secfirst.umbrella.feature.base.view.BaseController
import org.secfirst.umbrella.feature.checklist.DaggerChecklistComponent
import org.secfirst.umbrella.feature.checklist.interactor.ChecklistBaseInteractor
import org.secfirst.umbrella.feature.checklist.presenter.ChecklistBasePresenter
import org.secfirst.umbrella.feature.checklist.view.ChecklistView
import org.secfirst.umbrella.feature.checklist.view.adapter.ChecklistCustomAdapter
import org.secfirst.umbrella.misc.initRecyclerView
import javax.inject.Inject
class ChecklistCustomController(bundle: Bundle) : BaseController(bundle), ChecklistView {
@Inject
internal lateinit var presenter: ChecklistBasePresenter<ChecklistView, ChecklistBaseInteractor>
private val checklistId by lazy { args.getString(EXTRA_ID_CUSTOM_CHECKLIST) }
private val checklistName by lazy { args.getString(EXTRA_CUSTOM_CHECKLIST_NAME) }
private lateinit var adapter: ChecklistCustomAdapter
constructor(checklistId: String, checklistName: String) : this(Bundle().apply {
putString(EXTRA_ID_CUSTOM_CHECKLIST, checklistId)
putString(EXTRA_CUSTOM_CHECKLIST_NAME, checklistName)
})
override fun onInject() {
DaggerChecklistComponent.builder()
.application(UmbrellaApplication.instance)
.build()
.inject(this)
}
override fun onAttach(view: View) {
setUpToolbar()
enableNavigation(false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
val view = inflater.inflate(R.layout.checklist_custom_view, container, false)
presenter.onAttach(this)
adapter = ChecklistCustomAdapter()
view.checklistCustomRecyclerView.initRecyclerView(adapter)
view.addChecklistItem.setOnClickListener { validateChecklistItemIsEmpty() }
enterAction(view)
initDeleteChecklistItem(view)
return view
}
private fun enterAction(view: View) {
view.checklistContent?.setOnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
validateChecklistItemIsEmpty()
return@setOnKeyListener true
}
false
}
}
private fun addChecklistItem() {
val checklistItem = checklistContent.text.toString()
checklistContent?.text?.clear()
adapter.add(checklistItem)
}
private fun submitChecklist() {
if (adapter.getChecklistItems().isNotEmpty())
presenter.submitInsertCustomChecklist(checklistName,
checklistId, adapter.getChecklistItems())
}
private fun initDeleteChecklistItem(view: View) {
val swipeHandler = object : SwipeToDeleteCallback(context) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
adapter.removeAt(position)
}
}
val itemTouchHelper = ItemTouchHelper(swipeHandler)
itemTouchHelper.attachToRecyclerView(view.checklistCustomRecyclerView)
}
private fun setUpToolbar() {
customChecklistToolbar?.let {
mainActivity.setSupportActionBar(it)
mainActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
mainActivity.supportActionBar?.title = checklistName
}
}
private fun validateChecklistItemIsEmpty(): Boolean {
return if (checklistContent?.text.toString().isNotBlank()) {
addChecklistItem()
true
} else {
checklistContent?.error = context.getString(R.string.checklist_custom_empty_item_error_message)
false
}
}
override fun onDestroyView(view: View) {
enableNavigation(true)
}
override fun handleBack(): Boolean {
submitChecklist()
router.popCurrentController()
return true
}
companion object {
private const val EXTRA_ID_CUSTOM_CHECKLIST = "id_custom_check_list"
private const val EXTRA_CUSTOM_CHECKLIST_NAME = "name_custom_check_list"
private const val INITIAL_INDEX = 0
}
} | gpl-3.0 | 37e0b373da9d93b05fd2d1d62d648481 | 37.19685 | 110 | 0.710103 | 4.964176 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/opus/src/templates/kotlin/opus/templates/OpusEnc.kt | 4 | 13138 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opus.templates
import opus.*
import org.lwjgl.generator.*
val OpusEnc = "OpusEnc".nativeClass(Module.OPUS, prefix = "OPE", prefixMethod = "ope_", binding = OPUS_BINDING_DELEGATE) {
javaImport("static org.lwjgl.util.opus.Opus.*")
documentation =
"""
This is the documentation for the ${url("https://github.com/xiph/libopusenc", "libopusenc")} C API.
The {@code libopusenc} package provides a convenient high-level API for encoding Ogg Opus files.
<h3>Organization</h3>
The main API is divided into several sections:
${ul(
"encoding",
"comments",
"encoder_ctl",
"callbacks",
"error_codes"
)}
<h4>Error Codes</h4>
Many of the functions in this library return a negative error code when a function fails.
"""
IntConstant(
"API version for this header. Can be used to check for features at compile time.",
"API_VERSION".."0"
)
IntConstant(
"Error codes.",
"OK".."0",
"BAD_ARG".."-11",
"INTERNAL_ERROR".."-13",
"UNIMPLEMENTED".."-15",
"ALLOC_FAIL".."-17",
"CANNOT_OPEN".."-30",
"TOO_LATE".."-31",
"INVALID_PICTURE".."-32",
"INVALID_ICON".."-33",
"WRITE_FAIL".."-34",
"CLOSE_FAIL".."-35"
)
EnumConstant(
"\"Raw\" request values -- they should usually not be used.",
"SET_DECISION_DELAY_REQUEST".enum("", "14000"),
"GET_DECISION_DELAY_REQUEST".enum,
"SET_MUXING_DELAY_REQUEST".enum,
"GET_MUXING_DELAY_REQUEST".enum,
"SET_COMMENT_PADDING_REQUEST".enum,
"GET_COMMENT_PADDING_REQUEST".enum,
"SET_SERIALNO_REQUEST".enum,
"GET_SERIALNO_REQUEST".enum,
"SET_PACKET_CALLBACK_REQUEST".enum,
"SET_HEADER_GAIN_REQUEST".enum("", "14010"),
"GET_HEADER_GAIN_REQUEST".enum,
"GET_NB_STREAMS_REQUEST".enum("", "14013"),
"GET_NB_COUPLED_STREAMS_REQUEST".enum("", "14015")
)
OggOpusComments.p(
"comments_create",
"Create a new comments object.",
void(),
returnDoc = "newly-created comments object"
)
OggOpusComments.p(
"comments_copy",
"Create a deep copy of a comments object.",
OggOpusComments.p("comments", "comments object to copy"),
returnDoc = "deep copy of input"
)
void(
"comments_destroy",
"Destroys a comments object.",
OggOpusComments.p("comments", "comments object to destroy")
)
int(
"comments_add",
"Add a comment.",
OggOpusComments.p("comments", "where to add the comments"),
charUTF8.const.p("tag", "tag for the comment (must not contain {@code =} char)"),
charUTF8.const.p("val", "value for the tag"),
returnDoc = "error code"
)
int(
"comments_add_string",
"Add a comment as a single tag=value string.",
OggOpusComments.p("comments", "where to add the comments"),
charUTF8.const.p("tag_and_val", "string of the form {@code tag=value} (must contain {@code =} char)"),
returnDoc = "error code"
)
int(
"comments_add_picture",
"Add a picture from a file.",
OggOpusComments.p("comments", "where to add the comments"),
charUTF8.const.p("filename", "file name for the picture"),
int("picture_type", "type of picture ({@code -1} for default)"),
nullable..charUTF8.const.p("description", "description (#NULL means no comment)"),
returnDoc = "error code"
)
int(
"comments_add_picture_from_memory",
"Add a picture already in memory.",
OggOpusComments.p("comments", "where to add the comments"),
char.const.p("ptr", "pointer to picture in memory"),
AutoSize("ptr")..size_t("size", "size of picture pointed to by {@code ptr}"),
int("picture_type", "type of picture ({@code -1} for default)"),
nullable..charUTF8.const.p("description", "description (#NULL means no comment)"),
returnDoc = "error code"
)
OggOpusEnc.p(
"encoder_create_file",
"Create a new OggOpus file.",
charUTF8.const.p("path", "path where to create the file"),
OggOpusComments.p("comments", "comments associated with the stream"),
opus_int32("rate", "input sampling rate (48 kHz is faster)"),
int("channels", "number of channels"),
int("family", "mapping family (0 for mono/stereo, 1 for surround)"),
Check(1)..nullable..int.p("error", "error code (#NULL if no error is to be returned)"),
returnDoc = "newly-created encoder"
)
OggOpusEnc.p(
"encoder_create_callbacks",
"Create a new OggOpus stream to be handled using callbacks",
OpusEncCallbacks.const.p("callbacks", "callback functions"),
opaque_p("user_data", "pointer to be associated with the stream and passed to the callbacks"),
OggOpusComments.p("comments", "comments associated with the stream"),
opus_int32("rate", "input sampling rate (48 kHz is faster)"),
int("channels", "number of channels"),
int("family", "mapping family ({@code 0} for mono/stereo, {@code 1} for surround)"),
Check(1)..nullable..int.p("error", "error code (#NULL if no error is to be returned)"),
returnDoc = "newly-created encoder"
)
OggOpusEnc.p(
"encoder_create_pull",
"Create a new OggOpus stream to be used along with #encoder_get_page(). This is mostly useful for muxing with other streams.",
OggOpusComments.p("comments", "comments associated with the stream"),
opus_int32("rate", "input sampling rate (48 kHz is faster)"),
int("channels", "number of channels"),
int("family", "mapping family (0 for mono/stereo, 1 for surround)"),
Check(1)..nullable..int.p("error", "error code (#NULL if no error is to be returned)"),
returnDoc = "newly-created encoder"
)
int(
"encoder_deferred_init_with_mapping",
"""
Deferred initialization of the encoder to force an explicit channel mapping. This can be used to override the default channel coupling, but using it
for regular surround will almost certainly lead to worse quality.
""",
OggOpusEnc.p("enc", "encoder"),
int("family", "mapping family ({@code 0} for mono/stereo, {@code 1} for surround)"),
int("streams", "total number of streams"),
int("coupled_streams", "number of coupled streams"),
Unsafe..unsigned_char.const.p("mapping", "channel mapping"),
returnDoc = "error code"
)
int(
"encoder_write_float",
"Add/encode any number of float samples to the stream.",
OggOpusEnc.p("enc", "encoder"),
Unsafe..float.const.p("pcm", "floating-point PCM values in the {@code +/-1} range (interleaved if multiple channels)"),
int("samples_per_channel", "number of samples for each channel"),
returnDoc = "error code"
)
int(
"encoder_write",
"Add/encode any number of 16-bit linear samples to the stream.",
OggOpusEnc.p("enc", "encoder"),
Unsafe..opus_int16.const.p("pcm", "linear 16-bit PCM values in the {@code [-32768,32767]} range (interleaved if multiple channels)"),
int("samples_per_channel", "number of samples for each channel"),
returnDoc = "error code"
)
intb(
"encoder_get_page",
"Get the next page from the stream (only if using #encoder_create_pull()).",
OggOpusEnc.p("enc", "encoder"),
Check(1)..unsigned_char.p.p("page", "next available encoded page"),
Check(1)..opus_int32.p("len", "size (in bytes) of the page returned"),
intb("flush", "if non-zero, forces a flush of the page (if any data available)"),
returnDoc = "1 if there is a page available, 0 if not"
)
int(
"encoder_drain",
"Finalizes the stream, but does not deallocate the object.",
OggOpusEnc.p("enc", "encoder"),
returnDoc = "error code"
)
void(
"encoder_destroy",
"Deallocates the obect. Make sure to #encoder_drain() first.",
OggOpusEnc.p("enc", "encoder")
)
int(
"encoder_chain_current",
"Ends the stream and create a new stream within the same file.",
OggOpusEnc.p("enc", "encoder"),
OggOpusComments.p("comments", "comments associated with the stream"),
returnDoc = "error code"
)
int(
"encoder_continue_new_file",
"Ends the stream and create a new file.",
OggOpusEnc.p("enc", "encoder"),
charUTF8.const.p("path", "path where to write the new file"),
OggOpusComments.p("comments", "comments associated with the stream"),
returnDoc = "error code"
)
int(
"encoder_continue_new_callbacks",
"Ends the stream and create a new file (callback-based).",
OggOpusEnc.p("enc", "encoder"),
opaque_p("user_data", "pointer to be associated with the new stream and passed to the callbacks"),
OggOpusComments.p("comments", "comments associated with the stream"),
returnDoc = "error code"
)
int(
"encoder_flush_header",
"Write out the header now rather than wait for audio to begin.",
OggOpusEnc.p("enc", "encoder"),
returnDoc = "error code"
)
private..int(
"encoder_ctl",
"Sets encoder options.",
OggOpusEnc.p("enc", "encoder"),
returnDoc = "error code"
)
charUTF8.const.p(
"strerror",
"Converts a libopusenc error code into a human readable string.",
int("error", "error number"),
returnDoc = "error string"
)
charUTF8.const.p(
"get_version_string",
"Returns a string representing the version of libopusenc being used at run time.",
void(),
returnDoc = "a string describing the version of this library"
)
int(
"get_abi_version",
"ABI version for this header. Can be used to check for features at run time.",
void(),
returnDoc = "an integer representing the ABI version"
)
customMethod("""
/**
* Sets encoder options.
*
* @param enc encoder
* @param request use a request macro
*
* @return error code
*/
public static int ope_encoder_ctl(@NativeType("OggOpusEnc *") long enc, int request) {
return new CTLRequestV(request).apply(enc, Functions.encoder_ctl);
}
/**
* Sets encoder options.
*
* @param enc encoder
* @param request use a request macro
*
* @return error code
*/
public static int ope_encoder_ctl(@NativeType("OggOpusEnc *") long enc, CTLRequest request) {
return request.apply(enc, Functions.encoder_ctl);
}
public static CTLRequest OPE_SET_DECISION_DELAY_REQUEST(int value) { return new CTLRequestI(OPE_SET_DECISION_DELAY_REQUEST, value); }
public static CTLRequest OPE_GET_DECISION_DELAY_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_DECISION_DELAY_REQUEST, memAddress(__result)); }
public static CTLRequest OPE_SET_MUXING_DELAY_REQUEST(int value) { return new CTLRequestI(OPE_SET_MUXING_DELAY_REQUEST, value); }
public static CTLRequest OPE_GET_MUXING_DELAY_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_MUXING_DELAY_REQUEST, memAddress(__result)); }
public static CTLRequest OPE_SET_COMMENT_PADDING_REQUEST(int value) { return new CTLRequestI(OPE_SET_COMMENT_PADDING_REQUEST, value); }
public static CTLRequest OPE_GET_COMMENT_PADDING_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_COMMENT_PADDING_REQUEST, memAddress(__result)); }
public static CTLRequest OPE_SET_SERIALNO_REQUEST(int value) { return new CTLRequestI(OPE_SET_SERIALNO_REQUEST, value); }
public static CTLRequest OPE_GET_SERIALNO_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_SERIALNO_REQUEST, memAddress(__result)); }
public static CTLRequest OPE_SET_PACKET_CALLBACK_REQUEST(OPEPacketFuncI value) { return new CTLRequestP(OPE_SET_PACKET_CALLBACK_REQUEST, value.address()); }
public static CTLRequest OPE_SET_HEADER_GAIN_REQUEST(int value) { return new CTLRequestI(OPE_SET_HEADER_GAIN_REQUEST, value); }
public static CTLRequest OPE_GET_HEADER_GAIN_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_HEADER_GAIN_REQUEST, memAddress(__result)); }
public static CTLRequest OPE_GET_NB_STREAMS_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_NB_STREAMS_REQUEST, memAddress(__result)); }
public static CTLRequest OPE_GET_NB_COUPLED_STREAMS_REQUEST(IntBuffer __result) { return new CTLRequestP(OPE_GET_NB_COUPLED_STREAMS_REQUEST, memAddress(__result)); }
""")
}
| bsd-3-clause | a8d94cf99df95a1fdc35ab9e1f0a489f | 34.034667 | 169 | 0.617369 | 3.890435 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PageView.kt | 1 | 8179 | package eu.kanade.tachiyomi.ui.reader.viewer.pager
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.ui.reader.viewer.base.PageDecodeErrorLayout
import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.RightToLeftReader
import eu.kanade.tachiyomi.ui.reader.viewer.pager.vertical.VerticalReader
import eu.kanade.tachiyomi.util.inflate
import kotlinx.android.synthetic.main.chapter_image.view.*
import kotlinx.android.synthetic.main.item_pager_reader.view.*
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.subjects.PublishSubject
import rx.subjects.SerializedSubject
import java.io.File
import java.util.concurrent.TimeUnit
class PageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null)
: FrameLayout(context, attrs) {
/**
* Page of a chapter.
*/
lateinit var page: Page
/**
* Subscription for status changes of the page.
*/
private var statusSubscription: Subscription? = null
/**
* Subscription for progress changes of the page.
*/
private var progressSubscription: Subscription? = null
/**
* Layout of decode error.
*/
private var decodeErrorLayout: View? = null
fun initialize(reader: PagerReader, page: Page) {
val activity = reader.activity as ReaderActivity
when (activity.readerTheme) {
ReaderActivity.BLACK_THEME -> progress_text.setTextColor(reader.whiteColor)
ReaderActivity.WHITE_THEME -> progress_text.setTextColor(reader.blackColor)
}
if (reader is RightToLeftReader) {
rotation = -180f
}
with(image_view) {
setMaxBitmapDimensions((reader.activity as ReaderActivity).maxBitmapSize)
setDoubleTapZoomStyle(SubsamplingScaleImageView.ZOOM_FOCUS_FIXED)
setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_INSIDE)
setMinimumScaleType(reader.scaleType)
setMinimumDpi(90)
setMinimumTileDpi(180)
setRegionDecoderClass(reader.regionDecoderClass)
setBitmapDecoderClass(reader.bitmapDecoderClass)
setVerticalScrollingParent(reader is VerticalReader)
setOnTouchListener { v, motionEvent -> reader.gestureDetector.onTouchEvent(motionEvent) }
setOnImageEventListener(object : SubsamplingScaleImageView.DefaultOnImageEventListener() {
override fun onReady() {
onImageDecoded(reader)
}
override fun onImageLoadError(e: Exception) {
onImageDecodeError(reader)
}
})
}
retry_button.setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_UP) {
activity.presenter.retryPage(page)
}
true
}
this.page = page
observeStatus()
}
override fun onDetachedFromWindow() {
unsubscribeProgress()
unsubscribeStatus()
image_view.setOnTouchListener(null)
image_view.setOnImageEventListener(null)
super.onDetachedFromWindow()
}
/**
* Observes the status of the page and notify the changes.
*
* @see processStatus
*/
private fun observeStatus() {
statusSubscription?.unsubscribe()
val statusSubject = SerializedSubject(PublishSubject.create<Int>())
page.setStatusSubject(statusSubject)
statusSubscription = statusSubject.startWith(page.status)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { processStatus(it) }
}
/**
* Observes the progress of the page and updates view.
*/
private fun observeProgress() {
progressSubscription?.unsubscribe()
progressSubscription = Observable.interval(100, TimeUnit.MILLISECONDS)
.map { page.progress }
.distinctUntilChanged()
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { progress ->
progress_text.text = context.getString(R.string.download_progress, progress)
}
}
/**
* Called when the status of the page changes.
*
* @param status the new status of the page.
*/
private fun processStatus(status: Int) {
when (status) {
Page.QUEUE -> setQueued()
Page.LOAD_PAGE -> setLoading()
Page.DOWNLOAD_IMAGE -> {
observeProgress()
setDownloading()
}
Page.READY -> {
setImage()
unsubscribeProgress()
}
Page.ERROR -> {
setError()
unsubscribeProgress()
}
}
}
/**
* Unsubscribes from the status subscription.
*/
private fun unsubscribeStatus() {
page.setStatusSubject(null)
statusSubscription?.unsubscribe()
statusSubscription = null
}
/**
* Unsubscribes from the progress subscription.
*/
private fun unsubscribeProgress() {
progressSubscription?.unsubscribe()
progressSubscription = null
}
/**
* Called when the page is queued.
*/
private fun setQueued() {
progress_container.visibility = View.VISIBLE
progress_text.visibility = View.INVISIBLE
retry_button.visibility = View.GONE
decodeErrorLayout?.let {
removeView(it)
decodeErrorLayout = null
}
}
/**
* Called when the page is loading.
*/
private fun setLoading() {
progress_container.visibility = View.VISIBLE
progress_text.visibility = View.VISIBLE
progress_text.setText(R.string.downloading)
}
/**
* Called when the page is downloading.
*/
private fun setDownloading() {
progress_container.visibility = View.VISIBLE
progress_text.visibility = View.VISIBLE
}
/**
* Called when the page is ready.
*/
private fun setImage() {
val path = page.imagePath
if (path != null && File(path).exists()) {
progress_text.visibility = View.INVISIBLE
image_view.setImage(ImageSource.uri(path))
} else {
page.status = Page.ERROR
}
}
/**
* Called when the page has an error.
*/
private fun setError() {
progress_container.visibility = View.GONE
retry_button.visibility = View.VISIBLE
}
/**
* Called when the image is decoded and going to be displayed.
*/
private fun onImageDecoded(reader: PagerReader) {
progress_container.visibility = View.GONE
with(image_view) {
when (reader.zoomType) {
PagerReader.ALIGN_LEFT -> setScaleAndCenter(scale, PointF(0f, 0f))
PagerReader.ALIGN_RIGHT -> setScaleAndCenter(scale, PointF(sWidth.toFloat(), 0f))
PagerReader.ALIGN_CENTER -> setScaleAndCenter(scale, center.apply { y = 0f })
}
}
}
/**
* Called when an image fails to decode.
*/
private fun onImageDecodeError(reader: PagerReader) {
progress_container.visibility = View.GONE
if (decodeErrorLayout != null || !reader.isAdded) return
val activity = reader.activity as ReaderActivity
val layout = inflate(R.layout.page_decode_error)
PageDecodeErrorLayout(layout, page, activity.readerTheme, {
if (reader.isAdded) {
activity.presenter.retryPage(page)
}
})
decodeErrorLayout = layout
addView(layout)
}
} | apache-2.0 | 2d01140138bbc314a5597e6d41e89f49 | 30.102662 | 102 | 0.627216 | 4.891746 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/data/politics/PoliticalLandscapeController.kt | 1 | 6895 | package top.zbeboy.isy.web.data.politics
import org.springframework.stereotype.Controller
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import top.zbeboy.isy.domain.tables.pojos.PoliticalLandscape
import top.zbeboy.isy.service.data.PoliticalLandscapeService
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import top.zbeboy.isy.web.vo.data.politics.PoliticsVo
import java.util.ArrayList
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
/**
* Created by zbeboy 2017-12-12 .
**/
@Controller
open class PoliticalLandscapeController {
@Resource
open lateinit var politicalLandscapeService: PoliticalLandscapeService
/**
* 获取全部政治面貌
*
* @return 全部政治面貌
*/
@RequestMapping(value = ["/user/political_landscapes"], method = [(RequestMethod.GET)])
@ResponseBody
fun politicalLandscapes(): AjaxUtils<PoliticalLandscape> {
val ajaxUtils = AjaxUtils.of<PoliticalLandscape>()
val politicalLandscapes = ArrayList<PoliticalLandscape>()
val politicalLandscape = PoliticalLandscape(0, "请选择政治面貌")
politicalLandscapes.add(politicalLandscape)
politicalLandscapes.addAll(politicalLandscapeService.findAll())
return ajaxUtils.success().msg("获取政治面貌数据成功!").listData(politicalLandscapes)
}
/**
* 政治面貌数据
*
* @return 政治面貌数据页面
*/
@RequestMapping(value = ["/web/menu/data/politics"], method = [(RequestMethod.GET)])
fun politicsData(): String {
return "web/data/politics/politics_data::#page-wrapper"
}
/**
* datatables ajax查询数据
*
* @param request 请求
* @return datatables数据
*/
@RequestMapping(value = ["/web/data/politics/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun politicsDatas(request: HttpServletRequest): DataTablesUtils<PoliticalLandscape> {
// 前台数据标题 注:要和前台标题顺序一致,获取order用
val headers = ArrayList<String>()
headers.add("political_landscape_id")
headers.add("political_landscape_name")
headers.add("operator")
val dataTablesUtils = DataTablesUtils<PoliticalLandscape>(request, headers)
val records = politicalLandscapeService.findAllByPage(dataTablesUtils)
var politics: List<PoliticalLandscape> = ArrayList()
if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) {
politics = records.into(PoliticalLandscape::class.java)
}
dataTablesUtils.data = politics
dataTablesUtils.setiTotalRecords(politicalLandscapeService.countAll().toLong())
dataTablesUtils.setiTotalDisplayRecords(politicalLandscapeService.countByCondition(dataTablesUtils).toLong())
return dataTablesUtils
}
/**
* 保存时检验政治面貌是否重复
*
* @param name 政治面貌
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/politics/save/valid"], method = [(RequestMethod.POST)])
@ResponseBody
fun saveValid(@RequestParam("politicalLandscapeName") name: String): AjaxUtils<*> {
val politicalLandscapeName = StringUtils.trimWhitespace(name)
if (StringUtils.hasLength(politicalLandscapeName)) {
val nations = politicalLandscapeService.findByPoliticalLandscapeName(politicalLandscapeName)
return if (ObjectUtils.isEmpty(nations)) {
AjaxUtils.of<Any>().success().msg("政治面貌不存在")
} else {
AjaxUtils.of<Any>().fail().msg("政治面貌已存在")
}
}
return AjaxUtils.of<Any>().fail().msg("政治面貌不能为空")
}
/**
* 保存政治面貌信息
*
* @param politicsVo 政治面貌
* @param bindingResult 检验
* @return true 保存成功 false 保存失败
*/
@RequestMapping(value = ["/web/data/politics/save"], method = [(RequestMethod.POST)])
@ResponseBody
fun politicsSave(@Valid politicsVo: PoliticsVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors()) {
val politicalLandscape = PoliticalLandscape()
politicalLandscape.politicalLandscapeName = StringUtils.trimWhitespace(politicsVo.politicalLandscapeName!!)
politicalLandscapeService.save(politicalLandscape)
return AjaxUtils.of<Any>().success().msg("保存成功")
}
return AjaxUtils.of<Any>().fail().msg("填写信息错误,请检查")
}
/**
* 检验编辑时政治面貌重复
*
* @param id 政治面貌id
* @param name 政治面貌
* @return true 合格 false 不合格
*/
@RequestMapping(value = ["/web/data/politics/update/valid"], method = [(RequestMethod.POST)])
@ResponseBody
fun updateValid(@RequestParam("politicalLandscapeId") id: Int, @RequestParam("politicalLandscapeName") name: String): AjaxUtils<*> {
val politicalLandscapeName = StringUtils.trimWhitespace(name)
val politicalLandscapeRecords = politicalLandscapeService.findByNationNameNePoliticalLandscapeId(politicalLandscapeName, id)
return if (politicalLandscapeRecords.isEmpty()) {
AjaxUtils.of<Any>().success().msg("政治面貌不重复")
} else AjaxUtils.of<Any>().fail().msg("政治面貌重复")
}
/**
* 保存更改
*
* @param politicsVo 政治面貌
* @param bindingResult 检验
* @return true 更改成功 false 更改失败
*/
@RequestMapping(value = ["/web/data/politics/update"], method = [(RequestMethod.POST)])
@ResponseBody
fun politicsUpdate(@Valid politicsVo: PoliticsVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors() && !ObjectUtils.isEmpty(politicsVo.politicalLandscapeId)) {
val politicalLandscape = politicalLandscapeService.findById(politicsVo.politicalLandscapeId!!)
if (!ObjectUtils.isEmpty(politicalLandscape)) {
politicalLandscape.politicalLandscapeName = StringUtils.trimWhitespace(politicsVo.politicalLandscapeName!!)
politicalLandscapeService.update(politicalLandscape)
return AjaxUtils.of<Any>().success().msg("更改成功")
}
}
return AjaxUtils.of<Any>().fail().msg("更改失败")
}
} | mit | eb8ff630bd5cf109ee5abf54ccfdded8 | 39.3625 | 136 | 0.685767 | 3.956495 | false | false | false | false |
paplorinc/intellij-community | java/java-indexing-impl/src/com/intellij/psi/impl/JavaSimplePropertyIndex.kt | 2 | 8991 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.LighterASTNode
import com.intellij.lang.java.JavaParserDefinition
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiField
import com.intellij.psi.impl.cache.RecordUtil
import com.intellij.psi.impl.source.JavaLightStubBuilder
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.JavaElementType
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stub.JavaStubImplUtil
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PropertyUtil
import com.intellij.psi.util.PropertyUtilBase
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.indexing.*
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.EnumeratorIntegerDescriptor
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import java.io.DataInput
import java.io.DataOutput
private val indexId = ID.create<Int, PropertyIndexValue>("java.simple.property")
private val log = Logger.getInstance(JavaSimplePropertyIndex::class.java)
fun getFieldOfGetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, true)
fun getFieldOfSetter(method: PsiMethodImpl): PsiField? = resolveFieldFromIndexValue(method, false)
private fun resolveFieldFromIndexValue(method: PsiMethodImpl, isGetter: Boolean): PsiField? {
val id = JavaStubImplUtil.getMethodStubIndex(method)
if (id != -1) {
val values = FileBasedIndex.getInstance().getValues(indexId, id, GlobalSearchScope.fileScope(method.containingFile))
when (values.size) {
0 -> return null
1 -> {
val indexValue = values[0]
if (isGetter != indexValue.getter) return null
val psiClass = method.containingClass
val project = psiClass!!.project
val expr = JavaPsiFacade.getElementFactory(project).createExpressionFromText(indexValue.propertyRefText, psiClass)
return PropertyUtil.getSimplyReturnedField(expr)
}
else -> {
log.error("multiple index values for method $method")
}
}
}
return null
}
data class PropertyIndexValue(val propertyRefText: String, val getter: Boolean)
class JavaSimplePropertyIndex : FileBasedIndexExtension<Int, PropertyIndexValue>(), PsiDependentIndex {
private val allowedExpressions by lazy {
TokenSet.create(ElementType.REFERENCE_EXPRESSION, ElementType.THIS_EXPRESSION, ElementType.SUPER_EXPRESSION)
}
override fun getIndexer(): DataIndexer<Int, PropertyIndexValue, FileContent> = DataIndexer { inputData ->
val result = ContainerUtil.newHashMap<Int, PropertyIndexValue>()
val tree = (inputData as FileContentImpl).lighterASTForPsiDependentIndex
object : RecursiveLighterASTNodeWalkingVisitor(tree) {
var methodIndex = 0
override fun visitNode(element: LighterASTNode) {
if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return
if (element.tokenType === JavaElementType.METHOD) {
extractProperty(element)?.let { result.put(methodIndex, it) }
methodIndex++
}
super.visitNode(element)
}
private fun extractProperty(method: LighterASTNode): PropertyIndexValue? {
var isConstructor = true
var isGetter = true
var isBooleanReturnType = false
var isVoidReturnType = false
var setterParameterName: String? = null
var refText: String? = null
for (child in tree.getChildren(method)) {
when (child.tokenType) {
JavaElementType.TYPE -> {
val children = tree.getChildren(child)
if (children.size != 1) return null
val typeElement = children[0]
if (typeElement.tokenType == JavaTokenType.VOID_KEYWORD) isVoidReturnType = true
if (typeElement.tokenType == JavaTokenType.BOOLEAN_KEYWORD) isBooleanReturnType = true
isConstructor = false
}
JavaElementType.PARAMETER_LIST -> {
if (isGetter) {
if (LightTreeUtil.firstChildOfType(tree, child, JavaElementType.PARAMETER) != null) return null
} else {
val parameters = LightTreeUtil.getChildrenOfType(tree, child, JavaElementType.PARAMETER)
if (parameters.size != 1) return null
setterParameterName = JavaLightTreeUtil.getNameIdentifierText(tree, parameters[0])
if (setterParameterName == null) return null
}
}
JavaElementType.CODE_BLOCK -> {
refText = if (isGetter) getGetterPropertyRefText(child) else getSetterPropertyRefText(child, setterParameterName!!)
if (refText == null) return null
}
JavaTokenType.IDENTIFIER -> {
if (isConstructor) return null
val name = RecordUtil.intern(tree.charTable, child)
val flavour = PropertyUtil.getMethodNameGetterFlavour(name)
when (flavour) {
PropertyUtilBase.GetterFlavour.NOT_A_GETTER -> {
if (PropertyUtil.isSetterName(name)) {
isGetter = false
}
else {
return null
}
}
PropertyUtilBase.GetterFlavour.BOOLEAN -> if (!isBooleanReturnType) return null
else -> { }
}
if (isVoidReturnType && isGetter) return null
}
}
}
return refText?.let { PropertyIndexValue(it, isGetter) }
}
private fun getSetterPropertyRefText(codeBlock: LighterASTNode, setterParameterName: String): String? {
val assignment = tree
.getChildren(codeBlock)
.singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) }
?.takeIf { it.tokenType == JavaElementType.EXPRESSION_STATEMENT }
?.let { LightTreeUtil.firstChildOfType(tree, it, JavaElementType.ASSIGNMENT_EXPRESSION) }
if (assignment == null || LightTreeUtil.firstChildOfType(tree, assignment, JavaTokenType.EQ) == null) return null
val operands = LightTreeUtil.getChildrenOfType(tree, assignment, ElementType.EXPRESSION_BIT_SET)
if (operands.size != 2 || LightTreeUtil.toFilteredString(tree, operands[1], null) != setterParameterName) return null
val lhsText = LightTreeUtil.toFilteredString(tree, operands[0], null)
if (lhsText == setterParameterName) return null
return lhsText
}
private fun getGetterPropertyRefText(codeBlock: LighterASTNode): String? {
return tree
.getChildren(codeBlock)
.singleOrNull { ElementType.JAVA_STATEMENT_BIT_SET.contains(it.tokenType) }
?.takeIf { it.tokenType == JavaElementType.RETURN_STATEMENT}
?.let { LightTreeUtil.firstChildOfType(tree, it, allowedExpressions) }
?.takeIf(this::checkQualifiers)
?.let { LightTreeUtil.toFilteredString(tree, it, null) }
}
private fun checkQualifiers(expression: LighterASTNode): Boolean {
if (!allowedExpressions.contains(expression.tokenType)) {
return false
}
val qualifier = JavaLightTreeUtil.findExpressionChild(tree, expression)
return qualifier == null || checkQualifiers(qualifier)
}
}.visitNode(tree.root)
result
}
override fun getKeyDescriptor(): KeyDescriptor<Int> = EnumeratorIntegerDescriptor.INSTANCE
override fun getValueExternalizer(): DataExternalizer<PropertyIndexValue> = object: DataExternalizer<PropertyIndexValue> {
override fun save(out: DataOutput, value: PropertyIndexValue?) {
value!!
EnumeratorStringDescriptor.INSTANCE.save(out, value.propertyRefText)
out.writeBoolean(value.getter)
}
override fun read(input: DataInput): PropertyIndexValue = PropertyIndexValue(EnumeratorStringDescriptor.INSTANCE.read(input), input.readBoolean())
}
override fun getName(): ID<Int, PropertyIndexValue> = indexId
override fun getInputFilter(): FileBasedIndex.InputFilter = object : DefaultFileTypeSpecificInputFilter(JavaFileType.INSTANCE) {
override fun acceptInput(file: VirtualFile): Boolean = JavaParserDefinition.JAVA_FILE.shouldBuildStubFor(file)
}
override fun dependsOnFileContent(): Boolean = true
override fun getVersion(): Int = 1
} | apache-2.0 | cd39cc8e22a6932ebd8408b50850242d | 43.514851 | 150 | 0.701924 | 5.082533 | false | false | false | false |
paplorinc/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeRangeList.kt | 6 | 1584 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.mergeinfo
import org.jetbrains.idea.svn.api.ErrorCode.MERGE_INFO_PARSE_ERROR
import org.jetbrains.idea.svn.commandLine.SvnBindException
data class MergeRangeList(val ranges: Set<MergeRange>) {
companion object {
@JvmStatic
@Throws(SvnBindException::class)
fun parseMergeInfo(value: String): Map<String, MergeRangeList> = if (value.isEmpty()) emptyMap()
else value.lineSequence().map { parseLine(it) }.toMap()
@Throws(SvnBindException::class)
fun parseRange(value: String): MergeRange {
val revisions = value.removeSuffix("*").split('-')
if (revisions.isEmpty() || revisions.size > 2) throwParseFailed(value)
val start = parseRevision(revisions[0])
val end = if (revisions.size == 2) parseRevision(revisions[1]) else start
return MergeRange(start, end, value.lastOrNull() != '*')
}
private fun parseLine(value: String): Pair<String, MergeRangeList> {
val parts = value.split(':')
if (parts.size != 2) throwParseFailed(value)
return Pair(parts[0], MergeRangeList(parts[1].splitToSequence(',').map { parseRange(it) }.toSet()))
}
private fun parseRevision(value: String) = try {
value.toLong()
}
catch (e: NumberFormatException) {
throwParseFailed(value)
}
private fun throwParseFailed(value: String): Nothing = throw SvnBindException(MERGE_INFO_PARSE_ERROR, "Could not parse $value")
}
} | apache-2.0 | 7b7dec2a7741bcdec0ee9a51d0bb1cf6 | 38.625 | 140 | 0.698232 | 4.010127 | false | false | false | false |
noboru-i/SlideViewer | app/src/main/java/hm/orz/chaos114/android/slideviewer/util/AnalyticsManager.kt | 1 | 1703 | package hm.orz.chaos114.android.slideviewer.util
import android.app.Application
import android.net.Uri
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import hm.orz.chaos114.android.slideviewer.infra.repository.TalkRepository
import java.util.Locale
import javax.inject.Inject
class AnalyticsManager @Inject constructor(
private val app: Application
) {
private val mFirebaseAnalytics: FirebaseAnalytics = FirebaseAnalytics.getInstance(app)
fun sendChangePageEvent(url: String, page: Int) {
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, getPath(url))
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "slide")
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "slide")
bundle.putDouble(FirebaseAnalytics.Param.VALUE, page.toDouble())
sendFirebaseEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
}
fun sendStartEvent(url: String) {
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "slide")
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, getPath(url))
sendFirebaseEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle)
}
fun updateUserProperty() {
val talkRepository = TalkRepository(app)
val count = talkRepository.count()
mFirebaseAnalytics.setUserProperty("slide_count", String.format(Locale.getDefault(), "%d", count))
}
private fun sendFirebaseEvent(event: String, bundle: Bundle) {
mFirebaseAnalytics.logEvent(event, bundle)
}
private fun getPath(url: String): String {
val uri = Uri.parse(url)
return uri.path
}
}
| mit | edc599aff430a042ed60efd6d20f83cf | 35.234043 | 106 | 0.725191 | 4.389175 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/searcheverywhere/NativePsiAndKtLightElementEqualityProviderTest.kt | 3 | 2901 | // 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.searcheverywhere
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.asJava.LightClassGenerationSupport
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.utils.addToStdlib.cast
/**
* @see KtSearchEverywhereEqualityProvider
*/
class NativePsiAndKtLightElementEqualityProviderTest : KotlinSearchEverywhereTestCase() {
fun `test only class presented`() {
val file = myFixture.configureByText("MyKotlinClassWithStrangeName.kt", "class MyKotlinClassWithStrangeName")
val klass = file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>()!!
val ulc = LightClassGenerationSupport.getInstance(project).createUltraLightClass(klass)!!
findPsiByPattern("MyKotlinClassWithStrangeName") { results ->
assertTrue(klass in results)
assertFalse(file in results)
assertFalse(ulc in results)
}
}
fun `test class conflict`() {
val file = myFixture.configureByText(
"MyKotlinClassWithStrangeName.kt",
"package one.two\nclass MyKotlinClassWithStrangeName\nclass MyKotlinClassWithStrangeName<T>",
) as KtFile
val klass = file.declarations.first() as KtClass
val klass2 = file.declarations.last() as KtClass
val ulc = LightClassGenerationSupport.getInstance(project).createUltraLightClass(klass)!!
val ulc2 = LightClassGenerationSupport.getInstance(project).createUltraLightClass(klass2)!!
findPsiByPattern("MyKotlinClassWithStrangeName") { results ->
assertTrue(klass in results)
assertTrue(klass2 in results)
assertFalse(file in results)
assertFalse(ulc in results)
assertFalse(ulc2 in results)
}
}
fun `test class and file presented`() {
val file = myFixture.configureByText(
"MyKotlinClassWithStrangeName.kt",
"class MyKotlinClassWithStrangeName\nfun t(){}",
) as KtFile
val klass = file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>()!!
val ulc = LightClassGenerationSupport.getInstance(project).createUltraLightClass(klass)!!
val syntheticClass = file.declarations.last().cast<KtNamedFunction>().toLightMethods().single().parent
findPsiByPattern("MyKotlinClassWithStrangeName") { results ->
assertTrue(results.toString(), results.size == 1)
assertTrue(klass in results)
assertFalse(file in results)
assertFalse(syntheticClass in results)
assertFalse(ulc in results)
}
}
}
| apache-2.0 | 864320edf36de27a6e09872cf46cac27 | 44.328125 | 120 | 0.707687 | 4.87563 | false | true | false | false |
youdonghai/intellij-community | platform/credential-store/src/CredentialStoreWrapper.kt | 2 | 5166 | /*
* 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.credentialStore
import com.intellij.ide.passwordSafe.PasswordStorage
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
import com.intellij.util.concurrency.QueueProcessor
private val nullCredentials = Credentials("\u0000", OneTimeString("\u0000"))
private val NOTIFICATION_MANAGER by lazy {
// we use name "Password Safe" instead of "Credentials Store" because it was named so previously (and no much sense to rename it)
SingletonNotificationManager(NotificationGroup.balloonGroup("Password Safe"), NotificationType.WARNING, null)
}
private class CredentialStoreWrapper(private val store: CredentialStore) : PasswordStorage {
private val fallbackStore = lazy { KeePassCredentialStore(memoryOnly = true) }
private val queueProcessor = QueueProcessor<() -> Unit>({ it() })
private val postponedCredentials = KeePassCredentialStore(memoryOnly = true)
override fun get(attributes: CredentialAttributes): Credentials? {
postponedCredentials.get(attributes)?.let {
return if (it == nullCredentials) null else it
}
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
val requestor = attributes.requestor
val userName = attributes.userName
try {
val value = store.get(attributes)
if (value != null || requestor == null || userName == null) {
return value
}
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
return store.get(attributes)
}
catch (e: Throwable) {
LOG.error(e)
return null
}
LOG.catchAndLog {
fun setNew(oldKey: CredentialAttributes): Credentials? {
return store.get(oldKey)?.let {
set(oldKey, null)
// https://youtrack.jetbrains.com/issue/IDEA-160341
set(attributes, Credentials(userName, it.password?.clone(false, true)))
Credentials(userName, it.password)
}
}
// try old key - as hash
setNew(toOldKey(requestor, userName))?.let { return it }
val appInfo = ApplicationInfoEx.getInstanceEx()
if (appInfo.isEAP || appInfo.build.isSnapshot) {
setNew(CredentialAttributes(SERVICE_NAME_PREFIX, "${requestor.name}/$userName"))?.let { return it }
}
}
return null
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
fun doSave() {
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
store.set(attributes, credentials)
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
store.set(attributes, credentials)
}
catch (e: Throwable) {
LOG.error(e)
}
postponedCredentials.set(attributes, null)
}
LOG.catchAndLog {
if (fallbackStore.isInitialized()) {
fallbackStore.value.set(attributes, credentials)
}
else {
postponedCredentials.set(attributes, credentials ?: nullCredentials)
queueProcessor.add { doSave() }
}
}
}
}
private fun notifyUnsatisfiedLinkError(e: UnsatisfiedLinkError) {
LOG.error(e)
var message = "Credentials are remembered until ${ApplicationNamesInfo.getInstance().fullProductName} is closed."
if (SystemInfo.isLinux) {
message += "\nPlease install required package libsecret-1-0: sudo apt-get install libsecret-1-0 gnome-keyring"
}
NOTIFICATION_MANAGER.notify("Cannot Access Native Keychain", message)
}
private class MacOsCredentialStoreFactory : CredentialStoreFactory {
override fun create(): PasswordStorage? {
if (isMacOsCredentialStoreSupported && SystemProperties.getBooleanProperty("use.mac.keychain", true)) {
return CredentialStoreWrapper(KeyChainCredentialStore())
}
return null
}
}
private class LinuxSecretCredentialStoreFactory : CredentialStoreFactory {
override fun create(): PasswordStorage? {
if (SystemInfo.isLinux && SystemProperties.getBooleanProperty("use.linux.keychain", true)) {
return CredentialStoreWrapper(SecretCredentialStore("com.intellij.credentialStore.Credential"))
}
return null
}
} | apache-2.0 | 2fc2c7cb651c2fddcdeeca313d3d6fee | 34.881944 | 131 | 0.72048 | 4.6125 | false | false | false | false |
JetBrains/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/CollectionEntity.kt | 1 | 2022 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
interface CollectionFieldEntity : WorkspaceEntity {
val versions: Set<Int>
val names: List<String>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : CollectionFieldEntity, WorkspaceEntity.Builder<CollectionFieldEntity>, ObjBuilder<CollectionFieldEntity> {
override var entitySource: EntitySource
override var versions: MutableSet<Int>
override var names: MutableList<String>
}
companion object : Type<CollectionFieldEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(versions: Set<Int>,
names: List<String>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): CollectionFieldEntity {
val builder = builder()
builder.versions = versions.toMutableWorkspaceSet()
builder.names = names.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: CollectionFieldEntity, modification: CollectionFieldEntity.Builder.() -> Unit) = modifyEntity(
CollectionFieldEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | 0133a3bbe7e3b3632858988f7466f90d | 37.150943 | 140 | 0.763106 | 5.171355 | false | false | false | false |
googlearchive/android-PictureInPicture | kotlinApp/app/src/androidTest/java/com/example/android/pictureinpicture/MediaSessionPlaybackActivityTest.kt | 2 | 6490 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.pictureinpicture
import android.content.pm.ActivityInfo
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.UiController
import android.support.test.espresso.ViewAction
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom
import android.support.test.espresso.matcher.ViewMatchers.isDisplayed
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.v4.media.session.PlaybackStateCompat
import android.view.View
import com.example.android.pictureinpicture.widget.MovieView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.not
import org.hamcrest.TypeSafeMatcher
import org.hamcrest.core.AllOf.allOf
import org.hamcrest.core.Is.`is`
import org.hamcrest.core.IsEqual.equalTo
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MediaSessionPlaybackActivityTest {
@Rule @JvmField
val rule = ActivityTestRule(MediaSessionPlaybackActivity::class.java)
@Test
fun movie_playingOnPip() {
// The movie should be playing on start
onView(withId(R.id.movie))
.check(matches(allOf(isDisplayed(), isPlaying())))
.perform(showControls())
// Click on the button to enter Picture-in-Picture mode
onView(withId(R.id.minimize)).perform(click())
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// The Activity is paused. We cannot use Espresso to test paused activities.
rule.runOnUiThread {
// We are now in Picture-in-Picture mode
assertTrue(rule.activity.isInPictureInPictureMode)
val view = rule.activity.findViewById<MovieView>(R.id.movie)
assertNotNull(view)
// The video should still be playing
assertTrue(view.isPlaying)
// The media session state should be playing.
assertMediaStateIs(PlaybackStateCompat.STATE_PLAYING)
}
}
@Test
fun movie_pauseAndResume() {
// The movie should be playing on start
onView(withId(R.id.movie))
.check(matches(allOf(isDisplayed(), isPlaying())))
.perform(showControls())
// Pause
onView(withId(R.id.toggle)).perform(click())
onView(withId(R.id.movie)).check(matches(not(isPlaying())))
// The media session state should be paused.
assertMediaStateIs(PlaybackStateCompat.STATE_PAUSED)
// Resume
onView(withId(R.id.toggle)).perform(click())
onView(withId(R.id.movie)).check(matches(isPlaying()))
// The media session state should be playing.
assertMediaStateIs(PlaybackStateCompat.STATE_PLAYING)
}
@Test
fun fullscreen_enabledOnLandscape() {
rule.runOnUiThread { rule.activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE }
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
rule.runOnUiThread {
val decorView = rule.activity.window.decorView
assertThat(decorView.systemUiVisibility,
hasFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN))
}
}
@Test
fun fullscreen_disabledOnPortrait() {
rule.runOnUiThread {
rule.activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
rule.runOnUiThread {
val decorView = rule.activity.window.decorView
assertThat(decorView.systemUiVisibility,
not(hasFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)))
}
}
private fun assertMediaStateIs(@PlaybackStateCompat.State expectedState: Int) {
val state = rule.activity.mediaController.playbackState
assertNotNull(state)
assertThat(
"MediaSession is not in the correct state",
state?.state,
`is`<Int>(equalTo<Int>(expectedState)))
}
private fun isPlaying(): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun matchesSafely(view: View): Boolean {
return (view as MovieView).isPlaying
}
override fun describeTo(description: Description) {
description.appendText("MovieView is playing")
}
}
}
private fun showControls(): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isAssignableFrom(MovieView::class.java)
}
override fun getDescription(): String {
return "Show controls of MovieView"
}
override fun perform(uiController: UiController, view: View) {
uiController.loopMainThreadUntilIdle()
(view as MovieView).showControls()
uiController.loopMainThreadUntilIdle()
}
}
}
private fun hasFlag(flag: Int): Matcher<in Int> {
return object : TypeSafeMatcher<Int>() {
override fun matchesSafely(i: Int?): Boolean {
return i?.and(flag) == flag
}
override fun describeTo(description: Description) {
description.appendText("Flag integer contains " + flag)
}
}
}
}
| apache-2.0 | cdd803ffdfabda6ce6552e74ffa64690 | 36.953216 | 109 | 0.676425 | 4.883371 | false | true | false | false |
apollographql/apollo-android | apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/network/http/BatchingHttpInterceptor.kt | 1 | 8584 | package com.apollographql.apollo3.network.http
import com.apollographql.apollo3.ApolloCall
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.annotations.ApolloInternal
import com.apollographql.apollo3.api.AnyAdapter
import com.apollographql.apollo3.api.CustomScalarAdapters
import com.apollographql.apollo3.api.ExecutionOptions
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.http.HttpBody
import com.apollographql.apollo3.api.http.HttpMethod
import com.apollographql.apollo3.api.http.HttpRequest
import com.apollographql.apollo3.api.http.HttpResponse
import com.apollographql.apollo3.api.http.valueOf
import com.apollographql.apollo3.api.json.BufferedSinkJsonWriter
import com.apollographql.apollo3.api.json.BufferedSourceJsonReader
import com.apollographql.apollo3.api.json.internal.buildJsonByteString
import com.apollographql.apollo3.api.json.internal.writeArray
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.exception.ApolloHttpException
import com.apollographql.apollo3.internal.BackgroundDispatcher
import com.apollographql.apollo3.mpp.ensureNeverFrozen
import com.apollographql.apollo3.mpp.freeze
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okio.Buffer
import okio.BufferedSink
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
/**
* An [HttpInterceptor] that batches HTTP queries to execute multiple at once.
* This reduces the number of HTTP round trips at the price of increased latency as
* every request in the batch is now as slow as the slowest one.
* Some servers might have a per-HTTP-call cache making it faster to resolve 1 big array
* of n queries compared to resolving the n queries separately.
*
* Because [com.apollographql.apollo3.ApolloCall.execute] suspends, it only makes sense to use query batching when queries are
* executed from different coroutines. Use [async] to create a new coroutine if needed
*
* [BatchingHttpInterceptor] buffers the whole response, so it might additionally introduce some
* client-side latency as it cannot amortize parsing/building the models during network I/O.
*
* [BatchingHttpInterceptor] only works with Post requests. Trying to batch a Get request is undefined.
*
* @param batchIntervalMillis the maximum time interval before a new batch is sent
* @param maxBatchSize the maximum number of requests queued before a new batch is sent
* @param exposeErrorBody configures whether to expose the error body in [ApolloHttpException].
*
* If you're setting this to `true`, you **must** catch [ApolloHttpException] and close the body explicitly
* to avoid sockets and other resources leaking.
*
* Default: false
*/
class BatchingHttpInterceptor @JvmOverloads constructor(
private val batchIntervalMillis: Long = 10,
private val maxBatchSize: Int = 10,
private val exposeErrorBody: Boolean = false,
) : HttpInterceptor {
private val dispatcher = BackgroundDispatcher()
private val scope = CoroutineScope(dispatcher.coroutineDispatcher)
private val mutex = Mutex()
private var disposed = false
private val job: Job
private var interceptorChain: HttpInterceptorChain? = null
init {
ensureNeverFrozen(this)
job = scope.launch {
while (true) {
delay(batchIntervalMillis)
executePendingRequests()
}
}
}
class PendingRequest(
val request: HttpRequest,
) {
val deferred = CompletableDeferred<HttpResponse>()
}
private val pendingRequests = mutableListOf<PendingRequest>()
override suspend fun intercept(request: HttpRequest, chain: HttpInterceptorChain): HttpResponse {
// Batching is enabled by default, unless explicitly disabled
val canBeBatched = request.headers.valueOf(ExecutionOptions.CAN_BE_BATCHED)?.toBoolean() ?: true
if (!canBeBatched) {
// Remove the CAN_BE_BATCHED header and forward directly
return chain.proceed(request.newBuilder().addHeaders(headers = request.headers.filter { it.name != ExecutionOptions.CAN_BE_BATCHED }).build())
}
// Keep the chain for later
interceptorChain = chain
val pendingRequest = PendingRequest(request)
val sendNow = mutex.withLock {
// if there was an error, the previous job was already canceled, ignore that error
pendingRequests.add(pendingRequest)
pendingRequests.size >= maxBatchSize
}
if (sendNow) {
executePendingRequests()
}
return pendingRequest.deferred.await()
}
private suspend fun executePendingRequests() {
val pending = mutex.withLock {
val copy = pendingRequests.toList()
pendingRequests.clear()
copy
}
if (pending.isEmpty()) {
return
}
val firstRequest = pending.first().request
val allLengths = pending.map { it.request.headers.valueOf("Content-Length")?.toLongOrNull() ?: -1L }
val contentLength = if (allLengths.contains(-1)) {
-1
} else {
allLengths.sum()
}
val allBodies = pending.map { it.request.body ?: error("empty body while batching queries") }
val body = object : HttpBody {
override val contentType = "application/json"
override val contentLength = contentLength
override fun writeTo(bufferedSink: BufferedSink) {
val writer = BufferedSinkJsonWriter(bufferedSink)
@OptIn(ApolloInternal::class)
writer.writeArray {
this as BufferedSinkJsonWriter
allBodies.forEach { body ->
val buffer = Buffer()
body.writeTo(buffer)
jsonValue(buffer.readUtf8())
}
}
}
}
val request = HttpRequest.Builder(
method = HttpMethod.Post,
url = firstRequest.url,
).body(
body = body,
).build()
freeze(request)
var exception: ApolloException? = null
val result = try {
val response = interceptorChain!!.proceed(request)
if (response.statusCode !in 200..299) {
val maybeBody = if (exposeErrorBody) {
response.body
} else {
response.body?.close()
null
}
throw ApolloHttpException(
response.statusCode,
response.headers,
maybeBody,
"HTTP error ${response.statusCode} while executing batched query"
)
}
val responseBody = response.body ?: throw ApolloException("null body when executing batched query")
// TODO: this is most likely going to transform BigNumbers into strings, not sure how much of an issue that is
val list = AnyAdapter.fromJson(BufferedSourceJsonReader(responseBody), CustomScalarAdapters.Empty)
if (list !is List<*>) throw ApolloException("batched query response is not a list when executing batched query")
if (list.size != pending.size) {
throw ApolloException("batched query response count (${list.size}) does not match the requested queries (${pending.size})")
}
list.map {
if (it == null) {
throw ApolloException("batched query response contains a null item")
}
@OptIn(ApolloInternal::class)
buildJsonByteString {
AnyAdapter.toJson(this, CustomScalarAdapters.Empty, it)
}
}
} catch (e: ApolloException) {
exception = e
null
}
if (exception != null) {
pending.forEach {
it.deferred.completeExceptionally(exception)
}
return
} else {
result!!.forEachIndexed { index, byteString ->
// This works because the server must return the responses in order
pending[index].deferred.complete(
HttpResponse.Builder(statusCode = 200)
.body(byteString)
.build()
)
}
}
}
override fun dispose() {
if (!disposed) {
interceptorChain = null
scope.cancel()
dispatcher.dispose()
disposed = true
}
}
companion object {
@JvmStatic
fun configureApolloClientBuilder(apolloClientBuilder: ApolloClient.Builder, canBeBatched: Boolean) {
apolloClientBuilder.canBeBatched(canBeBatched)
}
@JvmStatic
fun <D : Operation.Data> configureApolloCall(apolloCall: ApolloCall<D>, canBeBatched: Boolean) {
apolloCall.canBeBatched(canBeBatched)
}
}
}
| mit | 8272e442df2e59114a9d8b5b3a922013 | 33.894309 | 148 | 0.712255 | 4.59775 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepic/droid/ui/util/ViewExtensions.kt | 2 | 3866 | package org.stepic.droid.ui.util
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.Animation
import android.view.animation.Transformation
import android.webkit.WebView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.children
import androidx.core.view.isVisible
import com.google.android.material.snackbar.Snackbar
fun View.setHeight(height: Int) {
layoutParams.height = height
layoutParams = layoutParams
}
fun ViewGroup.hideAllChildren() {
children.forEach { it.isVisible = false }
}
fun TextView.setCompoundDrawables(
@DrawableRes start: Int = -1,
@DrawableRes top: Int = -1,
@DrawableRes end: Int = -1,
@DrawableRes bottom: Int = -1
) {
fun TextView.getDrawableOrNull(@DrawableRes res: Int) =
if (res != -1) AppCompatResources.getDrawable(context, res) else null
val startDrawable = getDrawableOrNull(start)
val topDrawable = getDrawableOrNull(top)
val endDrawable = getDrawableOrNull(end)
val bottomDrawable = getDrawableOrNull(bottom)
setCompoundDrawablesWithIntrinsicBounds(startDrawable, topDrawable, endDrawable, bottomDrawable)
}
fun TextView.setTextViewBackgroundWithoutResettingPadding(@DrawableRes backgroundRes: Int) {
setBackgroundResource(backgroundRes)
}
inline fun <T : View> T.doOnGlobalLayout(crossinline action: (view: T) -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
action(this@doOnGlobalLayout)
viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
fun View.snackbar(@StringRes messageRes: Int, length: Int = Snackbar.LENGTH_SHORT) {
snackbar(context.getString(messageRes), length)
}
fun View.snackbar(message: String, length: Int = Snackbar.LENGTH_SHORT) {
Snackbar
.make(this, message, length)
.show()
}
private const val durationMillis = 300
fun View.expand(animationListener: Animation.AnimationListener? = null) {
measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val targetHeight = measuredHeight
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
layoutParams.height = 1
visibility = View.VISIBLE
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
layoutParams.height = if (interpolatedTime == 1f)
ViewGroup.LayoutParams.WRAP_CONTENT
else
(targetHeight * interpolatedTime).toInt()
requestLayout()
}
override fun willChangeBounds(): Boolean {
return true
}
}
a.duration = durationMillis.toLong()
animationListener?.let { a.setAnimationListener(it) }
startAnimation(a)
}
fun View.collapse(animationListener: Animation.AnimationListener? = null) {
val initialHeight = measuredHeight
val a = object : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
if (interpolatedTime == 1f) {
visibility = View.GONE
} else {
layoutParams.height = initialHeight - (initialHeight * interpolatedTime).toInt()
requestLayout()
}
}
override fun willChangeBounds(): Boolean {
return true
}
}
a.duration = durationMillis.toLong()
animationListener?.let { a.setAnimationListener(it) }
startAnimation(a)
}
fun WebView.evaluateJavascriptCompat(code: String) {
evaluateJavascript(code, null)
} | apache-2.0 | 3bbfd813d09b37e0ba3c71baf946ee31 | 31.225 | 100 | 0.707967 | 4.766954 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/x11/egl/X11EglPlatformFactory.kt | 3 | 12191 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.x11.egl
import org.freedesktop.jaccall.Pointer
import org.freedesktop.wayland.shared.WlOutputTransform
import org.westford.compositor.core.*
import org.westford.compositor.core.events.RenderOutputDestroyed
import org.westford.compositor.protocol.WlOutput
import org.westford.compositor.protocol.WlOutputFactory
import org.westford.compositor.x11.X11Platform
import org.westford.nativ.libEGL.EglCreatePlatformWindowSurfaceEXT
import org.westford.nativ.libEGL.EglGetPlatformDisplayEXT
import org.westford.nativ.libEGL.LibEGL
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_BACK_BUFFER
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_CLIENT_APIS
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_CONTEXT_CLIENT_VERSION
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_EXTENSIONS
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NONE
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_CONTEXT
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_NO_DISPLAY
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_PLATFORM_X11_KHR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_RENDER_BUFFER
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_VENDOR
import org.westford.nativ.libEGL.LibEGL.Companion.EGL_VERSION
import org.westford.nativ.libxcb.Libxcb
import org.westford.nativ.libxcb.Libxcb.Companion.XCB_CLIENT_MESSAGE
import org.westford.nativ.libxcb.xcb_client_message_event_t
import java.lang.String.format
import java.util.logging.Logger
import javax.inject.Inject
import kotlin.experimental.and
class X11EglPlatformFactory @Inject internal constructor(private val libxcb: Libxcb,
private val libEGL: LibEGL,
private val privateX11EglPlatformFactory: PrivateX11EglPlatformFactory,
private val x11Platform: X11Platform,
private val wlOutputFactory: WlOutputFactory,
private val outputFactory: OutputFactory,
private val glRenderer: GlRenderer,
private val x11EglOutputFactory: X11EglOutputFactory) {
fun create(): X11EglPlatform {
val eglDisplay = createEglDisplay(this.x11Platform.xDisplay)
val eglExtensions = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_EXTENSIONS)).get()
val eglClientApis = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_CLIENT_APIS)).get()
val eglVendor = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_VENDOR)).get()
val eglVersion = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(eglDisplay,
EGL_VERSION)).get()
LOGGER.info(format("Creating X11 EGL output:\n" + "\tEGL client apis: %s\n" + "\tEGL vendor: %s\n" + "\tEGL version: %s\n" + "\tEGL extensions: %s",
eglClientApis,
eglVendor,
eglVersion,
eglExtensions))
val eglConfig = this.glRenderer.eglConfig(eglDisplay,
eglExtensions)
val eglContext = createEglContext(eglDisplay,
eglConfig)
val x11Outputs = this.x11Platform.renderOutputs
val x11EglOutputs = mutableListOf<X11EglOutput>()
val wlOutputs = mutableListOf<WlOutput>()
x11Outputs.forEach {
x11EglOutputs.add(this.x11EglOutputFactory.create(it,
createEglSurface(eglDisplay,
eglConfig,
it.xWindow),
eglContext,
eglDisplay))
}
x11EglOutputs.forEach {
wlOutputs.add(this.wlOutputFactory.create(createOutput(it)))
}
val x11EglPlatform = this.privateX11EglPlatformFactory.create(wlOutputs,
eglDisplay,
eglContext,
eglExtensions)
this.x11Platform.x11EventBus.xEventSignal.connect {
val responseType = (it.get().response_type and 0x7f).toInt()
when (responseType) {
XCB_CLIENT_MESSAGE -> {
handle(it.castp(xcb_client_message_event_t::class.java),
x11EglPlatform)
}
}
}
return x11EglPlatform
}
private fun createEglDisplay(nativeDisplay: Long): Long {
val noDisplayExtensions = Pointer.wrap<String>(String::class.java,
this.libEGL.eglQueryString(EGL_NO_DISPLAY,
EGL_EXTENSIONS))
if (noDisplayExtensions.address == 0L) {
throw RuntimeException("Could not query egl extensions.")
}
val extensions = noDisplayExtensions.get()
if (!extensions.contains("EGL_EXT_platform_x11")) {
throw RuntimeException("Required extension EGL_EXT_platform_x11 not available.")
}
val eglGetPlatformDisplayEXT = Pointer.wrap<EglGetPlatformDisplayEXT>(EglGetPlatformDisplayEXT::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglGetPlatformDisplayEXT").address))
val eglDisplay = eglGetPlatformDisplayEXT.get()(EGL_PLATFORM_X11_KHR,
nativeDisplay,
0L)
if (eglDisplay == 0L) {
throw RuntimeException("eglGetDisplay() failed")
}
if (this.libEGL.eglInitialize(eglDisplay,
0L,
0L) == 0) {
throw RuntimeException("eglInitialize() failed")
}
return eglDisplay
}
private fun createEglContext(eglDisplay: Long,
config: Long): Long {
val eglContextAttribs = Pointer.nref(//@formatter:off
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
//@formatter:on
)
val context = this.libEGL.eglCreateContext(eglDisplay,
config,
EGL_NO_CONTEXT,
eglContextAttribs.address)
if (context == 0L) {
throw RuntimeException("eglCreateContext() failed")
}
return context
}
private fun createEglSurface(eglDisplay: Long,
config: Long,
nativeWindow: Int): Long {
val eglSurfaceAttribs = Pointer.nref(EGL_RENDER_BUFFER,
EGL_BACK_BUFFER,
EGL_NONE)
val eglGetPlatformDisplayEXT = Pointer.wrap<EglCreatePlatformWindowSurfaceEXT>(EglCreatePlatformWindowSurfaceEXT::class.java,
this.libEGL.eglGetProcAddress(Pointer.nref("eglCreatePlatformWindowSurfaceEXT").address))
val eglSurface = eglGetPlatformDisplayEXT.get()(eglDisplay,
config,
Pointer.nref(nativeWindow).address,
eglSurfaceAttribs.address)
if (eglSurface == 0L) {
throw RuntimeException("eglCreateWindowSurface() failed")
}
return eglSurface
}
private fun createOutput(x11EglOutput: X11EglOutput): Output {
val x11Output = x11EglOutput.x11Output
val screen = x11Output.screen
val width = x11Output.width
val height = x11Output.height
val outputGeometry = OutputGeometry(x = x11Output.x,
y = x11Output.y,
subpixel = 0,
make = "Westford xcb",
model = "X11",
physicalWidth = (width / screen.width_in_pixels * screen.width_in_millimeters),
physicalHeight = (height / screen.height_in_pixels * screen.height_in_millimeters),
transform = WlOutputTransform.NORMAL.value)
val outputMode = OutputMode(flags = 0,
width = width,
height = height,
refresh = 60)
return this.outputFactory.create(x11EglOutput,
x11Output.name,
outputGeometry,
outputMode)
}
private fun handle(event: Pointer<xcb_client_message_event_t>,
x11EglPlatform: X11EglPlatform) {
val atom = event.get().data().data32.get()
val sourceWindow = event.get().window
if (atom == this.x11Platform.x11Atoms["WM_DELETE_WINDOW"]) {
val wlOutputIterator = x11EglPlatform.wlOutputs.iterator()
while (wlOutputIterator.hasNext()) {
val wlOutput = wlOutputIterator.next()
val x11EglOutput = wlOutput.output.renderOutput as X11EglOutput
val x11Output = x11EglOutput.x11Output
if (x11Output.xWindow == sourceWindow) {
this.libxcb.xcb_destroy_window(this.x11Platform.xcbConnection,
sourceWindow)
wlOutputIterator.remove()
x11EglPlatform.renderOutputDestroyedSignal.emit(RenderOutputDestroyed(wlOutput))
return
}
}
}
}
companion object {
private val LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
}
}
| agpl-3.0 | caf3e2bc930955e8e4280b40c1c18b5f | 49.376033 | 176 | 0.517021 | 5.605057 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/flow/Channels.kt | 1 | 9173 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("FlowKt")
package kotlinx.coroutines.flow
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.internal.*
import kotlin.coroutines.*
import kotlin.jvm.*
import kotlinx.coroutines.flow.internal.unsafeFlow as flow
/**
* Emits all elements from the given [channel] to this flow collector and [cancels][cancel] (consumes)
* the channel afterwards. If you need to iterate over the channel without consuming it,
* a regular `for` loop should be used instead.
*
* Note, that emitting values from a channel into a flow is not atomic. A value that was received from the
* channel many not reach the flow collector if it was cancelled and will be lost.
*
* This function provides a more efficient shorthand for `channel.consumeEach { value -> emit(value) }`.
* See [consumeEach][ReceiveChannel.consumeEach].
*/
public suspend fun <T> FlowCollector<T>.emitAll(channel: ReceiveChannel<T>): Unit =
emitAllImpl(channel, consume = true)
private suspend fun <T> FlowCollector<T>.emitAllImpl(channel: ReceiveChannel<T>, consume: Boolean) {
ensureActive()
// Manually inlined "consumeEach" implementation that does not use iterator but works via "receiveCatching".
// It has smaller and more efficient spilled state which also allows to implement a manual kludge to
// fix retention of the last emitted value.
// See https://youtrack.jetbrains.com/issue/KT-16222
// See https://github.com/Kotlin/kotlinx.coroutines/issues/1333
var cause: Throwable? = null
try {
while (true) {
// :KLUDGE: This "run" call is resolved to an extension function "run" and forces the size of
// spilled state to increase by an additional slot, so there are 4 object local variables spilled here
// which makes the size of spill state equal to the 4 slots that are spilled around subsequent "emit"
// call, ensuring that the previously emitted value is not retained in the state while receiving
// the next one.
// L$0 <- this
// L$1 <- channel
// L$2 <- cause
// L$3 <- this$run (actually equal to this)
val result = run { channel.receiveCatching() }
if (result.isClosed) {
result.exceptionOrNull()?.let { throw it }
break // returns normally when result.closeCause == null
}
// result is spilled here to the coroutine state and retained after the call, even though
// it is not actually needed in the next loop iteration.
// L$0 <- this
// L$1 <- channel
// L$2 <- cause
// L$3 <- result
emit(result.getOrThrow())
}
} catch (e: Throwable) {
cause = e
throw e
} finally {
if (consume) channel.cancelConsumed(cause)
}
}
/**
* Represents the given receive channel as a hot flow and [receives][ReceiveChannel.receive] from the channel
* in fan-out fashion every time this flow is collected. One element will be emitted to one collector only.
*
* See also [consumeAsFlow] which ensures that the resulting flow is collected just once.
*
* ### Cancellation semantics
*
* * Flow collectors are cancelled when the original channel is [closed][SendChannel.close] with an exception.
* * Flow collectors complete normally when the original channel is [closed][SendChannel.close] normally.
* * Failure or cancellation of the flow collector does not affect the channel.
*
* ### Operator fusion
*
* Adjacent applications of [flowOn], [buffer], [conflate], and [produceIn] to the result of `receiveAsFlow` are fused.
* In particular, [produceIn] returns the original channel.
* Calls to [flowOn] have generally no effect, unless [buffer] is used to explicitly request buffering.
*/
public fun <T> ReceiveChannel<T>.receiveAsFlow(): Flow<T> = ChannelAsFlow(this, consume = false)
/**
* Represents the given receive channel as a hot flow and [consumes][ReceiveChannel.consume] the channel
* on the first collection from this flow. The resulting flow can be collected just once and throws
* [IllegalStateException] when trying to collect it more than once.
*
* See also [receiveAsFlow] which supports multiple collectors of the resulting flow.
*
* ### Cancellation semantics
*
* * Flow collector is cancelled when the original channel is [closed][SendChannel.close] with an exception.
* * Flow collector completes normally when the original channel is [closed][SendChannel.close] normally.
* * If the flow collector fails with an exception, the source channel is [cancelled][ReceiveChannel.cancel].
*
* ### Operator fusion
*
* Adjacent applications of [flowOn], [buffer], [conflate], and [produceIn] to the result of `consumeAsFlow` are fused.
* In particular, [produceIn] returns the original channel (but throws [IllegalStateException] on repeated calls).
* Calls to [flowOn] have generally no effect, unless [buffer] is used to explicitly request buffering.
*/
public fun <T> ReceiveChannel<T>.consumeAsFlow(): Flow<T> = ChannelAsFlow(this, consume = true)
/**
* Represents an existing [channel] as [ChannelFlow] implementation.
* It fuses with subsequent [flowOn] operators, but for the most part ignores the specified context.
* However, additional [buffer] calls cause a separate buffering channel to be created and that is where
* the context might play a role, because it is used by the producing coroutine.
*/
private class ChannelAsFlow<T>(
private val channel: ReceiveChannel<T>,
private val consume: Boolean,
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = Channel.OPTIONAL_CHANNEL,
onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND
) : ChannelFlow<T>(context, capacity, onBufferOverflow) {
private val consumed = atomic(false)
private fun markConsumed() {
if (consume) {
check(!consumed.getAndSet(true)) { "ReceiveChannel.consumeAsFlow can be collected just once" }
}
}
override fun create(context: CoroutineContext, capacity: Int, onBufferOverflow: BufferOverflow): ChannelFlow<T> =
ChannelAsFlow(channel, consume, context, capacity, onBufferOverflow)
override fun dropChannelOperators(): Flow<T> =
ChannelAsFlow(channel, consume)
override suspend fun collectTo(scope: ProducerScope<T>) =
SendingCollector(scope).emitAllImpl(channel, consume) // use efficient channel receiving code from emitAll
override fun produceImpl(scope: CoroutineScope): ReceiveChannel<T> {
markConsumed() // fail fast on repeated attempt to collect it
return if (capacity == Channel.OPTIONAL_CHANNEL) {
channel // direct
} else
super.produceImpl(scope) // extra buffering channel
}
override suspend fun collect(collector: FlowCollector<T>) {
if (capacity == Channel.OPTIONAL_CHANNEL) {
markConsumed()
collector.emitAllImpl(channel, consume) // direct
} else {
super.collect(collector) // extra buffering channel, produceImpl will mark it as consumed
}
}
override fun additionalToStringProps(): String = "channel=$channel"
}
/**
* Represents the given broadcast channel as a hot flow.
* Every flow collector will trigger a new broadcast channel subscription.
*
* ### Cancellation semantics
* 1) Flow consumer is cancelled when the original channel is cancelled.
* 2) Flow consumer completes normally when the original channel completes (~is closed) normally.
* 3) If the flow consumer fails with an exception, subscription is cancelled.
*/
@Deprecated(
level = DeprecationLevel.WARNING,
message = "'BroadcastChannel' is obsolete and all corresponding operators are deprecated " +
"in the favour of StateFlow and SharedFlow"
) // Since 1.5.0, was @FlowPreview, safe to remove in 1.7.0
public fun <T> BroadcastChannel<T>.asFlow(): Flow<T> = flow {
emitAll(openSubscription())
}
/**
* Creates a [produce] coroutine that collects the given flow.
*
* This transformation is **stateful**, it launches a [produce] coroutine
* that collects the given flow, and has the same behavior:
*
* * if collecting the flow throws, the channel will be closed with that exception
* * if the [ReceiveChannel] is cancelled, the collection of the flow will be cancelled
* * if collecting the flow completes normally, the [ReceiveChannel] will be closed normally
*
* A channel with [default][Channel.Factory.BUFFERED] buffer size is created.
* Use [buffer] operator on the flow before calling `produceIn` to specify a value other than
* default and to control what happens when data is produced faster than it is consumed,
* that is to control backpressure behavior.
*/
@FlowPreview
public fun <T> Flow<T>.produceIn(
scope: CoroutineScope
): ReceiveChannel<T> =
asChannelFlow().produceImpl(scope)
| apache-2.0 | c5cea36d7517e679afba2f8ebf331547 | 44.865 | 119 | 0.704459 | 4.492165 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/utils/Props.kt | 1 | 1463 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.utils
import java.io.File
/**
* Created by kishorereddy on 5/19/17.
*/
object Props {
// OS
val osArch get() = getOrEmpty("os.arch")
val osName get() = getOrEmpty("os.name")
val osVersion get() = getOrEmpty("os.version")
// Java
val javaClassPath get() = getOrEmpty("java.class.path")
val javaHome get() = getOrEmpty("java.home")
val javaVendor get() = getOrEmpty("java.vendor")
val javaVersion get() = getOrEmpty("java.version")
val javaVmInfo get() = getOrEmpty("java.vm.info")
val javaVmName get() = getOrEmpty("java.vm.name")
val javaVmVendor get() = getOrEmpty("java.vm.vendor")
val javaVmVersion get() = getOrEmpty("java.vm.version")
val tmpDir get() = getOrEmpty("java.io.tmpdir")
val pathSeparator get() = File.separatorChar.toString()
// User
val userDir get() = getOrEmpty("user.dir")
val userHome get() = getOrEmpty("user.home")
val userName get() = getOrEmpty("user.name")
fun getOrEmpty(name: String): String {
val pval = System.getProperty(name)
return pval.orEmpty()
}
}
| apache-2.0 | 0fe3906cf51d986c84ad42edc893f88d | 28.857143 | 59 | 0.664388 | 3.542373 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/internal/ml/ResourcesMetadataReader.kt | 1 | 1278 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.ml
class ResourcesMetadataReader(private val metadataHolder: Class<*>, private val featuresDirectory: String) {
fun binaryFeatures(): String = resourceContent("binary.json")
fun floatFeatures(): String = resourceContent("float.json")
fun categoricalFeatures(): String = resourceContent("categorical.json")
fun allKnown(): String = resourceContent("all_features.json")
fun featureOrderDirect(): List<String> = resourceContent("features_order.txt").lines()
fun extractVersion(): String? {
val resource = metadataHolder.classLoader.getResource("$featuresDirectory/binary.json") ?: return null
val result = resource.file.substringBeforeLast(".jar!", "").substringAfterLast("-", "")
return if (result.isBlank()) null else result
}
private fun resourceContent(fileName: String): String {
val resource = "$featuresDirectory/$fileName"
val fileStream = metadataHolder.classLoader.getResourceAsStream(resource)
?: throw InconsistentMetadataException("Metadata file not found: $resource")
return fileStream.bufferedReader().use { it.readText() }
}
}
| apache-2.0 | 20edf0d0de2fc1562590a1bd7d41fb0b | 52.25 | 140 | 0.740219 | 4.715867 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/controlStructures/continueInFor.kt | 2 | 2578 | fun for_int_range(): Int {
var c = 0
for (i in 1..10) {
if (c >= 5) continue
c++
}
return c
}
fun for_byte_range(): Int {
var c = 0
val from: Byte = 1
val to: Byte = 10
for (i in from..to) {
if (c >= 5) continue
c++
}
return c
}
fun for_long_range(): Int {
var c = 0
val from: Long = 1
val to: Long = 10
for (i in from..to) {
if (c >= 5) continue
c++
}
return c
}
fun for_int_list(): Int {
val a = ArrayList<Int>()
a.add(0); a.add(0); a.add(0); a.add(0); a.add(0)
a.add(0); a.add(0); a.add(0); a.add(0); a.add(0)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun for_byte_list(): Int {
val a = ArrayList<Byte>()
a.add(0); a.add(0); a.add(0); a.add(0); a.add(0)
a.add(0); a.add(0); a.add(0); a.add(0); a.add(0)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun for_long_list(): Int {
val a = ArrayList<Long>()
a.add(0); a.add(0); a.add(0); a.add(0); a.add(0)
a.add(0); a.add(0); a.add(0); a.add(0); a.add(0)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun for_double_list(): Int {
val a = ArrayList<Double>()
a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0)
a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun for_object_list(): Int {
val a = ArrayList<Any>()
a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0)
a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0); a.add(0.0)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun for_str_array(): Int {
val a = arrayOfNulls<String>(10)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun for_intarray(): Int {
val a = IntArray(10)
var c = 0
for (i in a) {
if (c >= 5) continue
c++
}
return c
}
fun box(): String {
if (for_int_range() != 5) return "fail 1"
if (for_byte_range() != 5) return "fail 2"
if (for_long_range() != 5) return "fail 3"
if (for_intarray() != 5) return "fail 4"
if (for_str_array() != 5) return "fail 5"
if (for_int_list() != 5) return "fail 6"
if (for_byte_list() != 5) return "fail 7"
if (for_long_list() != 5) return "fail 8"
if (for_double_list() != 5) return "fail 9"
return "OK"
}
| apache-2.0 | 61bf4f9ba27e9a20f7228360c491da2b | 19.95935 | 62 | 0.46315 | 2.512671 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/callableReference/bound/emptyLHS.kt | 1 | 1441 | // LANGUAGE_VERSION: 1.2
var result = ""
class A {
fun memberFunction() { result += "A.mf," }
fun aMemberFunction() { result += "A.amf," }
val memberProperty: Int get() = 42.also { result += "A.mp," }
val aMemberProperty: Int get() = 42.also { result += "A.amp," }
fun test(): String {
(::memberFunction)()
(::aExtensionFunction)()
(::memberProperty)()
(::aExtensionProperty)()
return result
}
inner class B {
fun memberFunction() { result += "B.mf," }
val memberProperty: Int get() = 42.also { result += "B.mp," }
fun test(): String {
(::aMemberFunction)()
(::aExtensionFunction)()
(::aMemberProperty)()
(::aExtensionProperty)()
(::memberFunction)()
(::memberProperty)()
(::bExtensionFunction)()
(::bExtensionProperty)()
return result
}
}
}
fun A.aExtensionFunction() { result += "A.ef," }
val A.aExtensionProperty: Int get() = 42.also { result += "A.ep," }
fun A.B.bExtensionFunction() { result += "B.ef," }
val A.B.bExtensionProperty: Int get() = 42.also { result += "B.ep," }
fun box(): String {
val a = A().test()
if (a != "A.mf,A.ef,A.mp,A.ep,") return "Fail $a"
result = ""
val b = A().B().test()
if (b != "A.amf,A.ef,A.amp,A.ep,B.mf,B.mp,B.ef,B.ep,") return "Fail $b"
return "OK"
}
| apache-2.0 | 42b83ab33a2ed857a8fda3ca97c8da3e | 24.280702 | 75 | 0.516308 | 3.531863 | false | true | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaOptionButtonUI.kt | 12 | 4505 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.laf.darcula.ui
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.*
import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI.getDisabledTextColor
import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI.isDefaultButton
import com.intellij.ide.ui.laf.darcula.ui.DarculaComboBoxUI.getArrowButtonPreferredSize
import com.intellij.ui.components.BasicOptionButtonUI
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.scale
import java.awt.*
import java.awt.geom.Rectangle2D
import javax.swing.AbstractButton
import javax.swing.JComponent
import javax.swing.UIManager
import javax.swing.border.Border
open class DarculaOptionButtonUI : BasicOptionButtonUI() {
protected open val clipXOffset: Int = scale(7)
private var optionButtonBorder: Border? = null
override fun configureOptionButton(): Unit = super.configureOptionButton().also {
optionButtonBorder = optionButton.border
optionButton.border = if (isSimpleButton) optionButtonBorder else mainButton.border
}
override fun unconfigureOptionButton(): Unit = super.unconfigureOptionButton().also {
optionButton.border = optionButtonBorder
optionButtonBorder = null
}
override fun createMainButton(): MainButton = object : MainButton() {
override fun paintNotSimple(g: Graphics2D) {
g.clipRect(0, 0, width - clipXOffset, height)
paintBackground(g, this)
super.paintNotSimple(g)
}
}
override fun configureMainButton(): Unit = super.configureMainButton().also { mainButton.isOpaque = false }
override fun unconfigureMainButton(): Unit = super.unconfigureMainButton().also { mainButton.isOpaque = true }
override fun createArrowButton(): ArrowButton = object : ArrowButton() {
override fun paintNotSimple(g: Graphics2D) {
g.clipRect(clipXOffset, 0, width - clipXOffset, height)
paintBackground(g, this)
super.paintNotSimple(g)
paintArrow(g, this)
}
}
protected open fun paintArrow(g: Graphics2D, b: AbstractButton) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE)
g.color = if (b.isEnabled) getButtonTextColor(b) else getDisabledTextColor()
g.fill(DarculaComboBoxUI.getArrowShape(b))
}
override fun configureArrowButton(): Unit = super.configureArrowButton().also { arrowButton.isOpaque = false }
override fun unconfigureArrowButton(): Unit = super.unconfigureArrowButton().also { arrowButton.isOpaque = true }
override val arrowButtonPreferredSize: Dimension
get() = Dimension(getArrowButtonPreferredSize(null).width, optionButton.preferredSize.height)
override val showPopupXOffset: Int get() = JBUI.scale(3)
override fun paint(g: Graphics, c: JComponent) {
if (!isSimpleButton) paintSeparatorArea(g as Graphics2D, c)
}
protected open fun paintSeparatorArea(g: Graphics2D, c: JComponent) {
g.clipRect(mainButton.width - clipXOffset, 0, 2 * clipXOffset, c.height)
paintBackground(g, c)
mainButton.ui.paint(g, c)
paintSeparator(g, c)
// clipXOffset is rather big and cuts arrow - so we also paint arrow part here
g.translate(mainButton.width, 0)
paintArrow(g, arrowButton)
}
protected open fun paintSeparator(g: Graphics2D, c: JComponent) {
val yOffset = BW.getFloat() + LW.getFloat() + scale(1)
val x = mainButton.width.toFloat()
g.paint = separatorColor(c)
g.fill(Rectangle2D.Float(x, yOffset, LW.getFloat(), mainButton.height - yOffset * 2))
}
private fun separatorColor(c: JComponent) : Paint {
val defButton = isDefaultButton(c as AbstractButton)
val hasFocus = c.hasFocus()
val resourceName = when {
defButton && !hasFocus -> "OptionButton.default.separatorColor"
!defButton && !hasFocus -> "OptionButton.separatorColor"
else -> null
}
return resourceName?.let{ UIManager.getColor(resourceName)} ?: (mainButton.border as DarculaButtonPainter).getBorderPaint(c)
}
override fun updateOptions(): Unit = super.updateOptions().also {
optionButton.border = if (isSimpleButton) optionButtonBorder else mainButton.border
}
companion object {
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun createUI(c: JComponent): DarculaOptionButtonUI = DarculaOptionButtonUI()
}
} | apache-2.0 | 8d84135e7af2ab671d7c0b3b09031638 | 37.512821 | 140 | 0.748058 | 4.36531 | false | true | false | false |
jwren/intellij-community | java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt | 1 | 12792 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.java.JavaBundle
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiUtil
import org.jetbrains.annotations.NonNls
/**
* Checks package accessibility according to JLS 7 "Packages and Modules".
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a>
* @see <a href="http://openjdk.java.net/jeps/261">JEP 261: Module System</a>
*/
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName(): String = JavaBundle.message("java.platform.module.system.name")
override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null
override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false)
private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
val index = ProjectFileIndex.getInstance(useFile.project)
if (useVFile == null || !index.isInLibrarySource(useVFile)) {
if (targetFile != null && targetFile.isPhysical) {
return checkAccess(targetFile, useFile, targetPackageName, quick)
}
else if (useVFile != null) {
val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName)
if (target != null) {
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val moduleScope = module.getModuleWithDependenciesAndLibrariesScope(test)
val dirs = target.getDirectories(moduleScope)
if (dirs.isEmpty()) {
if (target.getFiles(moduleScope).isEmpty()) {
return if (quick) ERR else ErrorWithFixes(JavaErrorBundle.message("package.not.found", target.qualifiedName))
}
else {
return null
}
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return when {
error == null -> null
dirs.size == 1 -> error
dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null
else -> error
}
}
}
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
var useModule = JavaModuleGraphUtil.findDescriptorByElement(place)
if (useModule is LightJavaModule) {
useModule = null
}
if (targetModule != null) {
if (targetModule == useModule) {
return null
}
val targetName = targetModule.name
val useName = useModule?.name ?: "ALL-UNNAMED"
val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) }
if (useModule == null) {
val origin = targetModule.containingFile?.virtualFile
if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) {
return null // a target is not on the mandatory module path
}
var isRoot = !targetName.startsWith("java.") || inAddedModules(module, targetName) || hasUpgrade(module, targetName, packageName, place)
if (!isRoot) {
val root = JavaPsiFacade.getInstance(place.project).findModule("java.se", module.moduleWithLibrariesScope)
isRoot = root == null || JavaModuleGraphUtil.reads(root, targetModule)
}
if (!isRoot) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorBundle.message("module.access.not.in.graph", packageName, targetName),
listOf(AddModulesOptionFix(module, targetName)))
}
}
if (!(targetModule is LightJavaModule ||
JavaModuleGraphUtil.exports(targetModule, packageName, useModule) ||
module != null && inAddedExports(module, targetName, packageName, useName))) {
if (quick) return ERR
val fixes = when {
packageName.isEmpty() -> emptyList()
targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName))
targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName))
else -> emptyList()
}
return when (useModule) {
null -> ErrorWithFixes(JavaErrorBundle.message("module.access.from.unnamed", packageName, targetName), fixes)
else -> ErrorWithFixes(JavaErrorBundle.message("module.access.from.named", packageName, targetName, useName), fixes)
}
}
if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return when {
quick -> ERR
PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes(
JavaErrorBundle.message("module.access.does.not.read", packageName, targetName, useName),
listOf(AddRequiresDirectiveFix(useModule, targetName)))
else -> ErrorWithFixes(JavaErrorBundle.message("module.access.bad.name", packageName, targetName))
}
}
}
else if (useModule != null) {
val autoModule = detectAutomaticModule(target)
if (autoModule == null || !JavaModuleGraphUtil.reads(useModule, autoModule)) {
return if (quick) ERR else ErrorWithFixes(JavaErrorBundle.message("module.access.to.unnamed", packageName, useModule.name))
}
}
return null
}
private fun detectAutomaticModule(target: PsiFileSystemItem): PsiJavaModule? {
val project = target.project
val m = ProjectFileIndex.getInstance(project).getModuleForFile(target.virtualFile) ?: return null
return JavaPsiFacade.getInstance(project).findModule(LightJavaModule.moduleName(m.name), GlobalSearchScope.moduleScope(m))
}
private fun hasUpgrade(module: Module, targetName: String, packageName: String, place: PsiFileSystemItem): Boolean {
if (PsiJavaModule.UPGRADEABLE.contains(targetName)) {
val target = JavaPsiFacade.getInstance(module.project).findPackage(packageName)
if (target != null) {
val useVFile = place.virtualFile
if (useVFile != null) {
val index = ModuleRootManager.getInstance(module).fileIndex
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
return dirs.any { index.getOrderEntryForFile(it.virtualFile) !is JdkOrderEntry }
}
}
}
return false
}
private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
if (options.isEmpty()) return false
val prefix = "${targetName}/${packageName}="
return optionValues(options, "--add-exports")
.filter { it.startsWith(prefix) }
.map { it.substring(prefix.length) }
.flatMap { it.splitToSequence(",") }
.any { it == useName }
}
private fun inAddedModules(module: Module, moduleName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
return optionValues(options, "--add-modules")
.flatMap { it.splitToSequence(",") }
.any { it == moduleName || it == "ALL-SYSTEM" || it == "ALL-MODULE-PATH" }
}
private fun optionValues(options: List<String>, name: String) =
if (options.isEmpty()) emptySequence()
else {
var useValue = false
options.asSequence()
.map {
when {
it == name -> { useValue = true; "" }
useValue -> { useValue = false; it }
it.startsWith(name) && it[name.length] == '=' -> it.substring(name.length + 1)
else -> ""
}
}
.filterNot { it.isEmpty() }
}
private abstract class CompilerOptionFix(private val module: Module) : IntentionAction {
@NonNls override fun getFamilyName() = "Fix compiler option" // not visible
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (isAvailable(project, editor, file)) {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList()
update(options)
JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options)
PsiManager.getInstance(project).dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
}
protected abstract fun update(options: MutableList<String>)
override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = null
override fun startInWriteAction() = true
}
private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) {
private val qualifier = "${targetName}/${packageName}"
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports ${qualifier}=${useName}")
override fun update(options: MutableList<String>) {
var idx = -1; var candidate = -1; var offset = 0
val prefix = "--add-exports"
for ((i, option) in options.withIndex()) {
if (option.startsWith(prefix)) {
if (option.length == prefix.length) { candidate = i + 1 ; offset = 0 }
else if (option[prefix.length] == '=') { candidate = i; offset = prefix.length + 1 }
}
if (i == candidate && option.startsWith(qualifier, offset)) {
val qualifierEnd = qualifier.length + offset
if (option.length == qualifierEnd || option[qualifierEnd] == '=') {
idx = i
}
}
}
when (idx) {
-1 -> options += listOf(prefix, "${qualifier}=${useName}")
else -> options[idx] = "${options[idx].trimEnd(',')},${useName}"
}
}
}
private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) {
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules ${moduleName}")
override fun update(options: MutableList<String>) {
var idx = -1
val prefix = "--add-modules"
for ((i, option) in options.withIndex()) {
if (option.startsWith(prefix)) {
if (option.length == prefix.length) idx = i + 1
else if (option[prefix.length] == '=') idx = i
}
}
when (idx) {
-1 -> options += listOf(prefix, moduleName)
options.size -> options += moduleName
else -> {
val value = options[idx]
options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}"
}
}
}
}
}
| apache-2.0 | 9b4e898ff142211923cead82e9271186 | 44.042254 | 151 | 0.671201 | 4.72902 | false | false | false | false |
JetBrains/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/jcef/impl/JcefBrowserPipeImpl.kt | 1 | 4522 | // 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.intellij.plugins.markdown.ui.preview.jcef.impl
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Disposer
import com.intellij.ui.jcef.JBCefBrowserBase
import com.intellij.ui.jcef.JBCefJSQuery
import org.cef.browser.CefBrowser
import org.cef.browser.CefFrame
import org.cef.handler.CefLoadHandlerAdapter
import org.intellij.plugins.markdown.ui.preview.BrowserPipe
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
/**
* You can check resource/org/intellij/plugins/markdown/ui/preview/jcef/BrowserPipe.js
* for the browser-side implementation.
*
* @param browser Browser to use this pipe with.
* @param injectionAllowedUrls A list of safe URLs which are allowed to receive injection with [BrowserPipe] API.
* All URLs are considered to be safe for injection if this parameter is null.
*/
internal class JcefBrowserPipeImpl(
browser: JBCefBrowserBase,
private val injectionAllowedUrls: List<String>? = null
): BrowserPipe {
private val query = checkNotNull(JBCefJSQuery.create(browser))
private val receiveSubscribers = hashMapOf<String, MutableList<BrowserPipe.Handler>>()
private var browserInstance: JBCefBrowserBase? = browser
private val browser
get() = checkNotNull(browserInstance) { "Browser instance should not be accessed after disposal" }
init {
Disposer.register(this, query)
query.addHandler(::receiveHandler)
browser.jbCefClient.addLoadHandler(object: CefLoadHandlerAdapter() {
override fun onLoadEnd(browser: CefBrowser, frame: CefFrame, httpStatusCode: Int) {
val pageUrl = browser.url
when {
injectionAllowedUrls != null && pageUrl !in injectionAllowedUrls -> {
logger.warn("$pageUrl was not included in the list of allowed for injection urls! Allowed urls:\n$injectionAllowedUrls")
}
else -> inject(browser)
}
}
}, browser.cefBrowser)
}
override fun subscribe(type: String, handler: BrowserPipe.Handler) {
receiveSubscribers.merge(type, mutableListOf(handler)) { current, _ ->
current.also { it.add(handler) }
}
}
override fun removeSubscription(type: String, handler: BrowserPipe.Handler) {
receiveSubscribers[type]?.remove(handler)
if (receiveSubscribers[type]?.isEmpty() == true) {
receiveSubscribers.remove(type)
}
}
override fun send(type: String, data: String) {
val raw = jacksonObjectMapper().writeValueAsString(PackedMessage(type, data))
logger.debug("Sending message: $raw")
browser.cefBrowser.executeJavaScript(postToBrowserFunctionCall(raw), null, 0)
}
override fun dispose() {
receiveSubscribers.clear()
browserInstance = null
}
private fun inject(browser: CefBrowser) {
val code = query.inject("raw")
browser.executeJavaScript("window['$ourBrowserNamespace']['$postToIdeFunctionName'] = raw => $code;", null, 0)
browser.executeJavaScript("window.dispatchEvent(new Event('IdeReady'));", null, 0)
}
@ApiStatus.Internal
data class PackedMessage(
val type: String,
val data: String
)
private fun parseMessage(raw: String): PackedMessage? {
try {
return jacksonObjectMapper().readValue<PackedMessage>(raw).takeIf { it.type.isNotEmpty() }
} catch (exception: IOException) {
logger.error(exception)
return null
}
}
private fun receiveHandler(raw: String?): JBCefJSQuery.Response? {
val (type, data) = raw?.let(::parseMessage) ?: return null
callSubscribers(type, data)
return null
}
private fun callSubscribers(type: String, data: String) {
when (val subscribers = receiveSubscribers[type]) {
null -> logger.warn("No subscribers for $type!\nAttached data: $data")
else -> subscribers.forEach { it.messageReceived(data) }
}
}
companion object {
private val logger = logger<JcefBrowserPipeImpl>()
private fun postToBrowserFunctionCall(data: String): String {
return "window.__IntelliJTools.messagePipe.callBrowserListeners($data);"
}
private const val ourBrowserNamespace = "__IntelliJTools"
private const val postToIdeFunctionName = "___jcefMessagePipePostToIdeFunction"
const val WINDOW_READY_EVENT = "documentReady"
}
}
| apache-2.0 | e292c1ab7542f88dae4077084c9bb9b9 | 36.371901 | 158 | 0.730208 | 4.1987 | false | false | false | false |
androidx/androidx | wear/watchface/watchface-editor/src/androidTest/java/androidx/wear/watchface/editor/EditorSessionGuavaTest.kt | 3 | 12815 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.editor
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.Icon
import android.os.Handler
import android.os.HandlerThread
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.wear.watchface.complications.ComplicationDataSourceInfo
import androidx.wear.watchface.complications.ComplicationSlotBounds
import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy
import androidx.wear.watchface.complications.SystemDataSources
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.data.LongTextComplicationData
import androidx.wear.watchface.CanvasComplication
import androidx.wear.watchface.ComplicationDataSourceChooserIntent
import androidx.wear.watchface.ComplicationHelperActivity
import androidx.wear.watchface.ComplicationSlot
import androidx.wear.watchface.ComplicationSlotsManager
import androidx.wear.watchface.MutableWatchState
import androidx.wear.watchface.WatchFace
import androidx.wear.watchface.client.WatchFaceId
import androidx.wear.watchface.client.asApiEditorState
import androidx.wear.watchface.complications.rendering.CanvasComplicationDrawable
import androidx.wear.watchface.complications.rendering.ComplicationDrawable
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.UserStyleSetting
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CompletableDeferred
import org.junit.After
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import java.time.Instant
import java.util.concurrent.TimeUnit
private const val TIMEOUT_MS = 500L
@RunWith(AndroidJUnit4::class)
@MediumTest
public class EditorSessionGuavaTest {
private val testComponentName = ComponentName("test.package", "test.class")
private val testEditorPackageName = "test.package"
private val testInstanceId = WatchFaceId("TEST_INSTANCE_ID")
private var editorDelegate = Mockito.mock(WatchFace.EditorDelegate::class.java)
private val screenBounds = Rect(0, 0, 400, 400)
private val mockInvalidateCallback =
Mockito.mock(CanvasComplication.InvalidateCallback::class.java)
private val placeholderWatchState = MutableWatchState().asWatchState()
private val mockLeftCanvasComplication =
CanvasComplicationDrawable(
ComplicationDrawable(),
placeholderWatchState,
mockInvalidateCallback
)
private val leftComplication =
@Suppress("DEPRECATION")
ComplicationSlot.createRoundRectComplicationSlotBuilder(
LEFT_COMPLICATION_ID,
{ _, _, -> mockLeftCanvasComplication },
listOf(
ComplicationType.RANGED_VALUE,
ComplicationType.LONG_TEXT,
ComplicationType.SHORT_TEXT,
ComplicationType.MONOCHROMATIC_IMAGE,
ComplicationType.SMALL_IMAGE
),
DefaultComplicationDataSourcePolicy(SystemDataSources.DATA_SOURCE_SUNRISE_SUNSET),
ComplicationSlotBounds(RectF(0.2f, 0.4f, 0.4f, 0.6f))
).setDefaultDataSourceType(ComplicationType.SHORT_TEXT)
.build()
private val mockRightCanvasComplication =
CanvasComplicationDrawable(
ComplicationDrawable(),
placeholderWatchState,
mockInvalidateCallback
)
private val rightComplication =
@Suppress("DEPRECATION")
ComplicationSlot.createRoundRectComplicationSlotBuilder(
RIGHT_COMPLICATION_ID,
{ _, _, -> mockRightCanvasComplication },
listOf(
ComplicationType.RANGED_VALUE,
ComplicationType.LONG_TEXT,
ComplicationType.SHORT_TEXT,
ComplicationType.MONOCHROMATIC_IMAGE,
ComplicationType.SMALL_IMAGE
),
DefaultComplicationDataSourcePolicy(SystemDataSources.DATA_SOURCE_DAY_OF_WEEK),
ComplicationSlotBounds(RectF(0.6f, 0.4f, 0.8f, 0.6f))
).setDefaultDataSourceType(ComplicationType.SHORT_TEXT)
.build()
private val backgroundHandlerThread = HandlerThread("TestBackgroundThread").apply {
start()
}
private val backgroundHandler = Handler(backgroundHandlerThread.looper)
@SuppressLint("NewApi")
private fun createOnWatchFaceEditingTestActivity(
userStyleSettings: List<UserStyleSetting>,
complicationSlots: List<ComplicationSlot>,
watchFaceId: WatchFaceId = testInstanceId,
previewReferenceInstant: Instant = Instant.ofEpochMilli(12345)
): ActivityScenario<OnWatchFaceEditingTestActivity> {
val userStyleRepository = CurrentUserStyleRepository(UserStyleSchema(userStyleSettings))
val complicationSlotsManager =
ComplicationSlotsManager(complicationSlots, userStyleRepository)
complicationSlotsManager.watchState = placeholderWatchState
WatchFace.registerEditorDelegate(testComponentName, editorDelegate)
Mockito.`when`(editorDelegate.complicationSlotsManager).thenReturn(complicationSlotsManager)
Mockito.`when`(editorDelegate.userStyleSchema).thenReturn(userStyleRepository.schema)
Mockito.`when`(editorDelegate.userStyle).thenReturn(userStyleRepository.userStyle.value)
Mockito.`when`(editorDelegate.screenBounds).thenReturn(screenBounds)
Mockito.`when`(editorDelegate.previewReferenceInstant).thenReturn(previewReferenceInstant)
Mockito.`when`(editorDelegate.backgroundThreadHandler).thenReturn(backgroundHandler)
OnWatchFaceEditingTestActivity.complicationDataSourceInfoRetrieverProvider =
TestComplicationDataSourceInfoRetrieverProvider()
return ActivityScenario.launch(
WatchFaceEditorContract().createIntent(
ApplicationProvider.getApplicationContext<Context>(),
EditorRequest(
testComponentName,
testEditorPackageName,
null,
watchFaceId,
null,
null
)
).apply {
component = ComponentName(
ApplicationProvider.getApplicationContext<Context>(),
OnWatchFaceEditingTestActivity::class.java
)
}
)
}
@After
public fun tearDown() {
ComplicationDataSourceChooserContract.useTestComplicationHelperActivity = false
ComplicationHelperActivity.useTestComplicationDataSourceChooserActivity = false
ComplicationHelperActivity.skipPermissionCheck = false
WatchFace.clearAllEditorDelegates()
backgroundHandlerThread.quitSafely()
}
@Test
public fun listenableOpenComplicationDataSourceChooser() {
ComplicationDataSourceChooserContract.useTestComplicationHelperActivity = true
val chosenComplicationDataSourceInfo = ComplicationDataSourceInfo(
"TestDataSource3App",
"TestDataSource3",
Icon.createWithBitmap(
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
),
ComplicationType.LONG_TEXT,
dataSource3
)
TestComplicationHelperActivity.resultIntent = CompletableDeferred(
Intent().apply {
putExtra(
ComplicationDataSourceChooserIntent.EXTRA_PROVIDER_INFO,
chosenComplicationDataSourceInfo.toWireComplicationProviderInfo()
)
}
)
val scenario = createOnWatchFaceEditingTestActivity(
emptyList(),
listOf(leftComplication, rightComplication)
)
lateinit var listenableEditorSession: ListenableEditorSession
scenario.onActivity { activity ->
listenableEditorSession = activity.listenableEditorSession
}
/**
* Invoke [TestComplicationHelperActivity] which will change the data source (and hence
* the preview data) for [LEFT_COMPLICATION_ID].
*/
val chosenComplicationDataSource =
listenableEditorSession.listenableOpenComplicationDataSourceChooser(
LEFT_COMPLICATION_ID
).get(TIMEOUT_MS, TimeUnit.MILLISECONDS)
assertThat(chosenComplicationDataSource).isNotNull()
checkNotNull(chosenComplicationDataSource)
assertThat(chosenComplicationDataSource.complicationSlotId).isEqualTo(LEFT_COMPLICATION_ID)
assertEquals(
chosenComplicationDataSourceInfo,
chosenComplicationDataSource.complicationDataSourceInfo
)
// This should update the preview data to point to the updated dataSource3 data.
val previewComplication =
listenableEditorSession.complicationsPreviewData.value[LEFT_COMPLICATION_ID]
as LongTextComplicationData
assertThat(
previewComplication.text.getTextAt(
ApplicationProvider.getApplicationContext<Context>().resources,
Instant.EPOCH
)
).isEqualTo("DataSource3")
}
@Test
@Suppress("Deprecation") // userStyleSettings
public fun doNotCommitChangesOnClose() {
val scenario = createOnWatchFaceEditingTestActivity(
listOf(colorStyleSetting, watchHandStyleSetting),
emptyList()
)
val editorObserver = TestEditorObserver()
val observerId = EditorService.globalEditorService.registerObserver(editorObserver)
lateinit var listenableEditorSession: ListenableEditorSession
scenario.onActivity { activity ->
listenableEditorSession = activity.listenableEditorSession
assertThat(editorDelegate.userStyle[colorStyleSetting]!!.id.value)
.isEqualTo(redStyleOption.id.value)
assertThat(editorDelegate.userStyle[watchHandStyleSetting]!!.id.value)
.isEqualTo(classicStyleOption.id.value)
// Select [blueStyleOption] and [gothicStyleOption], which are the last options in the
// corresponding setting definitions.
listenableEditorSession.userStyle.value =
listenableEditorSession.userStyle.value.toMutableUserStyle().apply {
listenableEditorSession.userStyleSchema.userStyleSettings.forEach {
this[it] = it.options.last()
}
}.toUserStyle()
// This should cause the style on the to be reverted back to the initial style.
listenableEditorSession.commitChangesOnClose = false
listenableEditorSession.close()
activity.finish()
}
val result = editorObserver.awaitEditorStateChange(
TIMEOUT_MS,
TimeUnit.MILLISECONDS
).asApiEditorState()
assertThat(result.userStyle.userStyleMap[colorStyleSetting.id.value])
.isEqualTo(blueStyleOption.id.value)
assertThat(result.userStyle.userStyleMap[watchHandStyleSetting.id.value])
.isEqualTo(gothicStyleOption.id.value)
Assert.assertFalse(result.shouldCommitChanges)
Assert.assertNull(result.previewImage)
// The original style should be applied to the watch face however because
// commitChangesOnClose is false.
assertThat(editorDelegate.userStyle[colorStyleSetting]!!.id.value)
.isEqualTo(redStyleOption.id.value)
assertThat(editorDelegate.userStyle[watchHandStyleSetting]!!.id.value)
.isEqualTo(classicStyleOption.id.value)
EditorService.globalEditorService.unregisterObserver(observerId)
}
}
| apache-2.0 | 260f9af2ac9ab9f8d01edd4d83bdff57 | 42.440678 | 100 | 0.710183 | 5.540424 | false | true | false | false |
androidx/androidx | room/room-compiler-processing/src/test/java/androidx/room/compiler/processing/ksp/KSTypeExtTest.kt | 3 | 7761 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import androidx.room.compiler.processing.util.Source
import androidx.room.compiler.processing.util.className
import androidx.room.compiler.processing.util.compileFiles
import androidx.room.compiler.processing.util.kspResolver
import androidx.room.compiler.processing.util.runKspTest
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.google.devtools.ksp.getDeclaredProperties
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class KSTypeExtTest {
@Test
fun kotlinTypeName() {
fun createSubject(pkg: String): Source {
return Source.kotlin(
"Foo.kt",
"""
package $pkg
import kotlin.collections.*
class Baz {
val intField : Int = TODO()
val listOfInts : List<Int> = TODO()
val mutableMapOfAny = mutableMapOf<String, Any?>()
val nested:Nested = TODO()
class Nested {
}
}
""".trimIndent()
)
}
val subjectSrc = createSubject(pkg = "main")
val classpath = compileFiles(listOf(createSubject(pkg = "lib")))
runKspTest(sources = listOf(subjectSrc), classpath = classpath) { invocation ->
listOf("main", "lib").map {
it to invocation.kspResolver.requireClass("$it.Baz")
}.forEach { (pkg, subject) ->
assertThat(subject.propertyType("intField").asJTypeName(invocation.kspResolver))
.isEqualTo(TypeName.INT)
assertThat(subject.propertyType("listOfInts").asJTypeName(invocation.kspResolver))
.isEqualTo(
ParameterizedTypeName.get(
List::class.className(),
TypeName.INT.box()
)
)
assertThat(
subject.propertyType("mutableMapOfAny").asJTypeName(invocation.kspResolver)
)
.isEqualTo(
ParameterizedTypeName.get(
Map::class.className(),
String::class.className(),
TypeName.OBJECT,
)
)
val typeName = subject.propertyType("nested").asJTypeName(invocation.kspResolver)
check(typeName is ClassName)
assertThat(typeName.packageName()).isEqualTo(pkg)
assertThat(typeName.simpleNames()).containsExactly("Baz", "Nested")
}
}
}
@Test
fun javaTypeName() {
fun createSubject(pkg: String): Source {
return Source.java(
"$pkg.Baz",
"""
package $pkg;
import java.util.List;
class Baz {
int intField;
List<Integer> listOfInts;
List incompleteGeneric;
Nested nested;
static class Nested {
}
}
""".trimIndent()
)
}
val subjectSrc = createSubject(pkg = "main")
val classpath = compileFiles(listOf(createSubject(pkg = "lib")))
runKspTest(sources = listOf(subjectSrc), classpath = classpath) { invocation ->
listOf("main.Baz", "lib.Baz").map {
invocation.kspResolver.requireClass(it)
}.forEach { subject ->
assertWithMessage(subject.qualifiedName!!.asString())
.that(
subject.propertyType("intField").asJTypeName(invocation.kspResolver)
).isEqualTo(TypeName.INT)
assertWithMessage(subject.qualifiedName!!.asString())
.that(
subject.propertyType("listOfInts").asJTypeName(invocation.kspResolver)
).isEqualTo(
ParameterizedTypeName.get(
List::class.className(),
TypeName.INT.box()
)
)
val propertyType = subject.propertyType("incompleteGeneric")
val typeName = propertyType.asJTypeName(invocation.kspResolver)
assertWithMessage(subject.qualifiedName!!.asString())
.that(
typeName
).isEqualTo(
ClassName.get(List::class.java)
)
val nestedTypeName =
subject.propertyType("nested").asJTypeName(invocation.kspResolver)
assertWithMessage(subject.qualifiedName!!.asString())
.that(nestedTypeName)
.isEqualTo(
ClassName.get(subject.packageName.asString(), "Baz", "Nested")
)
}
}
}
@Test
fun kotlinErrorType() {
val subjectSrc = Source.kotlin(
"Foo.kt",
"""
import kotlin.collections.*
class Foo {
val errorField : DoesNotExist = TODO()
val listOfError : List<DoesNotExist> = TODO()
val mutableMapOfDontExist : MutableMap<String, DoesNotExist> = TODO()
}
""".trimIndent()
)
runKspTest(sources = listOf(subjectSrc)) { invocation ->
val subject = invocation.kspResolver.requireClass("Foo")
assertThat(
subject.propertyType("errorField").asJTypeName(invocation.kspResolver)
).isEqualTo(ERROR_JTYPE_NAME)
assertThat(
subject.propertyType("listOfError").asJTypeName(invocation.kspResolver)
).isEqualTo(
ParameterizedTypeName.get(
List::class.className(),
ERROR_JTYPE_NAME
)
)
assertThat(
subject.propertyType("mutableMapOfDontExist").asJTypeName(invocation.kspResolver)
).isEqualTo(
ParameterizedTypeName.get(
Map::class.className(),
String::class.className(),
ERROR_JTYPE_NAME
)
)
invocation.assertCompilationResult {
compilationDidFail()
}
}
}
private fun KSClassDeclaration.requireProperty(name: String) = getDeclaredProperties().first {
it.simpleName.asString() == name
}
private fun KSClassDeclaration.propertyType(name: String) = checkNotNull(
requireProperty(name).type
)
}
| apache-2.0 | 499baf5e3fe48ec35039ffd2bde76e79 | 38.395939 | 98 | 0.543873 | 5.504255 | false | false | false | false |
gorrotowi/BitsoPriceChecker | app/src/main/java/com/chilangolabs/bitsopricechecker/models/LastTradesResponse.kt | 1 | 850 | package com.chilangolabs.bitsopricechecker.models
import com.google.gson.annotations.SerializedName
data class LastTradesResponse(
@field:SerializedName("payload")
val payload: List<PayloadItem?>? = null,
@field:SerializedName("success")
val success: Boolean? = null
) {
data class PayloadItem(
@field:SerializedName("amount")
val amount: String? = null,
@field:SerializedName("price")
val price: String? = null,
@field:SerializedName("book")
val book: String? = null,
@field:SerializedName("created_at")
val createdAt: String? = null,
@field:SerializedName("maker_side")
val makerSide: String? = null,
@field:SerializedName("tid")
val tid: Int? = null
)
} | apache-2.0 | 0510cb9aa0c7c2dacbca80e75aa1d6ac | 24.787879 | 49 | 0.587059 | 4.67033 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/ContainerInlayPresentation.kt | 12 | 3429 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.codeInsight.hints.InlayPresentationFactory
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.util.ui.GraphicsUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.Color
import java.awt.Graphics2D
import java.awt.Point
import java.awt.event.MouseEvent
/**
* Presentation that wraps existing with borders, background and rounded corners if set.
* @see com.intellij.codeInsight.hints.InlayPresentationFactory.container
*/
@ApiStatus.Experimental
class ContainerInlayPresentation(
presentation: InlayPresentation,
private val padding: InlayPresentationFactory.Padding? = null,
private val roundedCorners: InlayPresentationFactory.RoundedCorners? = null,
private val background: Color? = null,
private val backgroundAlpha: Float = 0.55f
) : StaticDelegatePresentation(presentation) {
private var presentationIsUnderCursor: Boolean = false
override val width: Int
get() = leftInset + presentation.width + rightInset
override val height: Int
get() = topInset + presentation.height + bottomInset
override fun paint(g: Graphics2D, attributes: TextAttributes) {
if (background != null) {
val preservedBackground = g.background
g.color = background
if (roundedCorners != null) {
val (arcWidth, arcHeight) = roundedCorners
fillRoundedRectangle(g, height, width, arcWidth, arcHeight, backgroundAlpha)
} else {
g.fillRect(0, 0, width, height)
}
g.color = preservedBackground
}
g.withTranslated(leftInset, topInset) {
presentation.paint(g, attributes)
}
}
override fun mouseClicked(event: MouseEvent, translated: Point) {
handleMouse(translated) { point ->
presentation.mouseClicked(event, point)
}
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
handleMouse(translated) { point ->
presentation.mouseClicked(event, point)
}
}
override fun mouseExited() {
try {
presentation.mouseExited()
}
finally {
presentationIsUnderCursor = false
}
}
private fun handleMouse(
original: Point,
action: (Point) -> Unit
) {
val x = original.x
val y = original.y
if (!isInInnerBounds(x, y)) {
if (presentationIsUnderCursor) {
presentation.mouseExited()
presentationIsUnderCursor = false
}
return
}
val translated = original.translateNew(-leftInset, -topInset)
action(translated)
}
private fun isInInnerBounds(x: Int, y: Int): Boolean {
return x >= leftInset && x < leftInset + presentation.width && y >= topInset && y < topInset + presentation.height
}
private val leftInset: Int
get() = padding?.left ?: 0
private val rightInset: Int
get() = padding?.right ?: 0
private val topInset: Int
get() = padding?.top ?: 0
private val bottomInset: Int
get() = padding?.bottom ?: 0
private fun fillRoundedRectangle(g: Graphics2D, height: Int, width: Int, arcWidth: Int, arcHeight: Int, backgroundAlpha: Float) {
val config = GraphicsUtil.setupAAPainting(g)
GraphicsUtil.paintWithAlpha(g, backgroundAlpha)
g.fillRoundRect(0, 0, width, height, arcWidth, arcHeight)
config.restore()
}
} | apache-2.0 | f5c7965b0777d78dce3c0d40da42bbd1 | 30.46789 | 140 | 0.70837 | 4.340506 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerComponent.kt | 2 | 14644 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl
import com.intellij.ProjectTopics
import com.intellij.configurationStore.BatchUpdateListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileTypes.FileTypeEvent
import com.intellij.openapi.fileTypes.FileTypeListener
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.project.RootsChangeRescanningInfo
import com.intellij.openapi.roots.*
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.LocalFileSystem.WatchRequest
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.impl.VirtualFilePointerContainerImpl
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.project.stateStore
import com.intellij.util.ObjectUtils
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.indexing.EntityIndexingService
import com.intellij.util.indexing.IndexableFilesIndex
import com.intellij.util.indexing.roots.IndexableFilesIndexImpl
import com.intellij.util.io.systemIndependentPath
import com.intellij.workspaceModel.core.fileIndex.WorkspaceFileIndex
import com.intellij.workspaceModel.core.fileIndex.impl.WorkspaceFileIndexEx
import kotlinx.coroutines.*
import org.jetbrains.annotations.TestOnly
import java.lang.Runnable
import java.util.concurrent.atomic.AtomicReference
private val LOG = logger<ProjectRootManagerComponent>()
private val LOG_CACHES_UPDATE by lazy(LazyThreadSafetyMode.NONE) {
ApplicationManager.getApplication().isInternal && !ApplicationManager.getApplication().isUnitTestMode
}
private val WATCHED_ROOTS_PROVIDER_EP_NAME = ExtensionPointName<WatchedRootsProvider>("com.intellij.roots.watchedRootsProvider")
/**
* ProjectRootManager extended with ability to watch events.
*/
open class ProjectRootManagerComponent(project: Project) : ProjectRootManagerImpl(project), Disposable {
private var isStartupActivityPerformed = false
// accessed in EDT only
private var collectWatchRootsJob = AtomicReference<Job>()
private var pointerChangesDetected = false
private var insideWriteAction = 0
@OptIn(ExperimentalCoroutinesApi::class)
private val sequentialDispatcher = Dispatchers.Default.limitedParallelism(1)
var rootsToWatch: MutableSet<WatchRequest> = CollectionFactory.createSmallMemoryFootprintSet()
private set
// accessed in EDT
private var rootPointersDisposable = Disposer.newDisposable()
private val rootsChangedListener: VirtualFilePointerListener = object : VirtualFilePointerListener {
private fun getPointersChanges(pointers: Array<VirtualFilePointer>): RootsChangeRescanningInfo {
var result: RootsChangeRescanningInfo? = null
for (pointer in pointers) {
if (pointer.isValid) {
return RootsChangeRescanningInfo.TOTAL_RESCAN
}
else {
if (result == null) {
result = RootsChangeRescanningInfo.NO_RESCAN_NEEDED
}
}
}
return ObjectUtils.notNull(result, RootsChangeRescanningInfo.TOTAL_RESCAN)
}
override fun beforeValidityChanged(pointers: Array<VirtualFilePointer>) {
if (myProject.isDisposed) {
return
}
if (!isInsideWriteAction && !pointerChangesDetected) {
pointerChangesDetected = true
//this is the first pointer changing validity
myRootsChanged.levelUp()
}
myRootsChanged.beforeRootsChanged()
if (LOG_CACHES_UPDATE || LOG.isTraceEnabled) {
LOG.trace(Throwable(if (pointers.size > 0) pointers[0].presentableUrl else ""))
}
}
override fun validityChanged(pointers: Array<VirtualFilePointer>) {
val changeInfo = getPointersChanges(pointers)
if (myProject.isDisposed) {
return
}
if (isInsideWriteAction) {
myRootsChanged.rootsChanged(changeInfo)
}
else {
clearScopesCaches()
}
}
private val isInsideWriteAction: Boolean
get() = insideWriteAction == 0
}
init {
if (!myProject.isDefault) {
registerListeners()
}
}
private fun registerListeners() {
val connection = myProject.messageBus.connect(this)
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
@Deprecated("Deprecated in Java")
override fun projectOpened(project: Project) {
if (project === myProject) {
addRootsToWatch()
ApplicationManager.getApplication().addApplicationListener(AppListener(), myProject)
}
}
override fun projectClosed(project: Project) {
if (project === myProject) {
[email protected]()
}
}
})
connection.subscribe(FileTypeManager.TOPIC, object : FileTypeListener {
override fun beforeFileTypesChanged(event: FileTypeEvent) {
myFileTypesChanged.beforeRootsChanged()
}
override fun fileTypesChanged(event: FileTypeEvent) {
myFileTypesChanged.rootsChanged()
}
})
StartupManager.getInstance(myProject).registerStartupActivity { isStartupActivityPerformed = true }
connection.subscribe(BatchUpdateListener.TOPIC, object : BatchUpdateListener {
override fun onBatchUpdateStarted() {
myRootsChanged.levelUp()
myFileTypesChanged.levelUp()
}
override fun onBatchUpdateFinished() {
myRootsChanged.levelDown()
myFileTypesChanged.levelDown()
}
})
val rootsExtensionPointListener = Runnable {
ApplicationManager.getApplication().invokeLater {
ApplicationManager.getApplication().runWriteAction {
makeRootsChange(EmptyRunnable.getInstance(), RootsChangeRescanningInfo.TOTAL_RESCAN)
}
}
}
AdditionalLibraryRootsProvider.EP_NAME.addChangeListener(rootsExtensionPointListener, this)
OrderEnumerationHandler.EP_NAME.addChangeListener(rootsExtensionPointListener, this)
}
protected open fun projectClosed() {
LocalFileSystem.getInstance().removeWatchedRoots(rootsToWatch)
}
@RequiresEdt
private fun addRootsToWatch() {
if (myProject.isDefault) {
return
}
ApplicationManager.getApplication().assertIsWriteThread()
val oldDisposable = rootPointersDisposable
val newDisposable = Disposer.newDisposable()
if (ApplicationManager.getApplication().isUnitTestMode) {
val watchRoots = collectWatchRoots(newDisposable)
postCollect(newDisposable, oldDisposable, watchRoots)
}
else {
myProject.coroutineScope.launch {
val job = launch(start = CoroutineStart.LAZY) {
val watchRoots = readAction { collectWatchRoots(newDisposable) }
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
postCollect(newDisposable, oldDisposable, watchRoots)
}
}
collectWatchRootsJob.getAndSet(job)?.cancelAndJoin()
job.start()
}
}
}
private fun postCollect(newDisposable: Disposable, oldDisposable: Disposable, watchRoots: Pair<Set<String>, Set<String>>) {
rootPointersDisposable = newDisposable
// dispose after the re-creating container to keep VFPs from disposing and re-creating back;
// instead, just increment/decrement their usage count
Disposer.dispose(oldDisposable)
rootsToWatch = LocalFileSystem.getInstance().replaceWatchedRoots(rootsToWatch, watchRoots.first, watchRoots.second)
}
override fun fireBeforeRootsChangeEvent(fileTypes: Boolean) {
isFiringEvent = true
try {
(DirectoryIndex.getInstance(myProject) as? DirectoryIndexImpl)?.reset()
if (IndexableFilesIndex.shouldBeUsed()) {
IndexableFilesIndexImpl.getInstanceImpl(myProject).beforeRootsChanged()
}
(WorkspaceFileIndex.getInstance(myProject) as WorkspaceFileIndexEx).resetCustomContributors()
myProject.messageBus.syncPublisher(ProjectTopics.PROJECT_ROOTS).beforeRootsChange(ModuleRootEventImpl(myProject, fileTypes))
}
finally {
isFiringEvent = false
}
}
override fun fireRootsChangedEvent(fileTypes: Boolean, indexingInfos: List<RootsChangeRescanningInfo>) {
isFiringEvent = true
try {
(DirectoryIndex.getInstance(myProject) as? DirectoryIndexImpl)?.reset()
(WorkspaceFileIndex.getInstance(myProject) as WorkspaceFileIndexEx).resetCustomContributors()
val isFromWorkspaceOnly = EntityIndexingService.getInstance().isFromWorkspaceOnly(indexingInfos)
if (IndexableFilesIndex.shouldBeUsed()) {
IndexableFilesIndexImpl.getInstanceImpl(myProject).afterRootsChanged(fileTypes, indexingInfos, isFromWorkspaceOnly)
}
myProject.messageBus.syncPublisher(ProjectTopics.PROJECT_ROOTS)
.rootsChanged(ModuleRootEventImpl(myProject, fileTypes, indexingInfos, isFromWorkspaceOnly))
}
finally {
isFiringEvent = false
}
if (isStartupActivityPerformed) {
EntityIndexingService.getInstance().indexChanges(myProject, indexingInfos)
}
addRootsToWatch()
}
private fun collectWatchRoots(disposable: Disposable): Pair<Set<String>, Set<String>> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val recursivePathsToWatch = CollectionFactory.createFilePathSet()
val flatPaths = CollectionFactory.createFilePathSet()
val store = myProject.stateStore
val projectFilePath = store.projectFilePath
if (Project.DIRECTORY_STORE_FOLDER != projectFilePath.parent.fileName?.toString()) {
flatPaths.add(projectFilePath.systemIndependentPath)
flatPaths.add(store.workspacePath.systemIndependentPath)
}
for (extension in AdditionalLibraryRootsProvider.EP_NAME.extensionList) {
val toWatch = extension.getRootsToWatch(myProject)
if (!toWatch.isEmpty()) {
for (file in toWatch) {
recursivePathsToWatch.add(file.path)
}
}
}
for (extension in WATCHED_ROOTS_PROVIDER_EP_NAME.extensionList) {
val toWatch = extension.getRootsToWatch(myProject)
if (!toWatch.isEmpty()) {
for (path in toWatch) {
recursivePathsToWatch.add(FileUtilRt.toSystemIndependentName(path))
}
}
}
val excludedUrls = HashSet<String>()
// changes in files provided by this method should be watched manually because no-one's bothered to set up correct pointers for them
for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(myProject)) {
excludedUrls.addAll(excludePolicy.excludeUrlsForProject)
}
// avoid creating empty unnecessary container
if (!excludedUrls.isEmpty()) {
Disposer.register(this, disposable)
// creating a container with these URLs with the sole purpose to get events to getRootsValidityChangedListener() when these roots change
val container = VirtualFilePointerManager.getInstance().createContainer(disposable, rootsValidityChangedListener)
(container as VirtualFilePointerContainerImpl).addAll(excludedUrls)
}
// module roots already fire validity change events, see usages of ProjectRootManagerComponent.getRootsValidityChangedListener
collectModuleWatchRoots(recursivePaths = recursivePathsToWatch, flatPaths = flatPaths)
return Pair(recursivePathsToWatch, flatPaths)
}
private fun collectModuleWatchRoots(recursivePaths: MutableSet<in String>, flatPaths: MutableSet<in String>) {
val urls = CollectionFactory.createFilePathSet()
for (module in ModuleManager.getInstance(myProject).modules) {
val rootManager = ModuleRootManager.getInstance(module)
urls.addAll(rootManager.contentRootUrls)
rootManager.orderEntries().withoutModuleSourceEntries().withoutDepModules().forEach { entry ->
if (entry is LibraryOrSdkOrderEntry) {
for (type in OrderRootType.getAllTypes()) {
urls.addAll(entry.getRootUrls(type))
}
}
true
}
}
for (url in urls) {
val protocol = VirtualFileManager.extractProtocol(url)
when {
protocol == null || StandardFileSystems.FILE_PROTOCOL == protocol -> recursivePaths.add(extractLocalPath(url))
StandardFileSystems.JAR_PROTOCOL == protocol -> flatPaths.add(extractLocalPath(url))
StandardFileSystems.JRT_PROTOCOL == protocol -> recursivePaths.add(extractLocalPath(url))
}
}
}
override fun clearScopesCaches() {
super.clearScopesCaches()
myProject.getServiceIfCreated(LibraryScopeCache::class.java)?.clear()
}
override fun clearScopesCachesForModules() {
super.clearScopesCachesForModules()
for (module in ModuleManager.getInstance(myProject).modules) {
(module as ModuleEx).clearScopesCache()
}
}
override fun markRootsForRefresh() {
val paths = CollectionFactory.createFilePathSet()
collectModuleWatchRoots(paths, paths)
val fs = LocalFileSystem.getInstance()
for (path in paths) {
val root = fs.findFileByPath(path)
if (root is NewVirtualFile) {
root.markDirtyRecursively()
}
}
}
override fun dispose() {}
@TestOnly
fun disposeVirtualFilePointersAfterTest() {
Disposer.dispose(rootPointersDisposable)
}
private inner class AppListener : ApplicationListener {
override fun beforeWriteActionStart(action: Any) {
insideWriteAction++
}
override fun writeActionFinished(action: Any) {
if (--insideWriteAction == 0 && pointerChangesDetected) {
pointerChangesDetected = false
myRootsChanged.levelDown()
}
}
}
override fun getRootsValidityChangedListener(): VirtualFilePointerListener = rootsChangedListener
} | apache-2.0 | 93c459052c5da1495fdb4ef3b6ab8ca3 | 38.474394 | 142 | 0.745903 | 5.006496 | false | false | false | false |
Meisolsson/PocketHub | app/src/main/java/com/github/pockethub/android/ui/item/issue/IssueEventItem.kt | 6 | 4006 | package com.github.pockethub.android.ui.item.issue
import android.content.Context
import android.text.Html
import com.github.pockethub.android.R
import com.github.pockethub.android.ui.view.OcticonTextView
import com.github.pockethub.android.util.AvatarLoader
import com.github.pockethub.android.util.TimeUtils
import com.meisolsson.githubsdk.model.Issue
import com.meisolsson.githubsdk.model.IssueEvent
import com.meisolsson.githubsdk.model.IssueEventType.*
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.comment_event.*
import kotlinx.android.synthetic.main.comment_event.view.*
class IssueEventItem(
private val avatarLoader: AvatarLoader,
private val context: Context,
private val issue: Issue,
val issueEvent: IssueEvent
) : Item(issueEvent.id()!!.toLong()) {
override fun getLayout(): Int = R.layout.comment_event_item
override fun bind(holder: ViewHolder, position: Int) {
var message = String.format(
"<b>%s</b> %s",
issueEvent.actor()!!.login(),
issueEvent.event()
)
avatarLoader.bind(holder.itemView.iv_avatar, issueEvent.actor())
val eventType = issueEvent.event()
when (eventType) {
Assigned, Unassigned -> {
holder.tv_event.text = OcticonTextView.ICON_PERSON
holder.tv_event.setTextColor(context.resources.getColor(R.color.text_description))
}
Labeled, Unlabeled -> {
holder.tv_event.text = OcticonTextView.ICON_TAG
holder.tv_event.setTextColor(context.resources.getColor(R.color.text_description))
}
Referenced -> {
holder.tv_event.text = OcticonTextView.ICON_BOOKMARK
holder.tv_event.setTextColor(context.resources.getColor(R.color.text_description))
}
Milestoned, Demilestoned -> {
holder.tv_event.text = OcticonTextView.ICON_MILESTONE
holder.tv_event.setTextColor(context.resources.getColor(R.color.text_description))
}
Closed -> {
holder.tv_event.text = OcticonTextView.ICON_ISSUE_CLOSE
holder.tv_event.setTextColor(context.resources.getColor(R.color.issue_event_closed))
}
Reopened -> {
holder.tv_event.text = OcticonTextView.ICON_ISSUE_REOPEN
holder.tv_event.setTextColor(
context.resources.getColor(R.color.issue_event_reopened)
)
}
Renamed -> {
holder.tv_event.text = OcticonTextView.ICON_EDIT
holder.tv_event.setTextColor(context.resources.getColor(R.color.text_description))
}
Merged -> {
message += String.format(
" commit <b>%s</b> into <tt>%s</tt> from <tt>%s</tt>",
issueEvent.commitId()!!.substring(0, 6),
issue.pullRequest()!!.base()!!.ref(),
issue.pullRequest()!!.head()!!.ref()
)
holder.tv_event.text = OcticonTextView.ICON_MERGE
holder.tv_event.setTextColor(context.resources.getColor(R.color.issue_event_merged))
}
Locked -> {
holder.tv_event.text = OcticonTextView.ICON_LOCK
holder.tv_event.setTextColor(
context.resources.getColor(R.color.issue_event_lock))
}
Unlocked -> {
holder.tv_event.text = OcticonTextView.ICON_KEY
holder.tv_event.setTextColor(
context.resources.getColor(R.color.issue_event_lock))
}
}
message += " " + TimeUtils.getRelativeTime(issueEvent.createdAt())
holder.tv_event.text = Html.fromHtml(message)
}
}
| apache-2.0 | 2714b65ba5365827f9e9329112967869 | 42.543478 | 100 | 0.602596 | 4.511261 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFix.kt | 4 | 6387 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.*
import org.jetbrains.kotlin.idea.refactoring.CompositeRefactoringRunner
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.refactoring.changeSignature.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.lang.ref.WeakReference
class CreateParameterFromUsageFix<E : KtElement>(
originalExpression: E,
private val dataProvider: (E) -> CreateParameterData<E>?
) : CreateFromUsageFixBase<E>(originalExpression) {
private var parameterInfoReference: WeakReference<KotlinParameterInfo>? = null
private fun parameterInfo(): KotlinParameterInfo? =
parameterInfoReference?.get() ?: parameterData()?.parameterInfo?.also {
parameterInfoReference = WeakReference(it)
}
private val calculatedText: String by lazy {
element?.let { _ ->
parameterInfo()?.run {
if (valOrVar != KotlinValVar.None)
KotlinBundle.message("create.property.0.as.constructor.parameter", name)
else
KotlinBundle.message("create.parameter.0", name)
}
} ?: ""
}
private val calculatedAvailable: Boolean by lazy {
element != null && parameterInfo() != null
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean =
element?.run { calculatedAvailable } ?: false
override fun getText(): String = element?.run { calculatedText } ?: ""
override fun startInWriteAction() = false
private fun runChangeSignature(project: Project, editor: Editor?) {
val originalExpression = element ?: return
val parameterInfo = parameterInfo() ?: return
val config = object : KotlinChangeSignatureConfiguration {
override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor {
return originalDescriptor.modify { it.addParameter(parameterInfo) }
}
override fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean = parameterData()?.createSilently ?: false
}
runChangeSignature(project, editor, parameterInfo.callableDescriptor, config, originalExpression, text)
}
private fun parameterData() = element?.let { dataProvider(it) }
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val onComplete = parameterData()?.onComplete
if (onComplete == null) {
runChangeSignature(project, editor)
} else {
object : CompositeRefactoringRunner(project, "refactoring.changeSignature") {
override fun runRefactoring() {
runChangeSignature(project, editor)
}
override fun onRefactoringDone() {
onComplete(editor)
}
}.run()
}
}
companion object {
fun <E : KtElement> createFixForPrimaryConstructorPropertyParameter(
element: E,
callableInfosFactory: (E) -> List<CallableInfo>?
): CreateParameterFromUsageFix<E> = CreateParameterFromUsageFix(element, dataProvider = fun(element): CreateParameterData<E>? {
val info = callableInfosFactory.invoke(element)?.singleOrNull().safeAs<PropertyInfo>() ?: return null
if (info.receiverTypeInfo.staticContextRequired) return null
val builder = CallableBuilderConfiguration(listOf(info), element).createBuilder()
val receiverTypeCandidate = builder.computeTypeCandidates(info.receiverTypeInfo).firstOrNull()
val receiverClassDescriptor: ClassDescriptor =
if (receiverTypeCandidate != null) {
builder.placement = CallablePlacement.WithReceiver(receiverTypeCandidate)
receiverTypeCandidate.theType.constructor.declarationDescriptor as? ClassDescriptor ?: return null
} else {
if (element !is KtSimpleNameExpression) return null
val classOrObject = element.getStrictParentOfType<KtClassOrObject>() ?: return null
val classDescriptor = classOrObject.resolveToDescriptorIfAny() ?: return null
val paramInfo = CreateParameterByRefActionFactory.extractFixData(element)?.parameterInfo
if (paramInfo?.callableDescriptor == classDescriptor.unsubstitutedPrimaryConstructor) return null
classDescriptor
}
if (receiverClassDescriptor.kind != ClassKind.CLASS) return null
receiverClassDescriptor.source.getPsi().safeAs<KtClass>()?.takeIf { it.canRefactor() } ?: return null
val constructorDescriptor = receiverClassDescriptor.unsubstitutedPrimaryConstructor ?: return null
val paramType = info.returnTypeInfo.getPossibleTypes(builder).firstOrNull()
if (paramType != null && paramType.hasTypeParametersToAdd(constructorDescriptor, builder.currentFileContext)) return null
return CreateParameterData(
parameterInfo = KotlinParameterInfo(
callableDescriptor = constructorDescriptor,
name = info.name,
originalTypeInfo = KotlinTypeInfo(false, paramType),
valOrVar = if (info.writable) KotlinValVar.Var else KotlinValVar.Val
),
originalExpression = element
)
})
}
} | apache-2.0 | 1de41df89a22968d459169f44b939943 | 46.318519 | 158 | 0.683733 | 5.859633 | false | false | false | false |
vovagrechka/fucking-everything | aps/back-php/src/shared-back-php-impl.kt | 1 | 8983 | package aps.back
import aps.*
import phizdetslib.*
typealias XSerializable = PHP_Serializable
typealias XTransient = PHP_Transient
typealias XCrudRepository<T, ID> = PHP_CrudRepository<T, ID>
typealias XGenericGenerator = PHP_GenericGenerator
typealias XTimestamp = PHP_Timestamp
typealias XFetchType = PHP_FetchType
typealias XCascadeType = PHP_CascadeType
typealias XIndex = PHP_Index
typealias XEmbeddable = PHP_Embeddable
typealias XPreUpdate = PHP_PreUpdate
typealias XGenerationType = PHP_GenerationType
typealias XGeneratedValue = PHP_GeneratedValue
typealias XId = PHP_Id
typealias XMappedSuperclass = PHP_MappedSuperclass
typealias XEntity = PHP_Entity
typealias XTable = PHP_Table
typealias XEmbedded = PHP_Embedded
typealias XOneToMany = PHP_OneToMany
typealias XColumn = PHP_Column
typealias XEnumerated = PHP_Enumerated
typealias XEnumType = PHP_EnumType
typealias XManyToOne = PHP_ManyToOne
typealias XJsonIgnoreProperties = PHP_JsonIgnoreProperties
typealias XLogger = PHP_Logger
typealias XDate = PHP_Date
typealias XXmlRootElement = PHP_XmlRootElement
typealias XXmlAccessType = PHP_XmlAccessType
typealias XXmlElement = PHP_XmlElement
typealias XCollections = PHP_Collections
typealias XXmlAccessorType = PHP_XmlAccessorType
typealias XBeanDefinition = PHP_BeanDefinition
typealias XScope = PHP_Scope
typealias XComponent = PHP_Component
typealias XDataSource = PHP_DataSource
typealias XServletException = PHP_ServletException
typealias XHttpServletRequest = PHP_HttpServletRequest
typealias XHttpServletResponse = PHP_HttpServletResponse
typealias XThreadLocal<T> = PHP_ThreadLocal<T>
class PHP_ThreadLocal<T> {
private var value: T? = null
fun set(newValue: T) {
value = newValue
}
}
class PHP_ServletException(cause: Throwable) : Exception(cause.message) {
val fuckingCause = cause
}
class PHP_HttpServletRequest {
var characterEncoding: String
get() = imf("d81d0a76-3609-4ce3-b0ce-a96ee4e19e50")
set(value) {imf("31fbdf22-7d70-4693-bca5-a194d246de72")}
val reader: Reader
get() = imf("3a69f489-d254-4aab-a321-a1a0d39713b8")
interface Reader {
fun readText(): String
}
val pathInfo: String
get() = imf("561c681d-8cfe-44ee-afae-1da09189ef78")
val queryString: String
get() {
"aaaaaaaaaaaaaaaaaaaaa"
return phiEval("return \$_SERVER['QUERY_STRING'];") as String
}
}
class PHP_HttpServletResponse {
companion object {
val SC_OK = 200
}
var contentType: String
get() = imf("3a14d9b1-5118-4f15-8e59-8d0c2a7634d6")
set(value) {imf("78a5c5eb-bf55-4dec-b8c7-af6fb10894f1")}
val writer: Writer
get() = imf("ad50f428-2fe5-4eb4-b676-98b7128bbae3")
interface Writer {
fun println(s: String)
}
var status: Int
get() = imf("93f1db06-5aa5-4609-8d06-7ddebfbb3612")
set(value) {imf("b49d85f3-5745-40e8-89fd-5927f744bb30")}
fun addHeader(name: String, value: String) {
header("$name: $value")
}
}
class PHP_DataSource {
fun close() {
imf("e738c4a5-8529-4d45-8227-f3df72bc5c31")
}
}
annotation class PHP_Scope(val scopeName: String)
annotation class PHP_Component
interface PHP_BeanDefinition {
companion object {
const val SCOPE_PROTOTYPE = "prototype"
}
}
val backPlatform = object : XBackPlatform {
override val log = object : XLogger {
override fun info(s: String) {
phplog.println("[INFO] " + s)
}
override fun error(s: String, e: Throwable) {
phplog.println("[ERROR] " + s)
phplog.println("[ERROR] " + e.message)
}
override fun section(s: String) {
imf("e1456463-02c4-4a7a-8771-42ce63b12fd1")
}
}
override fun makeServant(procedureName: String): BitchyProcedure {
PhiTools.dumpEnvAndDie(PhiTools.currentEnv())
imf("15b54189-8f6f-4077-a3a3-b54b214fd23f")
}
override fun requestTransaction(pathInfo: String, block: () -> Unit) {
imf("24fa286c-d938-4f0f-9b15-ebe66b9290ab")
}
override fun dbTransaction(block: (ShitToDoInTransaction) -> Unit) {
imf("ddc40b4a-2409-4586-b052-9a14168c5c58")
}
override fun makeDataSource(db: DB.Database): XDataSource {
imf("2128b176-c20b-4c91-98c6-150f4b457768")
}
override fun recreateDBSchema() {
imf("59ba047a-305d-48f8-9ed3-2d09991e4347")
}
override fun hashPassword(clearText: String): String {
imf("cd0e3c93-885a-44da-97dd-a27a50524485")
}
override val userRepo: aps.back.UserRepository
get() = imf("4407362e-e680-4428-8895-0610b4387d02")
override val userTokenRepo: UserTokenRepository
get() = imf("26e27a93-3629-4b6a-99ed-e78fcbe34dd7")
override val userParamsHistoryItemRepo: UserParamsHistoryItemRepository
get() = imf("b218bb24-a063-4d73-bfa9-8cf0576e97ef")
override val uaOrderRepo: UAOrderRepository
get() = imf("e61037f8-c86f-4302-b975-2eee2325d6d6")
override val uaOrderFileRepo: UAOrderFileRepository
get() = imf("e5987681-0fd4-462f-bad6-84f09b1bdc8a")
override val uaDocumentCategoryRepo: UADocumentCategoryRepository
get() = imf("6a39f4b8-a677-49bc-8370-de8778e2aba4")
override val userTimesDocumentCategoryRepo: UserTimesDocumentCategoryRepository
get() = imf("8f610afc-3ffc-4fd7-97b3-3e9c30878ecd")
override val userParamsHistoryItemTimesDocumentCategoryRepo: UserParamsHistoryItemTimesDocumentCategoryRepository
get() = imf("0008f7e4-e9ab-41ab-b210-81d0b90bf437")
override val bidRepo: BidRepository
get() = imf("b9b83c63-ac6b-4e21-b88f-1ee972d11501")
override val requestGlobus: RequestGlobusType
get() = imf("a714ef49-e3a7-48f1-8f12-c4efa1e859a6")
override val debugLog: XLogger
get() = imf("d63b32ee-94cf-4777-9e44-2133102acd0a")
override fun getServeObjectRequestFunction(params: Any): (Any) -> Any {
imf("812eea57-ef5a-4694-8707-a430d0533526")
}
override fun captureStackTrace(): Array<out XStackTraceElement> {
imf("6635c61c-85e1-49b6-8bcf-43250dcfa763")
}
override fun isRequestThread(): Boolean {
imf("b2b115c7-8e0c-4606-aeaa-5776eb44fea2")
}
override fun getResourceAsText(path: String): String {
imf("d1071b3f-2012-45d8-9e52-baa8d3a0e533")
}
override fun highlightRanges(text: String, searchWords: List<String>): List<IntRangeRTO> {
imf("dec07828-b259-46c9-8192-2374ff069057")
}
override val hackyObjectMapper: XHackyObjectMapper
get() = imf("70245e8a-3883-4d5c-b148-5dcbdfc6850b")
override val shittyObjectMapper: XShittyObjectMapper
get() = imf("cfed105b-5fb9-4e50-a570-65d4a325eb1c")
}
annotation class PHP_XmlRootElement(val name: String = "##default")
annotation class PHP_XmlElement(val name: String = "##default")
annotation class PHP_XmlAccessorType(val value: XXmlAccessType)
enum class PHP_XmlAccessType {
FIELD
}
object PHP_Collections {
fun <T> synchronizedList(list: MutableList<T>): MutableList<T> {
return list
}
}
class PHP_Date {
}
interface PHP_Logger {
fun info(s: String)
fun error(s: String, e: Throwable)
fun section(s: String)
}
interface PHP_Serializable
annotation class PHP_JsonIgnoreProperties(val ignoreUnknown: Boolean)
annotation class PHP_Transient
interface PHP_SharedSessionContractImplementor {
}
class PHP_Timestamp(val time: Long) {
}
enum class PHP_FetchType {
LAZY, EAGER
}
enum class PHP_CascadeType {
ALL
}
annotation class PHP_Index(val columnList: String)
annotation class PHP_Embeddable
annotation class PHP_PreUpdate
enum class PHP_GenerationType {
IDENTITY
}
annotation class PHP_GeneratedValue(
val strategy: XGenerationType,
val generator: String
)
annotation class PHP_Id
annotation class PHP_MappedSuperclass
annotation class PHP_Entity
annotation class PHP_Table(val name: String, val indexes: Array<XIndex>)
annotation class PHP_Embedded
annotation class PHP_OneToMany(
val fetch: XFetchType,
val mappedBy: String,
val cascade: Array<XCascadeType> = arrayOf(),
val orphanRemoval: Boolean = false
)
annotation class PHP_Column(val length: Int = 255, val columnDefinition: String = "")
annotation class PHP_Enumerated(val type: XEnumType)
enum class PHP_EnumType {
STRING
}
annotation class PHP_ManyToOne(val fetch: XFetchType)
interface PHP_CrudRepository<T, ID> {
fun <S : T> save(entity: S): S
fun <S : T> save(entities: Iterable<S>): Iterable<S>
fun findOne(id: ID): T?
fun exists(id: ID): Boolean
fun findAll(): Iterable<T>
fun findAll(ids: Iterable<ID>): Iterable<T>
fun count(): Long
fun delete(id: ID)
fun delete(entity: T)
fun delete(entities: Iterable<T>)
fun deleteAll()
}
annotation class PHP_GenericGenerator(
val name: String,
val strategy: String
)
| apache-2.0 | 22a8e2224953c37eb22f371f90c18746 | 27.071875 | 117 | 0.710342 | 3.327037 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/impl/libraries/LibraryKindRegistryImpl.kt | 3 | 2871 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl.libraries
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.impl.OrderEntryUtil
import com.intellij.openapi.roots.libraries.*
internal class LibraryKindRegistryImpl private constructor() : LibraryKindRegistry() {
init {
//todo[nik] this is temporary workaround for IDEA-98118: we need to initialize all library types to ensure that their kinds are created and registered in LibraryKind.ourAllKinds
//In order to properly fix the problem we should extract all UI-related methods from LibraryType to a separate class and move LibraryType to intellij.platform.projectModel.impl module
LibraryType.EP_NAME.extensionList
LibraryType.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<LibraryType<*>> {
override fun extensionAdded(extension: LibraryType<*>, pluginDescriptor: PluginDescriptor) {
WriteAction.run<RuntimeException> {
LibraryKind.registerKind(extension.kind)
processAllLibraries { rememberKind(extension.kind, it) }
}
}
override fun extensionRemoved(extension: LibraryType<*>, pluginDescriptor: PluginDescriptor) {
LibraryKind.unregisterKind(extension.kind)
processAllLibraries { forgetKind(extension.kind, it) }
}
}, null)
}
private fun processAllLibraries(processor: (Library) -> Unit) {
LibraryTablesRegistrar.getInstance().libraryTable.libraries.forEach(processor)
for (table in LibraryTablesRegistrar.getInstance().customLibraryTables) {
table.libraries.forEach(processor)
}
for (project in ProjectManager.getInstance().openProjects) {
LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.forEach(processor)
for (module in ModuleManager.getInstance(project).modules) {
for (library in OrderEntryUtil.getModuleLibraries(ModuleRootManager.getInstance(module))) {
processor(library)
}
}
}
}
private fun forgetKind(kind: PersistentLibraryKind<*>, library: Library) {
if (kind == (library as LibraryEx).kind) {
val model = library.modifiableModel
model.forgetKind()
model.commit()
}
}
private fun rememberKind(kind: PersistentLibraryKind<*>, library: Library) {
if (((library as LibraryEx).kind as? UnknownLibraryKind)?.kindId == kind.kindId) {
val model = library.modifiableModel
model.restoreKind()
model.commit()
}
}
} | apache-2.0 | 78a7028d5e231b6cf7889bb2876035a3 | 43.875 | 187 | 0.749565 | 4.93299 | false | false | false | false |
mapzen/eraser-map | app/src/test/kotlin/com/mapzen/erasermap/model/IntentQueryParserTest.kt | 1 | 1903 | package com.mapzen.erasermap.model
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class IntentQueryParserTest {
companion object {
val TEST_QUERY = "q=350 5th Ave, New York, NY 10118"
val TEST_QUERY_WITH_LATLNG = "q=350 5th Ave, New York, NY 10118&sll=40.7484,-73.9857"
val TEST_QUERY_WITH_LATLNG_AND_RADIUS = "q=350 5th Ave, New York, NY 10118&sll=40.7484,-73.9857&radius=5"
val TEST_QUERY_DOUBLE_ENCODED = "q=Pier+97"
val MALFORMED_QUERY = "wtf=what a terrible failure"
}
val intentQueryParser = IntentQueryParser()
@Test fun shouldNotBeNull() {
assertThat(intentQueryParser).isNotNull()
}
@Test fun parse_shouldParseQueryString() {
assertThat(intentQueryParser.parse(TEST_QUERY)?.queryString)
.isEqualTo("350 5th Ave, New York, NY 10118")
}
@Test fun parse_shouldParseQueryStringWithFocusPoint() {
assertThat(intentQueryParser.parse(TEST_QUERY_WITH_LATLNG)?.queryString)
.isEqualTo("350 5th Ave, New York, NY 10118")
}
@Test fun parse_shouldParseQueryStringWithFocusPointAndRadius() {
assertThat(intentQueryParser.parse(TEST_QUERY_WITH_LATLNG_AND_RADIUS)?.queryString)
.isEqualTo("350 5th Ave, New York, NY 10118")
}
@Test fun parse_shouldReturnNullForMalformedQuery() {
assertThat(intentQueryParser.parse(MALFORMED_QUERY)).isNull()
}
@Test fun parse_shouldParseFocusPoint() {
val focusPoint = intentQueryParser.parse(TEST_QUERY_WITH_LATLNG)?.focusPoint
assertThat(focusPoint?.latitude).isEqualTo(40.7484)
assertThat(focusPoint?.longitude).isEqualTo(-73.9857)
}
@Test fun parse_shouldHandleDoubleEncodedQueryString() {
assertThat(intentQueryParser.parse(TEST_QUERY_DOUBLE_ENCODED)?.queryString)
.isEqualTo("Pier 97")
}
}
| gpl-3.0 | 5f95b34210c0104c209f8d239c888c3b | 37.06 | 113 | 0.684183 | 3.666667 | false | true | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/serialization/xml/XmlExt.kt | 2 | 670 | package com.jtransc.serialization.xml
import com.jtransc.vfs.SyncVfsFile
import org.intellij.lang.annotations.Language
fun Iterable<Xml>.str(name: String, defaultValue: String = ""): String = this.first().attributes[name] ?: defaultValue
fun Iterable<Xml>.children(name: String): Iterable<Xml> = this.flatMap { it.children(name) }
val Iterable<Xml>.allChildren: Iterable<Xml> get() = this.flatMap(Xml::allChildren)
operator fun Iterable<Xml>.get(name: String): Iterable<Xml> = this.children(name)
fun String.toXml(): Xml = Xml.parse(this)
fun Xml(@Language("xml") str: String): Xml = Xml.parse(str)
/*suspend*/ fun SyncVfsFile.readXml(): Xml = Xml(this.readString()) | apache-2.0 | 3398085a0433716a19178290770f067f | 46.928571 | 118 | 0.746269 | 3.544974 | false | false | false | false |
Bambooin/trime | app/src/main/java/com/osfans/trime/settings/components/DialogSeekBarPreference.kt | 1 | 6268 | package com.osfans.trime.settings.components
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.SeekBar
import androidx.appcompat.app.AlertDialog
import androidx.preference.Preference
import androidx.preference.PreferenceManager
import com.osfans.trime.R
import com.osfans.trime.databinding.SeekBarDialogBinding
/**
* Custom preference which represents a seek bar which shows the current value in the summary. The
* value can be changed by clicking on the preference, which brings up a dialog which a seek bar.
* This implementation also allows for a min / max step value, while being backwards compatible.
*
* @see R.styleable.DialogSeekBarPreferenceAttrs for which xml attributes this preference accepts
* besides the default Preference attributes.
*
* @property defaultValue The default value of this preference.
* @property min The minimum value of the seek bar. Must not be greater or equal than [max].
* @property max The maximum value of the seek bar. Must not be lesser or equal than [min].
* @property step The step in which the seek bar increases per move. If the provided value is less
* than 1, 1 will be used as step. Note that the xml attribute's name for this property is
* [R.styleable.DialogSeekBarPreferenceAttrs_seekBarIncrement].
* @property unit The unit to show after the value. Set to an empty string to disable this feature.
*/
class DialogSeekBarPreference : Preference {
private var defaultValue: Int = 0
private var systemDefaultValue: Int = -1
private var systemDefaultValueText: String? = null
private var min: Int = 0
private var max: Int = 100
private var step: Int = 1
private var unit: String = ""
private val currentValue: Int
get() = sharedPreferences.getInt(key, defaultValue)
@Suppress("unused")
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, R.attr.preferenceStyle)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
context.obtainStyledAttributes(attrs, R.styleable.DialogSeekBarPreferenceAttrs).apply {
min = getInt(R.styleable.DialogSeekBarPreferenceAttrs_min, min)
max = getInt(R.styleable.DialogSeekBarPreferenceAttrs_max, max)
step = getInt(R.styleable.DialogSeekBarPreferenceAttrs_seekBarIncrement, step)
if (step < 1) {
step = 1
}
defaultValue = getInt(R.styleable.DialogSeekBarPreferenceAttrs_android_defaultValue, defaultValue)
systemDefaultValue = getInt(R.styleable.DialogSeekBarPreferenceAttrs_systemDefaultValue, min - 1)
systemDefaultValueText = getString(R.styleable.DialogSeekBarPreferenceAttrs_systemDefaultValueText)
unit = getString(R.styleable.DialogSeekBarPreferenceAttrs_unit) ?: unit
recycle()
}
}
override fun onClick() {
showSeekBarDialog()
}
override fun onAttachedToHierarchy(preferenceManager: PreferenceManager?) {
super.onAttachedToHierarchy(preferenceManager)
summary = getTextForValue(currentValue)
}
/**
* Generates the text for the given [value] and adds the defined [unit] at the end.
* If [systemDefaultValueText] is not null this method tries to match the given [value] with
* [systemDefaultValue] and returns [systemDefaultValueText] upon matching.
*/
private fun getTextForValue(value: Int): String {
val systemDefValText = systemDefaultValueText
return if (value == systemDefaultValue && systemDefValText != null) {
systemDefValText
} else {
value.toString() + unit
}
}
/**
* Shows the seek bar dialog.
*/
private fun showSeekBarDialog() {
val dialogView = SeekBarDialogBinding.inflate(LayoutInflater.from(context))
val initValue = currentValue
dialogView.seekBar.max = actualValueToSeekBarProgress(max)
dialogView.seekBar.progress = actualValueToSeekBarProgress(initValue)
dialogView.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
dialogView.value.text = getTextForValue(seekBarProgressToActualValue(progress))
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
dialogView.value.text = getTextForValue(initValue)
AlertDialog.Builder(context).apply {
setTitle([email protected])
setCancelable(true)
setView(dialogView.root)
setPositiveButton(android.R.string.ok) { _, _ ->
val actualValue = seekBarProgressToActualValue(dialogView.seekBar.progress)
if (callChangeListener(actualValue)) {
sharedPreferences.edit().putInt(key, actualValue).apply()
summary = getTextForValue(currentValue)
}
}
setNeutralButton(R.string.pref__default) { _, _ ->
sharedPreferences.edit().putInt(key, defaultValue).apply()
summary = getTextForValue(currentValue)
}
setNegativeButton(android.R.string.cancel, null)
}.show()
}
/**
* Converts the actual value to a progress value which the Android SeekBar implementation can
* handle. (Android's SeekBar step is fixed at 1 and min at 0)
*
* @param actual The actual value.
* @return the internal value which is used to allow different min and step values.
*/
private fun actualValueToSeekBarProgress(actual: Int): Int {
return (actual - min) / step
}
/**
* Converts the Android SeekBar value to the actual value.
*
* @param progress The progress value of the SeekBar.
* @return the actual value which is ready to use.
*/
private fun seekBarProgressToActualValue(progress: Int): Int {
return (progress * step) + min
}
}
| gpl-3.0 | 949d5674c7e0026d09dc39900495930e | 44.42029 | 114 | 0.690491 | 4.889236 | false | false | false | false |
square/sqldelight | sample/android/src/main/java/com/example/sqldelight/hockey/ui/PlayersActivity.kt | 1 | 1537 | package com.example.sqldelight.hockey.ui
import android.app.Activity
import android.os.Bundle
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.sqldelight.hockey.R
import com.example.sqldelight.hockey.data.Db
import com.example.sqldelight.hockey.data.ForTeam
import com.example.sqldelight.hockey.data.getInstance
import com.example.sqldelight.hockey.ui.PlayersActivity.PlayersAdapter.ViewHolder
class PlayersActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.list)
val db = Db.getInstance(this).playerQueries
val players = findViewById<RecyclerView>(R.id.list)
players.layoutManager = LinearLayoutManager(this)
players.adapter = PlayersAdapter(db.forTeam(intent.getLongExtra(TEAM_ID, -1)).executeAsList())
}
private inner class PlayersAdapter(
private val data: List<ForTeam>
) : RecyclerView.Adapter<ViewHolder>() {
override fun getItemCount() = data.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(layoutInflater.inflate(R.layout.player_row, parent, false) as PlayerRow)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.row.populate(data[position])
}
inner class ViewHolder(val row: PlayerRow) : RecyclerView.ViewHolder(row)
}
companion object {
val TEAM_ID = "team_id"
}
}
| apache-2.0 | 48e0af1e8b57d879cd039ff4150471a3 | 33.931818 | 98 | 0.770982 | 4.269444 | false | false | false | false |
JimSeker/saveData | SupportPrefenceDemo_kt/app/src/main/java/edu/cs4730/supportprefencedemo_kt/PreferenceupdateFragment.kt | 1 | 3844 | package edu.cs4730.supportprefencedemo_kt
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.os.Bundle
import android.content.SharedPreferences
import android.util.Log
import androidx.preference.*
/**
* The support version of the preference fragment.
*/
class PreferenceupdateFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener {
private lateinit var mEditTextPreference: EditTextPreference
private lateinit var mListPreference: ListPreference
private lateinit var mMultiSelectListPreference: MultiSelectListPreference
private lateinit var mDropDownPreference: DropDownPreference
private val TAG = "PreferenceupdateFragment"
override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
//NOTE the rest of this code in not necessary, used so you can display current value on the summary line.
// Get a reference to the preferences, so we can dynamically update the preference screen summary info.
mEditTextPreference = preferenceScreen.findPreference("edittext_preference")!!
mListPreference = preferenceScreen.findPreference("list_preference")!!
mMultiSelectListPreference = preferenceManager.findPreference("multiselect_key")!!
mDropDownPreference = preferenceManager.findPreference("dropdown")!!
}
override fun onResume() {
super.onResume()
// Setup the initial values
mEditTextPreference.summary = "Text is " + mEditTextPreference.sharedPreferences!!
.getString("edittext_preference", "Default")
mListPreference.summary = "Current value is " + mListPreference.sharedPreferences!!
.getString("list_preference", "Default")
// multiselect returns a array set, not a string, so create one.
var list = ""
val selections = mMultiSelectListPreference.sharedPreferences!!
.getStringSet("multiselect_key", null)
for (s in selections!!) {
Log.wtf(TAG, "value is $s")
list += "$s "
}
mMultiSelectListPreference.summary = "selection is $list"
mDropDownPreference.summary =
"Current value is " + mDropDownPreference.sharedPreferences!!
.getString("dropdown", "Default")
// Set up a listener whenever a key changes
preferenceScreen.sharedPreferences!!.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
// Unregister the listener whenever a key changes
preferenceScreen.sharedPreferences!!.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == "edittext_preference") { //where textPref is the key used in the xml.
mEditTextPreference.summary =
"Text is " + sharedPreferences.getString("edittext_preference", "Default")
} else if (key == "list_preference") {
mListPreference.summary =
"Current value is " + sharedPreferences.getString(key, "Default")
} else if (key == "multiselect_key") {
var list = ""
val selections = mMultiSelectListPreference.sharedPreferences!!
.getStringSet("multiselect_key", null)
for (s in selections!!) {
//Log.wtf(TAG, "value is " + s);
list += "$s "
}
mMultiSelectListPreference.summary = "selection is $list"
} else if (key == "dropdown") {
mDropDownPreference.summary =
"Current value is " + mDropDownPreference.sharedPreferences!!
.getString("dropdown", "Default")
}
}
} | apache-2.0 | 40fb6c0098b52289f949411fcf0b5ced | 44.235294 | 113 | 0.673777 | 5.530935 | false | false | false | false |
STMicroelectronics-CentralLabs/BlueSTSDK_Android | BlueSTSDK/src/main/java/com/st/BlueSTSDK/Features/highSpeedDataLog/communication/DeviceModel/SensorStatus.kt | 1 | 982 | package com.st.BlueSTSDK.Features.highSpeedDataLog.communication.DeviceModel
import com.google.gson.annotations.SerializedName
data class SensorStatus (
//NOTE here there may be parameters in the future
@SerializedName("subSensorStatus") var subSensorStatusList : List<SubSensorStatus>,
var paramsLocked: Boolean = false
)
{
fun getSubSensorStatus(subSensorId: Int): SubSensorStatus? {
return subSensorStatusList.getOrNull(subSensorId)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SensorStatus
if (subSensorStatusList != other.subSensorStatusList) return false
if (paramsLocked != other.paramsLocked) return false
return true
}
override fun hashCode(): Int {
var result = subSensorStatusList.hashCode()
result = 31 * result + paramsLocked.hashCode()
return result
}
}
| bsd-3-clause | 58d02f49e0b20e70370078a7804a4aba | 28.757576 | 87 | 0.697556 | 4.610329 | false | false | false | false |
Wyvarn/chatbot | app/src/main/kotlin/com/chatbot/ui/base/BaseActivity.kt | 1 | 2328 | package com.chatbot.ui.base
import android.annotation.TargetApi
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.inputmethod.InputMethodManager
import com.chatbot.app.ChatBotApp
import com.chatbot.di.components.ActivityComponent
import com.chatbot.di.components.DaggerActivityComponent
import com.chatbot.di.modules.ActivityModule
/**
* @author lusinabrian on 10/06/17.
* *
* @Notes
*/
abstract class BaseActivity : AppCompatActivity(), BaseView, BaseFragment.Callback {
// fields
lateinit var activityComponent: ActivityComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityComponent = DaggerActivityComponent.builder()
.activityModule(ActivityModule(this))
.appComponent((application as ChatBotApp).appComponent)
.build()
}
@TargetApi(Build.VERSION_CODES.M)
fun requestPermissionsSafely(permissions: Array<String>, requestCode: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode)
}
}
@TargetApi(Build.VERSION_CODES.M)
fun hasPermission(permission: String): Boolean {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
/**
* before destroying the view, do a sanity check of the view bindings before destroying the
* activity */
public override fun onDestroy() {
super.onDestroy()
}
/**
* Hides keyboard
*/
override fun hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
/**
* Callback for when a fragment is attached to an activity
*/
override fun onFragmentAttached() {
}
/**
* Callback for when a fragment is detached from an activity
* @param tag the fragment tag to detach
*/
override fun onFragmentDetached(tag: String) {
}
}
| mit | 12ad44f9ec6a949f736ab356878f6107 | 28.1 | 132 | 0.69201 | 4.780287 | false | false | false | false |
tingtingths/jukebot | app/src/main/java/com/jukebot/jukebot/command/PlaylistCommandHandler.kt | 1 | 908 | package com.jukebot.jukebot.command
import com.jukebot.jukebot.manager.MessageManager
import com.jukebot.jukebot.pojo.Command
import com.jukebot.jukebot.util.Util
import com.pengrad.telegrambot.model.Message
import com.pengrad.telegrambot.request.SendMessage
/**
* Created by Ting.
*/
object PlaylistCommandHandler : CommandHandler() {
override var nextInLine: CommandHandler? = null
override fun cmd(): String = "/playlist"
override fun handle(command: Command, msg: Message) {
if (command.cmd.equals(cmd())) {
val reply = Util.buildPlaylistMessage()
MessageManager.enqueue(Pair(
SendMessage(msg.chat().id(), if (reply == "") "No track" else reply)
.replyToMessageId(msg.messageId())
, null)
)
} else {
nextInLine?.handle(command, msg)
}
}
}
| mit | adf4bd6248d927b2f37a2da130aa7921 | 27.375 | 88 | 0.627753 | 4.407767 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileSetPasswordCommand.kt | 1 | 2798 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.command.profile
import com.rpkit.core.command.RPKCommandExecutor
import com.rpkit.core.command.result.CommandResult
import com.rpkit.core.command.result.CommandSuccess
import com.rpkit.core.command.result.IncorrectUsageFailure
import com.rpkit.core.command.result.MissingServiceFailure
import com.rpkit.core.command.sender.RPKCommandSender
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.command.result.NoProfileSelfFailure
import com.rpkit.players.bukkit.command.result.NotAPlayerFailure
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import java.util.concurrent.CompletableFuture
class ProfileSetPasswordCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor {
override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<CommandResult> {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages.profileSetPasswordUsage)
return CompletableFuture.completedFuture(IncorrectUsageFailure())
}
if (sender !is RPKMinecraftProfile) {
sender.sendMessage(plugin.messages.notFromConsole)
return CompletableFuture.completedFuture(NotAPlayerFailure())
}
val profile = sender.profile
if (profile !is RPKProfile) {
sender.sendMessage(plugin.messages.noProfileSelf)
return CompletableFuture.completedFuture(NoProfileSelfFailure())
}
val password = args.joinToString(" ")
val profileService = Services[RPKProfileService::class.java]
if (profileService == null) {
sender.sendMessage(plugin.messages.noProfileService)
return CompletableFuture.completedFuture(MissingServiceFailure(RPKProfileService::class.java))
}
profile.setPassword(password.toCharArray())
return profileService.updateProfile(profile).thenApply {
sender.sendMessage(plugin.messages.profileSetPasswordValid)
CommandSuccess
}
}
} | apache-2.0 | 550dd34338d12063f430c0e555db2902 | 44.885246 | 113 | 0.753753 | 4.83247 | false | false | false | false |
mizukami2005/StockQiita | app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/view/activity/ListTagActivity.kt | 1 | 4868 | package com.mizukami2005.mizukamitakamasa.qiitaclient.view.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.MenuItem
import android.widget.AbsListView
import com.joanzapata.iconify.IconDrawable
import com.joanzapata.iconify.fonts.MaterialIcons
import com.mizukami2005.mizukamitakamasa.qiitaclient.QiitaClientApp
import com.mizukami2005.mizukamitakamasa.qiitaclient.R
import com.mizukami2005.mizukamitakamasa.qiitaclient.client.ArticleClient
import com.mizukami2005.mizukamitakamasa.qiitaclient.model.ArticleTag
import com.mizukami2005.mizukamitakamasa.qiitaclient.toast
import com.mizukami2005.mizukamitakamasa.qiitaclient.util.TagUtils
import com.mizukami2005.mizukamitakamasa.qiitaclient.view.adapter.ArticleTagListAdapter
import kotlinx.android.synthetic.main.activity_list_tag.*
import kotlinx.android.synthetic.main.view_article_tag.*
import kotlinx.android.synthetic.main.view_article_tag.view.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*
import javax.inject.Inject
class ListTagActivity : AppCompatActivity() {
@Inject
lateinit var articleClient: ArticleClient
val listAdapter: ArticleTagListAdapter by lazy {
ArticleTagListAdapter(applicationContext)
}
var count = 1
var isLoading = true
val checkTagList: MutableSet<String> = mutableSetOf()
companion object {
private var TAG_EXTRA: ArrayList<String> = arrayListOf()
fun intent(context: Context, tags: ArrayList<String>): Intent =
Intent(context, ListTagActivity::class.java)
.putStringArrayListExtra("${TAG_EXTRA}", tags)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as QiitaClientApp).component.inject(this)
setContentView(R.layout.activity_list_tag)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val saveTagLists = TagUtils().loadName(applicationContext, "TAG")
for (tag in saveTagLists) {
checkTagList += tag
}
getTags(articleClient.tags("$count"))
list_view.adapter = listAdapter
list_view.setOnItemClickListener { adapterView, view, position, id ->
val articleTag = listAdapter.articleTags[position]
if (view.tag_check_box.isChecked) {
view.tag_check_box.isChecked = false
checkTagList -= articleTag.id
} else {
view.tag_check_box.isChecked = true
checkTagList += articleTag.id
}
TagUtils().saveName(applicationContext, "TAG", checkTagList)
}
home_button.setImageDrawable(IconDrawable(this, MaterialIcons.md_home).colorRes(R.color.fab_background))
home_button.setOnClickListener {
val intent = intent
setResult(Activity.RESULT_OK, intent)
finish()
}
list_view.setOnScrollListener(object : AbsListView.OnScrollListener {
override fun onScroll(absListView: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
if (totalItemCount != 0 && totalItemCount == firstVisibleItem + visibleItemCount && isLoading && count <= 4) {
isLoading = false
count++
getAddTagItems(articleClient.tags("$count"))
}
}
override fun onScrollStateChanged(p0: AbsListView?, p1: Int) {
}
})
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
val intent = intent
setResult(Activity.RESULT_OK, intent)
finish()
}
}
return super.onOptionsItemSelected(item)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
val intent = intent
setResult(Activity.RESULT_OK, intent)
finish()
return true
}
return false
}
private fun getTags(observable: Observable<Array<ArticleTag>>) {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
listAdapter.articleTags = it
listAdapter.notifyDataSetChanged()
}, {
toast(getString(R.string.error_message))
})
}
private fun getAddTagItems(observable: Observable<Array<ArticleTag>>) {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
isLoading = true
}
.subscribe({
listAdapter.addList(it)
listAdapter.notifyDataSetChanged()
var position = list_view.firstVisiblePosition
var yOffset = list_view.getChildAt(0).top
list_view.setSelectionFromTop(position, yOffset)
}, {
toast(getString(R.string.error_message))
})
}
}
| mit | b57a2d7e5ec50470ba1b4ee2ed8cceb3 | 31.238411 | 123 | 0.725349 | 4.307965 | false | false | false | false |
pratikbutani/AppIntro | appintro/src/main/java/com/github/paolorotolo/appintro/AppIntroFragment.kt | 2 | 2984 | package com.github.paolorotolo.appintro
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.FontRes
import com.github.paolorotolo.appintro.model.SliderPage
@Suppress("LongParameterList")
class AppIntroFragment : AppIntroBaseFragment() {
override val layoutId: Int get() = R.layout.appintro_fragment_intro
companion object {
/**
* Generates a new instance for [AppIntroFragment]
*
* @param title CharSequence which will be the slide title
* @param description CharSequence which will be the slide description
* @param titleTypefaceFontRes @FontRes (Integer) custom title typeface obtained
* from Resources
* @param descTypefaceFontRes @FontRes (Integer) custom description typeface obtained
* from Resources
* @param imageDrawable @DrawableRes (Integer) the image that will be
* displayed, obtained from Resources
* @param bgDrawable @DrawableRes (Integer) custom background drawable
* @param bgColor @ColorInt (Integer) custom background color
* @param titleColor @ColorInt (Integer) custom title color
* @param descColor @ColorInt (Integer) custom description color
*
* @return An [AppIntroFragment] created instance
*/
@JvmOverloads
@JvmStatic
fun newInstance(
title: CharSequence? = null,
description: CharSequence? = null,
@FontRes titleTypefaceFontRes: Int = 0,
@FontRes descTypefaceFontRes: Int = 0,
@DrawableRes imageDrawable: Int = 0,
@ColorInt bgColor: Int = 0,
@DrawableRes bgDrawable: Int = 0,
@ColorInt titleColor: Int = 0,
@ColorInt descColor: Int = 0
): AppIntroFragment {
return newInstance(
SliderPage(
title = title,
description = description,
imageDrawable = imageDrawable,
bgColor = bgColor,
bgDrawable = bgDrawable,
titleColor = titleColor,
descColor = descColor,
titleTypefaceFontRes = titleTypefaceFontRes,
descTypefaceFontRes = descTypefaceFontRes
)
)
}
/**
* Generates an [AppIntroFragment] from a given [SliderPage]
*
* @param sliderPage the [SliderPage] object which contains all attributes for
* the current slide
*
* @return An [AppIntroFragment] created instance
*/
@JvmStatic
fun newInstance(sliderPage: SliderPage): AppIntroFragment {
val slide = AppIntroFragment()
slide.arguments = sliderPage.toBundle()
return slide
}
}
}
| apache-2.0 | 19c7b6ebde3eed626df4122e9ba5c859 | 38.263158 | 93 | 0.585791 | 5.45521 | false | false | false | false |
droibit/quickly | app/src/main/kotlin/com/droibit/quickly/packages/receiver/PackageActionReceiver.kt | 1 | 1837 | package com.droibit.quickly.packages.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.Intent.*
import com.droibit.quickly.packages.service.PackageActionService
import com.droibit.quickly.packages.PackageContract
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.KodeinInjector
import com.github.salomonbrys.kodein.instance
class PackageActionReceiver : BroadcastReceiver(), PackageContract.Receiver {
private val injector = KodeinInjector()
private val actionHandler: PackageContract.ActionHandler by injector.instance()
private val context: Context by injector.instance()
override fun onReceive(context: Context, intent: Intent) {
injector.inject(Kodein {
import(packageModule(context, receiver = this@PackageActionReceiver))
})
when (intent.action) {
ACTION_PACKAGE_ADDED -> {
actionHandler.onPackageAdded(intent.packageName)
}
ACTION_PACKAGE_REPLACED -> {
actionHandler.onPackageReplaced(intent.packageName)
}
ACTION_PACKAGE_REMOVED -> {
actionHandler.onPackageRemoved(intent.packageName,
replacing = intent.getBooleanExtra(EXTRA_REPLACING, false))
}
// ACTION_MY_PACKAGE_REPLACED -> {
// actionHandler.onPackageReplaced(packageName = BuildConfig.APPLICATION_ID)
// }
}
}
override fun startPackageAction(action: PackageContract.Action, packageName: String) {
val intent = PackageActionService.newIntent(context, action, packageName)
context.startService(intent)
}
}
private val Intent.packageName: String
get() = data.schemeSpecificPart | apache-2.0 | f8411f7b24d0662d0ba4332f800d2c38 | 35.76 | 91 | 0.69951 | 4.885638 | false | false | false | false |
lijunzz/LongChuanGang | app/src/main/kotlin/net/junzz/app/lcg/MainActivity.kt | 1 | 2822 | package net.junzz.app.lcg
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import net.junzz.app.util.ColorUtils
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewpager = ViewPager(this)
setContentView(viewpager)
val favoriteView = initFavoritePage()
val listView = initListPage()
val views = listOf(favoriteView, listView)
viewpager.adapter = MainAdapter(views)
viewpager.currentItem = 1
}
/** 收藏夹 */
private fun initFavoritePage(): View {
val emptyView = TextView(this)
emptyView.text = "空"
emptyView.textSize = 32f
emptyView.gravity = Gravity.CENTER
emptyView.typeface = Typeface.DEFAULT_BOLD
emptyView.setTextColor(Color.parseColor("#A9B7C6"))
return emptyView
}
/** 列表 */
private fun initListPage(): View {
val listView = RecyclerView(this)
listView.layoutManager = LinearLayoutManager(this)
val listData = mutableListOf<ListItemDO>()
val dbHelper = LcgDbHelper(this)
val db = dbHelper.writableDatabase
// 待查询项
val projection = arrayOf(LcgContract.LcgEntry.COLUMN_NAME_TITLE, LcgContract.LcgEntry.COLUMN_NAME_REMARK)
val cursor = db.query(LcgContract.LcgEntry.TABLE_NAME, projection, null, null, null, null, null)
with(cursor) {
while (moveToNext()) {
val title = getString(getColumnIndexOrThrow(LcgContract.LcgEntry.COLUMN_NAME_TITLE))
// val mark = getString(getColumnIndexOrThrow(LcgContract.LcgEntry.COLUMN_NAME_REMARK))
listData.add(ListItemDO(ColorUtils.newRandomColor(), title))
}
close()
}
db.close()
val listAdapter = ListAdapter(listData)
listView.adapter = listAdapter
return listView
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.create -> {
startActivity(Intent(this, CreateActivity::class.java))
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
} | gpl-3.0 | 669eb53149d21b5ef8fc42d779bfc5ef | 31.593023 | 113 | 0.665953 | 4.4689 | false | false | false | false |
talent-bearers/Slimefusion | src/main/java/talent/bearers/slimefusion/common/core/MetalEnums.kt | 1 | 1288 | package talent.bearers.slimefusion.common.core
import talent.bearers.slimefusion.common.block.base.EnumStringSerializable
/**
* @author WireSegal
* Created at 4:44 PM on 12/29/16.
*/
enum class EnumMetalType : EnumStringSerializable {
COPPER, IRON, GOLD, TIN, CADMIUM, ALUMINUM, CHROMIUM, ZINC, LEAD, BISMUTH, NICKEL;
companion object {
operator fun get(meta: Int) = EnumMetalType.values().getOrElse(meta) { COPPER }
fun getNamesFor(prefix: String) = EnumMetalType.values()
.map { prefix + "_" + it.getName() }
.toTypedArray()
}
}
enum class EnumOreType(val mainDrop: EnumMetalType, val rareDrop: EnumMetalType? = null) : EnumStringSerializable {
COPPER(EnumMetalType.COPPER, EnumMetalType.GOLD),
IRON(EnumMetalType.IRON, EnumMetalType.NICKEL),
TIN(EnumMetalType.TIN, EnumMetalType.ZINC),
ALUMINUM(EnumMetalType.ALUMINUM),
CHROMIUM(EnumMetalType.CHROMIUM, EnumMetalType.CADMIUM),
LEAD(EnumMetalType.LEAD, EnumMetalType.BISMUTH);
companion object {
operator fun get(meta: Int) = EnumOreType.values().getOrElse(meta) { COPPER }
fun getNamesFor(prefix: String) = EnumOreType.values()
.map { prefix + "_" + it.getName() }
.toTypedArray()
}
}
| mit | fc2decb4de63c9eec89355b31a098c7e | 34.777778 | 115 | 0.679348 | 3.481081 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/descriptors/MethodDescriptor.kt | 1 | 2816 | /*
* Copyright 2019 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.lightsaber.processor.descriptors
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getMethodType
import org.objectweb.asm.Type as AsmType
private val DEFAULT_CONSTRUCTOR_DESCRIPTOR = AsmType.getMethodDescriptor(AsmType.VOID_TYPE)
private val DEFAULT_CONSTRUCTOR = MethodDescriptor.forConstructor()
private val STATIC_INITIALIZER =
MethodDescriptor.forMethod(MethodDescriptor.STATIC_INITIALIZER_NAME, Type.Primitive.Void)
fun MethodDescriptor(name: String, desc: String) = MethodDescriptor(name, getMethodType(desc))
data class MethodDescriptor(val name: String, val type: Type.Method) {
companion object {
const val CONSTRUCTOR_NAME = "<init>"
const val STATIC_INITIALIZER_NAME = "<clinit>"
fun forMethod(name: String, returnType: Type, vararg argumentTypes: Type): MethodDescriptor {
return MethodDescriptor(name, getMethodType(returnType, *argumentTypes))
}
fun forConstructor(vararg argumentTypes: Type): MethodDescriptor {
return MethodDescriptor(CONSTRUCTOR_NAME, getMethodType(Type.Primitive.Void, *argumentTypes))
}
fun forDefaultConstructor(): MethodDescriptor {
return DEFAULT_CONSTRUCTOR
}
fun forStaticInitializer(): MethodDescriptor {
return STATIC_INITIALIZER
}
fun isConstructor(methodName: String): Boolean {
return CONSTRUCTOR_NAME == methodName
}
fun isDefaultConstructor(methodName: String, methodDesc: String): Boolean {
return isConstructor(methodName) && DEFAULT_CONSTRUCTOR_DESCRIPTOR == methodDesc
}
fun isStaticInitializer(methodName: String): Boolean {
return STATIC_INITIALIZER_NAME == methodName
}
}
}
val MethodDescriptor.descriptor: String
get() = type.descriptor
val MethodDescriptor.returnType: Type
get() = type.returnType
val MethodDescriptor.argumentTypes: List<Type>
get() = type.argumentTypes
val MethodDescriptor.isConstructor: Boolean
get() = MethodDescriptor.isConstructor(name)
val MethodDescriptor.isDefaultConstructor: Boolean
get() = MethodDescriptor.isDefaultConstructor(name, descriptor)
val MethodDescriptor.isStaticInitializer: Boolean
get() = STATIC_INITIALIZER == this
| apache-2.0 | f72aa8187e599a83666eef0e51d8028c | 33.341463 | 99 | 0.762784 | 4.701169 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/model/config/controller/XboxController.kt | 1 | 1114 | package com.github.emulio.model.config.controller
/** Mappings for the Xbox series of controllers. Works only on desktop so far.
* See [this
* image](https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/360_controller.svg/450px-360_controller.svg.png) which describes each button and axes.
* All codes are for buttons expect the L_STICK_XXX, R_STICK_XXX, L_TRIGGER and R_TRIGGER codes, which are axes.
* @author badlogic
*/
object XboxController {
val A = 0
val B = 1
val X = 2
val Y = 3
val L_BUMPER = 4
val R_BUMPER = 5
val BACK = 6
val START = 7
val L_STICK = 8
val R_STICK = 9
val POV_UP = 10
val POV_RIGHT = 11
val POV_DOWN = 12
val POV_LEFT = 13
val AXIS_LEFT_Y = 1 //-1 is up | +1 is down
val AXIS_LEFT_X = 0 //-1 is left | +1 is right
val AXIS_RIGHT_X = 2 //-1 is left | +1 is right
val AXIS_RIGHT_Y = 3 //-1 is up | +1 is down
val AXIS_LEFT_TRIGGER = 4 //-1 for released | 1 for pressed
val AXIS_RIGHT_TRIGGER = 5 //-1 for released | 1 for pressed
fun isXboxController(controllerName: String): Boolean {
return controllerName.toLowerCase().contains("xbox")
}
} | gpl-3.0 | 0db160871790cb493a38938c72edd133 | 30.857143 | 156 | 0.681329 | 2.931579 | false | false | false | false |
thomasvolk/alkali | src/main/kotlin/net/t53k/alkali/Actor.kt | 1 | 3361 | /*
* Copyright 2017 Thomas Volk
*
* 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 net.t53k.alkali
import java.util.concurrent.LinkedBlockingQueue
import kotlin.concurrent.thread
internal data class ActorMessageWrapper(val message: Any, val sender: ActorReference)
abstract class Actor: ActorFactory {
private val _inbox = LinkedBlockingQueue<ActorMessageWrapper>()
private var _running = false
private lateinit var _self: ActorReference
private lateinit var _system: ActorSystem
private lateinit var _sender: ActorReference
private lateinit var _thread: Thread
private val _watchers = mutableSetOf<ActorReference>()
override fun <T : Actor> actor(name: String, actor: T): ActorReference {
val actorRef = system().actor(name, actor)
self() watch actorRef
return actorRef
}
@Synchronized
internal fun start(name: String, system: ActorSystem): ActorReference {
if(_running) { throw IllegalStateException("actor already started!") }
_running = true
_self = ActorReference(system, this, name)
_system = system
_thread = thread {
system().currentActor(self())
before()
try {
mainLoop()
} finally {
after()
_watchers.forEach { it send Terminated }
}
}
return _self
}
internal fun waitForShutdown() { _thread.join() }
internal fun send(message: Any, sender: ActorReference) {
if(_running) {
_inbox.put(ActorMessageWrapper(message, sender))
} else {
system().deadLetter(message)
}
}
private fun mainLoop() {
while (_running) {
val (message, sender) = _inbox.take()
_sender = sender
when (message) {
is Forward -> _receive(message.message)
PoisonPill -> stop()
Watch -> _watchers += sender()
else -> _receive(message)
}
}
}
private fun _receive(message: Any) {
try {
receive(message)
} catch (e: Exception) {
onException(e)
}
}
protected fun stop() {
_running = false
}
protected fun system() = _system
protected fun sender() = _sender
protected fun self() = _self
protected abstract fun receive(message: Any)
open protected fun after() {
}
open protected fun before() {
}
open protected fun onException(e: Exception) {
throw e
}
} | apache-2.0 | feed08c477b0ec29de879e7eb7cda152 | 28.234783 | 85 | 0.619756 | 4.668056 | false | false | false | false |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/DisplayLeakConnectorView.kt | 2 | 7621 | /*
* Copyright (C) 2015 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 leakcanary.internal
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.graphics.PorterDuff.Mode.CLEAR
import android.graphics.PorterDuffXfermode
import android.util.AttributeSet
import android.view.View
import com.squareup.leakcanary.core.R
import leakcanary.internal.DisplayLeakConnectorView.Type.END
import leakcanary.internal.DisplayLeakConnectorView.Type.END_FIRST_UNREACHABLE
import leakcanary.internal.DisplayLeakConnectorView.Type.GC_ROOT
import leakcanary.internal.DisplayLeakConnectorView.Type.NODE_FIRST_UNREACHABLE
import leakcanary.internal.DisplayLeakConnectorView.Type.NODE_LAST_REACHABLE
import leakcanary.internal.DisplayLeakConnectorView.Type.NODE_REACHABLE
import leakcanary.internal.DisplayLeakConnectorView.Type.NODE_UNKNOWN
import leakcanary.internal.DisplayLeakConnectorView.Type.NODE_UNREACHABLE
import leakcanary.internal.DisplayLeakConnectorView.Type.START
import leakcanary.internal.DisplayLeakConnectorView.Type.START_LAST_REACHABLE
import leakcanary.internal.navigation.getColorCompat
import kotlin.math.sqrt
internal class DisplayLeakConnectorView(
context: Context,
attrs: AttributeSet
) : View(context, attrs) {
private val classNamePaint: Paint
private val leakPaint: Paint
private val clearPaint: Paint
private val referencePaint: Paint
private val strokeSize: Float
private val circleY: Float
private var type: Type? = null
private var cache: Bitmap? = null
enum class Type {
GC_ROOT,
START,
START_LAST_REACHABLE,
NODE_UNKNOWN,
NODE_FIRST_UNREACHABLE,
NODE_UNREACHABLE,
NODE_REACHABLE,
NODE_LAST_REACHABLE,
END,
END_FIRST_UNREACHABLE
}
init {
val resources = resources
type = NODE_UNKNOWN
circleY = resources.getDimensionPixelSize(R.dimen.leak_canary_connector_center_y)
.toFloat()
strokeSize = resources.getDimensionPixelSize(R.dimen.leak_canary_connector_stroke_size)
.toFloat()
classNamePaint = Paint(Paint.ANTI_ALIAS_FLAG)
classNamePaint.color = context.getColorCompat(R.color.leak_canary_class_name)
classNamePaint.strokeWidth = strokeSize
leakPaint = Paint(Paint.ANTI_ALIAS_FLAG)
leakPaint.color = context.getColorCompat(R.color.leak_canary_leak)
leakPaint.style = Paint.Style.STROKE
leakPaint.strokeWidth = strokeSize
val pathLines = resources.getDimensionPixelSize(R.dimen.leak_canary_connector_leak_dash_line)
.toFloat()
val pathGaps = resources.getDimensionPixelSize(R.dimen.leak_canary_connector_leak_dash_gap)
.toFloat()
leakPaint.pathEffect = DashPathEffect(floatArrayOf(pathLines, pathGaps), 0f)
clearPaint = Paint(Paint.ANTI_ALIAS_FLAG)
clearPaint.color = Color.TRANSPARENT
clearPaint.xfermode = CLEAR_XFER_MODE
referencePaint = Paint(Paint.ANTI_ALIAS_FLAG)
referencePaint.color = context.getColorCompat(R.color.leak_canary_reference)
referencePaint.strokeWidth = strokeSize
}
override fun onDraw(canvas: Canvas) {
val width = measuredWidth
val height = measuredHeight
if (cache != null && (cache!!.width != width || cache!!.height != height)) {
cache!!.recycle()
cache = null
}
if (cache == null) {
cache = Bitmap.createBitmap(width, height, ARGB_8888)
val cacheCanvas = Canvas(cache!!)
when (type) {
NODE_UNKNOWN -> drawItems(cacheCanvas, leakPaint, leakPaint)
NODE_UNREACHABLE, NODE_REACHABLE -> drawItems(
cacheCanvas, referencePaint, referencePaint
)
NODE_FIRST_UNREACHABLE -> drawItems(
cacheCanvas, leakPaint, referencePaint
)
NODE_LAST_REACHABLE -> drawItems(
cacheCanvas, referencePaint, leakPaint
)
START -> {
drawStartLine(cacheCanvas)
drawItems(cacheCanvas, null, referencePaint)
}
START_LAST_REACHABLE -> {
drawStartLine(cacheCanvas)
drawItems(cacheCanvas, null, leakPaint)
}
END -> drawItems(cacheCanvas, referencePaint, null)
END_FIRST_UNREACHABLE -> drawItems(
cacheCanvas, leakPaint, null
)
GC_ROOT -> drawGcRoot(cacheCanvas)
else -> throw UnsupportedOperationException("Unknown type " + type!!)
}
}
canvas.drawBitmap(cache!!, 0f, 0f, null)
}
private fun drawStartLine(cacheCanvas: Canvas) {
val width = measuredWidth
val halfWidth = width / 2f
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, circleY, classNamePaint)
}
private fun drawGcRoot(
cacheCanvas: Canvas
) {
val width = measuredWidth
val height = measuredHeight
val halfWidth = width / 2f
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, height.toFloat(), classNamePaint)
}
private fun drawItems(
cacheCanvas: Canvas,
arrowHeadPaint: Paint?,
nextArrowPaint: Paint?
) {
if (arrowHeadPaint != null) {
drawArrowHead(cacheCanvas, arrowHeadPaint)
}
if (nextArrowPaint != null) {
drawNextArrowLine(cacheCanvas, nextArrowPaint)
}
drawInstanceCircle(cacheCanvas)
}
private fun drawArrowHead(
cacheCanvas: Canvas,
paint: Paint
) {
// Circle center is at half height
val width = measuredWidth
val halfWidth = width / 2f
val circleRadius = width / 3f
// Splitting the arrow head in two makes an isosceles right triangle.
// It's hypotenuse is side * sqrt(2)
val arrowHeight = halfWidth / 2 * SQRT_TWO
val halfStrokeSize = strokeSize / 2
val translateY = circleY - arrowHeight - circleRadius * 2 - strokeSize
val lineYEnd = circleY - circleRadius - strokeSize / 2
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, lineYEnd, paint)
cacheCanvas.translate(halfWidth, translateY)
cacheCanvas.rotate(45f)
cacheCanvas.drawLine(
0f, halfWidth, halfWidth + halfStrokeSize, halfWidth,
paint
)
cacheCanvas.drawLine(halfWidth, 0f, halfWidth, halfWidth, paint)
cacheCanvas.rotate(-45f)
cacheCanvas.translate(-halfWidth, -translateY)
}
private fun drawNextArrowLine(
cacheCanvas: Canvas,
paint: Paint
) {
val height = measuredHeight
val width = measuredWidth
val centerX = width / 2f
cacheCanvas.drawLine(centerX, circleY, centerX, height.toFloat(), paint)
}
private fun drawInstanceCircle(cacheCanvas: Canvas) {
val width = measuredWidth
val circleX = width / 2f
val circleRadius = width / 3f
cacheCanvas.drawCircle(circleX, circleY, circleRadius, classNamePaint)
}
fun setType(type: Type) {
if (type != this.type) {
this.type = type
if (cache != null) {
cache!!.recycle()
cache = null
}
invalidate()
}
}
companion object {
private val SQRT_TWO = sqrt(2.0)
.toFloat()
private val CLEAR_XFER_MODE = PorterDuffXfermode(CLEAR)
}
}
| apache-2.0 | cac093b584383ecc7278b9ea89027a0c | 30.622407 | 97 | 0.714211 | 4.162206 | false | false | false | false |
square/leakcanary | shark/src/test/java/shark/internal/DominatorTreeTest.kt | 2 | 7904 | package shark.internal
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import shark.ValueHolder
@Suppress("UsePropertyAccessSyntax")
class DominatorTreeTest {
var latestObjectId: Long = 0
private fun newObjectId() = ++latestObjectId
@Suppress("PrivatePropertyName")
private val `10 bytes per object`: (Long) -> Int = { 10 }
@Test fun `new object is not already dominated`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val alreadyDominated = tree.updateDominated(newObjectId(), root)
assertThat(alreadyDominated).isFalse()
}
@Test fun `dominated object is already dominated`() {
val tree = DominatorTree()
val root1 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val root2 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child = newObjectId().apply { tree.updateDominated(this, root1) }
val alreadyDominated = tree.updateDominated(child, root2)
assertThat(alreadyDominated).isTrue()
}
@Test fun `only retained objects are returned in sizes map`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child = newObjectId().apply { tree.updateDominated(this, root) }
val sizes = tree.computeRetainedSizes(setOf(child), `10 bytes per object`)
assertThat(sizes).containsOnlyKeys(child)
}
@Test fun `single root has self size as retained size`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val sizes = tree.computeRetainedSizes(setOf(root), `10 bytes per object`)
assertThat(sizes[root]).isEqualTo(10 to 1)
}
@Test fun `size of dominator includes dominated`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
tree.updateDominated(newObjectId(), root)
val sizes = tree.computeRetainedSizes(setOf(root), `10 bytes per object`)
assertThat(sizes[root]).isEqualTo(20 to 2)
}
@Test fun `size of chain of dominators is additive`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child = newObjectId().apply { tree.updateDominated(this, root) }
tree.updateDominated(newObjectId(), child)
val sizes = tree.computeRetainedSizes(setOf(root, child), `10 bytes per object`)
assertThat(sizes[root]).isEqualTo(30 to 3)
assertThat(sizes[child]).isEqualTo(20 to 2)
}
@Test fun `diamond dominators don't dominate`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child1 = newObjectId().apply { tree.updateDominated(this, root) }
val child2 = newObjectId().apply { tree.updateDominated(this, root) }
val grandChild = newObjectId()
tree.updateDominated(grandChild, child1)
tree.updateDominated(grandChild, child2)
val sizes = tree.computeRetainedSizes(setOf(root, child1, child2), `10 bytes per object`)
assertThat(sizes[child1]).isEqualTo(10 to 1)
assertThat(sizes[child2]).isEqualTo(10 to 1)
assertThat(sizes[root]).isEqualTo(40 to 4)
}
@Test fun `two dominators dominated by common ancestor`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child1 = newObjectId().apply { tree.updateDominated(this, root) }
val child2 = newObjectId().apply { tree.updateDominated(this, root) }
val grandChild = newObjectId()
tree.updateDominated(grandChild, child1)
tree.updateDominated(grandChild, child2)
val sizes = tree.computeRetainedSizes(setOf(root, child1, child2), `10 bytes per object`)
assertThat(sizes[child1]).isEqualTo(10 to 1)
assertThat(sizes[child2]).isEqualTo(10 to 1)
assertThat(sizes[root]).isEqualTo(40 to 4)
}
@Test fun `two dominators dominated by lowest common ancestor`() {
val tree = DominatorTree()
val root = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child = newObjectId().apply { tree.updateDominated(this, root) }
val grandChild1 = newObjectId().apply { tree.updateDominated(this, child) }
val grandChild2 = newObjectId().apply { tree.updateDominated(this, child) }
val grandGrandChild = newObjectId()
tree.updateDominated(grandGrandChild, grandChild1)
tree.updateDominated(grandGrandChild, grandChild2)
val sizes =
tree.computeRetainedSizes(setOf(root, child, grandChild1, grandChild2), `10 bytes per object`)
assertThat(sizes[grandChild1]).isEqualTo(10 to 1)
assertThat(sizes[grandChild1]).isEqualTo(10 to 1)
assertThat(sizes[child]).isEqualTo(40 to 4)
assertThat(sizes[root]).isEqualTo(50 to 5)
}
@Test fun `two separate trees do not share size`() {
val tree = DominatorTree()
val root1 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val root2 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
var descendant1 = root1
var descendant2 = root2
for (i in 1..10) {
descendant1 = newObjectId().apply { tree.updateDominated(this, descendant1) }
descendant2 = newObjectId().apply { tree.updateDominated(this, descendant2) }
}
val sizes =
tree.computeRetainedSizes(setOf(root1, root2), `10 bytes per object`)
assertThat(sizes[root1]).isEqualTo(110 to 11)
assertThat(sizes[root2]).isEqualTo(110 to 11)
}
@Test fun `no common descendant does not include size`() {
val tree = DominatorTree()
val root1 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val root2 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
var descendant = root1
for (i in 1..10) {
descendant = newObjectId().apply { tree.updateDominated(this, descendant) }
}
tree.updateDominated(descendant, root2)
val sizes =
tree.computeRetainedSizes(setOf(root1, root2), `10 bytes per object`)
assertThat(sizes[root1]).isEqualTo(100 to 10)
assertThat(sizes[root2]).isEqualTo(10 to 1)
}
@Test fun `only compute retained size for retained objects`() {
val tree = DominatorTree()
val root1 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val root2 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child = newObjectId().apply { tree.updateDominated(this, root1) }
val grandChild = newObjectId().apply { tree.updateDominated(this, child) }
val grandGrandChild = newObjectId().apply { tree.updateDominated(this, grandChild) }
tree.updateDominated(grandGrandChild, root2)
val objectsWithComputedSize = mutableSetOf<Long>()
tree.computeRetainedSizes(setOf(child)) { objectId ->
objectsWithComputedSize += objectId
1
}
assertThat(objectsWithComputedSize).containsOnly(child, grandChild)
}
@Test fun `null ref dominates all`() {
val tree = DominatorTree()
val root1 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val root2 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val root3 = newObjectId().apply { tree.updateDominatedAsRoot(this) }
val child = newObjectId()
tree.updateDominated(child, root1)
tree.updateDominated(child, root2)
val grandChild = newObjectId().apply { tree.updateDominated(this, child) }
val fullDominatorTree = tree.buildFullDominatorTree(`10 bytes per object`)
assertThat(fullDominatorTree.getValue(root1).retainedSize).isEqualTo(10)
assertThat(fullDominatorTree.getValue(root2).retainedSize).isEqualTo(10)
assertThat(fullDominatorTree.getValue(root3).retainedSize).isEqualTo(10)
assertThat(fullDominatorTree.getValue(child).retainedSize).isEqualTo(20)
assertThat(fullDominatorTree.getValue(grandChild).retainedSize).isEqualTo(10)
assertThat(fullDominatorTree.getValue(ValueHolder.NULL_REFERENCE).retainedSize).isEqualTo(50)
}
} | apache-2.0 | c90169e87b3c7e649d45b441604202d6 | 38.525 | 100 | 0.716093 | 3.67457 | false | true | false | false |
ajmirB/Messaging | app/src/main/java/com/xception/messaging/features/channels/fragments/ConversationFragment.kt | 1 | 4749 | package com.xception.messaging.features.channels.fragments
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import android.widget.EditText
import android.widget.ImageView
import com.airbnb.epoxy.EpoxyRecyclerView
import com.sendbird.android.BaseChannel
import com.xception.messaging.R
import com.xception.messaging.features.channels.presenters.ConversationPresenter
import com.xception.messaging.features.channels.presenters.ConversationView
import com.xception.messaging.features.channels.presenters.MessageItemData
import com.xception.messaging.features.commons.BaseFragment
import com.xception.messaging.helper.toModel
import ru.alexbykov.nopaginate.paginate.Paginate
import ru.alexbykov.nopaginate.paginate.PaginateBuilder
class ConversationFragment: BaseFragment(), ConversationView {
lateinit var mConversationPresenter: ConversationPresenter
lateinit var mPaginate: Paginate
lateinit var mRecyclerView: EpoxyRecyclerView
lateinit var mMessageInputText: EditText
lateinit var mSendMessageButton: ImageView
lateinit var mFragmentListener: Listener
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is Listener) {
mFragmentListener = context
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_conversation, container, false)
val channelUrl = arguments.getString(CHANNEL_URL_KEY)
mConversationPresenter = ConversationPresenter(this, channelUrl!!)
mRecyclerView = view.findViewById(R.id.conversation_epoxy_recycler_view)
// To display the item in the reverse order
val layoutManager = LinearLayoutManager(activity)
layoutManager.reverseLayout = true
mRecyclerView.layoutManager = layoutManager
mMessageInputText = view.findViewById(R.id.conversation_epoxy_input_edit_text_view)
mSendMessageButton = view.findViewById(R.id.conversation_send_image_view)
mSendMessageButton.setOnClickListener({ mConversationPresenter.onSendButtonClicked(mMessageInputText.text.toString()) })
setHasOptionsMenu(true)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mConversationPresenter.onViewCreated()
}
override fun onDestroyView() {
super.onDestroyView()
setHasOptionsMenu(false)
mConversationPresenter.onViewDestroyed()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_conversation, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.conversation_participants_button -> {
mConversationPresenter.onParticipantsListClick()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
// region ConversationView
override fun initContent(messages: List<MessageItemData>) {
mRecyclerView.buildModelsWith { controller ->
messages.toModel().forEach {
it.addTo(controller)
}
}
mPaginate = PaginateBuilder()
.with(mRecyclerView)
.setCallback({ mConversationPresenter.onLoadingMore() })
.setLoadingTriggerThreshold(5)
.build()
}
override fun addPreviousMessages(messages: List<MessageItemData>) {
mRecyclerView.setModels(messages.toModel())
}
override fun addIncomingMessage(messages: List<MessageItemData>) {
mRecyclerView.setModels(messages.toModel())
mRecyclerView.smoothScrollToPosition(0)
}
override fun stopPaginate() {
mPaginate.setPaginateNoMoreItems(true)
}
override fun resetInputText() {
mMessageInputText.text = null
}
override fun goToParticipants(channel: BaseChannel) {
mFragmentListener.showParticipants(channel)
}
// endregion
companion object {
val CHANNEL_URL_KEY = "CHANNEL_URL_KEY"
fun newInstance(channelUrl: String): ConversationFragment {
val bundle = Bundle()
bundle.putString(CHANNEL_URL_KEY, channelUrl)
val fragment = ConversationFragment()
fragment.arguments = bundle
return fragment
}
}
interface Listener {
fun showParticipants(channel: BaseChannel)
}
} | apache-2.0 | 55b7a8bf2de3566c7af78aaf26ab6de0 | 30.25 | 129 | 0.703938 | 5.073718 | false | false | false | false |
petrbalat/jlib | src/main/java/cz/softdeluxe/jlib/delegate/SimpleCacheDelegate.kt | 1 | 1257 | package cz.softdeluxe.jlib.delegate
import java.util.concurrent.TimeUnit
import kotlin.reflect.KProperty
class SimpleCacheDelegate<T>(private val periodMillis: Long,
lock: Any? = null,
private val initializer: (oldData:T?) -> T) {
private val lock = lock ?: this
private var value: T? = null
private var lastGet: Long = System.currentTimeMillis()
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = synchronized(lock) {
val curentMillisec = System.currentTimeMillis()
var value = value
if (value == null || curentMillisec - lastGet >= periodMillis) {
value = initializer(value)
this.value = value
lastGet = curentMillisec
return value
}
return value
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value_: Any?) {
value = initializer(value)
}
}
/**
* cache delegát - pokud se nasetuje jakákoliv hodnota bere se hodnota z initializer
*/
fun <T> cacheDelegate(time: Long, timeUnit: TimeUnit = TimeUnit.SECONDS, lock: Any? = null, initializer: (oldData:T?) -> T)
= SimpleCacheDelegate(timeUnit.toMillis(time), lock, initializer)
| apache-2.0 | be159d9c16c4fd653eeb998218433c6c | 32.918919 | 123 | 0.630279 | 4.268707 | false | false | false | false |
mistraltechnologies/smogen | src/main/kotlin/com/mistraltech/smogen/plugin/MatcherGeneratorOptionsPanel.kt | 1 | 8806 | package com.mistraltech.smogen.plugin
import com.intellij.openapi.project.calcRelativeToProjectPath
import com.intellij.openapi.roots.FileIndex
import com.intellij.openapi.roots.JavaProjectRootsUtil
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiNameHelper
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.ProjectScope
import com.intellij.refactoring.ui.ClassNameReferenceEditor
import com.intellij.refactoring.ui.PackageNameReferenceEditorCombo
import com.intellij.ui.ReferenceEditorWithBrowseButton
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.util.PlatformIcons
import com.mistraltech.smogen.utils.PsiUtils.isAbstract
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComboBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.JRadioButton
import javax.swing.JTextField
class MatcherGeneratorOptionsPanel(private val dataSource: MatcherGeneratorOptionsPanelDataSource) {
private var rootPanel: JPanel? = null
private var classNameTextField: JTextField? = null
private var makeExtensibleCheckBox: JCheckBox? = null
private var packageComponent: PackageNameReferenceEditorCombo? = null
private var destinationSourceRootComboBox: JComboBox<ListItemWrapper<VirtualFile>>? = null
private var aRadioButton: JRadioButton? = null
private var anRadioButton: JRadioButton? = null
private var extendsCheckBox: JCheckBox? = null
private var superClassChooser: ReferenceEditorWithBrowseButton? = null
private var sourceClassName: JLabel? = null
private var classRadioButton: JRadioButton? = null
private var interfaceRadioButton: JRadioButton? = null
@Suppress("unused")
private var matchesLabel: JLabel? = null
private fun initialiseSourceClassNameField() {
sourceClassName!!.text = dataSource.matchedClass.qualifiedName
}
private fun initialiseGenerateTypeRadioButtons() {
classRadioButton!!.isEnabled = true
interfaceRadioButton!!.isEnabled = isSmogJavassistOnClasspath
if (interfaceRadioButton!!.isEnabled) {
interfaceRadioButton!!.isSelected = true
} else {
classRadioButton!!.isSelected = true
}
}
private fun initialiseClassNameField() {
classNameTextField!!.text = dataSource.defaultClassName
}
private fun initialiseExtendsFields() {
superClassChooser!!.isEnabled = false
extendsCheckBox!!.isSelected = false
extendsCheckBox!!.addChangeListener { onExtendsCheckBoxStateChange() }
}
private fun onExtendsCheckBoxStateChange() {
superClassChooser!!.isEnabled = extendsCheckBox!!.isSelected
}
private fun initialiseMakeExtensibleCheckBox() {
// If we are matching an abstract class, likelihood is we want the matcher to be extensible
makeExtensibleCheckBox!!.isSelected =
if (isAbstract(dataSource.matchedClass)) true else dataSource.defaultIsExtensible
makeExtensibleCheckBox!!.isEnabled = true
}
private fun initialiseFactoryMethodPrefixRadioButtons() {
// The factory method prefix is either 'a' or 'an', selected by radio buttons
// and labelled by matchesLabel.
val matchedClassName = dataSource.matchedClass.name ?: throw IllegalStateException("Matched class has no name")
aRadioButton!!.text = "a $matchedClassName"
anRadioButton!!.text = "an $matchedClassName"
if (hasVowelSound(matchedClassName)) {
anRadioButton!!.isSelected = true
} else {
aRadioButton!!.isSelected = true
}
}
private fun initialiseDestinationSourceRootComboBox() {
dataSource.candidateRoots.forEach { candidateRoot ->
val listItemWrapper = createSourceRootItemWrapper(candidateRoot)
destinationSourceRootComboBox!!.addItem(listItemWrapper)
if (candidateRoot == dataSource.defaultRoot) {
destinationSourceRootComboBox!!.selectedItem = listItemWrapper
}
}
destinationSourceRootComboBox!!.setRenderer(
object : SimpleListCellRenderer<ListItemWrapper<VirtualFile>>() {
override fun customize(
list: JList<out ListItemWrapper<VirtualFile>>,
value: ListItemWrapper<VirtualFile>?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
icon = value?.icon
text = value?.text
}
}
)
}
val selectedSourceRoot: VirtualFile
get() = destinationSourceRootComboBox!!.getItemAt(destinationSourceRootComboBox!!.selectedIndex).item
val selectedClassName: String
get() = classNameTextField!!.text
val selectedPackageName: String
get() = packageComponent!!.text
val isMakeExtensible: Boolean
get() = makeExtensibleCheckBox!!.isSelected
val isAn: Boolean
get() = anRadioButton!!.isSelected
val isGenerateInterface: Boolean
get() = interfaceRadioButton!!.isSelected
val superClassName: String?
get() = if (extendsCheckBox!!.isSelected) {
superClassChooser!!.text.trim { it <= ' ' }
} else {
null
}
val root: JComponent
get() = rootPanel!!
private fun hasVowelSound(matchedClassName: String): Boolean {
return "aeiou".contains(matchedClassName.substring(0, 1).toLowerCase())
}
private fun createSourceRootItemWrapper(candidateRoot: VirtualFile): ListItemWrapper<VirtualFile> {
val relativePath = calcRelativeToProjectPath(candidateRoot, dataSource.project, true, false, true)
return ListItemWrapper(candidateRoot, relativePath, getSourceRootIcon(candidateRoot))
}
private fun createUIComponents() {
// This is called by the form handler for custom-created components
val project = dataSource.project
packageComponent = PackageNameReferenceEditorCombo(
dataSource.packageName,
project,
dataSource.recentsKey,
"Choose Destination Package"
)
packageComponent!!.setTextFieldPreferredWidth(PANEL_WIDTH_CHARS)
val scope = JavaProjectRootsUtil.getScopeWithoutGeneratedSources(ProjectScope.getProjectScope(project), project)
superClassChooser = ClassNameReferenceEditor(project, null, scope)
superClassChooser!!.setTextFieldPreferredWidth(PANEL_WIDTH_CHARS)
}
private fun getSourceRootIcon(virtualFile: VirtualFile): Icon {
val fileIndex: FileIndex = ProjectRootManager.getInstance(dataSource.project).fileIndex
return when {
fileIndex.isInTestSourceContent(virtualFile) -> {
PlatformIcons.MODULES_TEST_SOURCE_FOLDER
}
fileIndex.isInSourceContent(virtualFile) -> {
PlatformIcons.MODULES_SOURCE_FOLDERS_ICON
}
else -> {
PlatformIcons.FOLDER_ICON
}
}
}
fun doValidate(): ValidationInfo? {
val className = classNameTextField!!.text.trim { it <= ' ' }
return when {
className.isEmpty() -> {
ValidationInfo("Class name is empty", classNameTextField)
}
!PsiNameHelper.getInstance(dataSource.project).isIdentifier(className) -> {
ValidationInfo("Class name is not a valid identifier", classNameTextField)
}
else -> null
}
}
private val isSmogJavassistOnClasspath: Boolean
get() {
val project = dataSource.project
val javaPsiFacade = JavaPsiFacade.getInstance(project)
val generatorClass = javaPsiFacade.findClass(SMOG_JAVASSIST_GENERATOR, GlobalSearchScope.allScope(project))
return generatorClass != null
}
private inner class ListItemWrapper<T> constructor(val item: T, val text: String, val icon: Icon)
companion object {
private const val PANEL_WIDTH_CHARS = 60
private const val SMOG_JAVASSIST_GENERATOR = "com.mistraltech.smog.proxy.javassist.JavassistMatcherGenerator"
}
init {
initialiseSourceClassNameField()
initialiseGenerateTypeRadioButtons()
initialiseClassNameField()
initialiseMakeExtensibleCheckBox()
initialiseExtendsFields()
initialiseFactoryMethodPrefixRadioButtons()
initialiseDestinationSourceRootComboBox()
}
}
| bsd-3-clause | a90282c014e497964be2c539be20bd32 | 38.137778 | 120 | 0.691687 | 5.362972 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | lib_service/src/main/java/no/nordicsemi/android/service/NotificationService.kt | 1 | 5800 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleService
private const val CHANNEL_ID = "FOREGROUND_BLE_SERVICE"
abstract class NotificationService : LifecycleService() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val result = super.onStartCommand(intent, flags, startId)
startForegroundService()
return result
}
override fun onDestroy() {
// when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService
cancelNotification()
stopForegroundService()
super.onDestroy()
}
/**
* Sets the service as a foreground service
*/
private fun startForegroundService() {
// when the activity closes we need to show the notification that user is connected to the peripheral sensor
// We start the service as a foreground service as Android 8.0 (Oreo) onwards kills any running background services
val notification = createNotification(R.string.csc_notification_connected_message, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, notification)
} else {
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
nm.notify(NOTIFICATION_ID, notification)
}
}
/**
* Stops the service as a foreground service
*/
private fun stopForegroundService() {
// when the activity rebinds to the service, remove the notification and stop the foreground service
// on devices running Android 8.0 (Oreo) or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true)
} else {
cancelNotification()
}
}
/**
* Creates the notification
*
* @param messageResId the message resource id. The message must have one String parameter,<br></br>
* f.e. `<string name="name">%s is connected</string>`
* @param defaults
*/
private fun createNotification(messageResId: Int, defaults: Int): Notification {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(CHANNEL_ID)
}
val intent: Intent? = packageManager.getLaunchIntentForPackage(packageName)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(messageResId, "Device"))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setColor(ContextCompat.getColor(this, R.color.md_theme_primary))
.setContentIntent(pendingIntent)
.build()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelName: String) {
val channel = NotificationChannel(
channelName,
getString(R.string.channel_connected_devices_title),
NotificationManager.IMPORTANCE_LOW
)
channel.description = getString(R.string.channel_connected_devices_description)
channel.setShowBadge(false)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
/**
* Cancels the existing notification. If there is no active notification this method does nothing
*/
private fun cancelNotification() {
val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
nm.cancel(NOTIFICATION_ID)
}
companion object {
private const val NOTIFICATION_ID = 200
}
}
| bsd-3-clause | b8115b021cc8859f207b5346d34e01df | 40.726619 | 153 | 0.714828 | 5.021645 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/tournaments/TournamentsViewModel.kt | 1 | 4493 | package com.garpr.android.features.tournaments
import androidx.annotation.AnyThread
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.garpr.android.data.models.AbsTournament
import com.garpr.android.data.models.Region
import com.garpr.android.data.models.TournamentsBundle
import com.garpr.android.features.common.viewModels.BaseViewModel
import com.garpr.android.misc.Schedulers
import com.garpr.android.misc.ThreadUtils
import com.garpr.android.misc.Timber
import com.garpr.android.repositories.TournamentsRepository
import java.util.Collections
class TournamentsViewModel(
private val schedulers: Schedulers,
private val threadUtils: ThreadUtils,
private val timber: Timber,
private val tournamentsRepository: TournamentsRepository
) : BaseViewModel() {
private val _stateLiveData = MutableLiveData<State>()
val stateLiveData: LiveData<State> = _stateLiveData
private var state: State = State()
set(value) {
field = value
_stateLiveData.postValue(value)
}
var searchQuery: String? = null
set(value) {
field = value
search(value)
}
@WorkerThread
private fun createList(bundle: TournamentsBundle?): List<ListItem>? {
val tournaments = bundle?.tournaments
return if (tournaments.isNullOrEmpty()) {
null
} else {
tournaments.map { tournament ->
ListItem.Tournament(
tournament = tournament
)
}
}
}
fun fetchTournaments(region: Region) {
state = state.copy(isFetching = true)
disposables.add(tournamentsRepository.getTournaments(region)
.subscribeOn(schedulers.background)
.observeOn(schedulers.background)
.subscribe({ bundle ->
val list = createList(bundle)
state = state.copy(
hasError = false,
isEmpty = list.isNullOrEmpty(),
isFetching = false,
list = list,
searchResults = null,
tournamentsBundle = bundle
)
}, {
timber.e(TAG, "Error fetching tournaments", it)
state = state.copy(
hasError = true,
isEmpty = false,
isFetching = false,
list = null,
searchResults = null,
tournamentsBundle = null
)
}))
}
@AnyThread
private fun search(query: String?) {
threadUtils.background.submit {
val results = search(query, state.list)
state = state.copy(searchResults = results)
}
}
@WorkerThread
private fun search(query: String?, list: List<ListItem>?): List<ListItem>? {
if (query.isNullOrBlank() || list.isNullOrEmpty()) {
return null
}
val trimmedQuery = query.trim()
val results = list
.filterIsInstance(ListItem.Tournament::class.java)
.filter { listItem ->
listItem.tournament.name.contains(trimmedQuery, ignoreCase = true)
}
return if (results.isEmpty()) {
Collections.singletonList(ListItem.NoResults(trimmedQuery))
} else {
results
}
}
companion object {
private const val TAG = "TournamentsViewModel"
}
sealed class ListItem {
abstract val listId: Long
class NoResults(
val query: String
) : ListItem() {
override val listId: Long = Long.MIN_VALUE + 1L
}
class Tournament(
val tournament: AbsTournament
) : ListItem() {
override val listId: Long = tournament.hashCode().toLong()
}
}
data class State(
val hasError: Boolean = false,
val isEmpty: Boolean = false,
val isFetching: Boolean = false,
val list: List<ListItem>? = null,
val searchResults: List<ListItem>? = null,
val tournamentsBundle: TournamentsBundle? = null
)
}
| unlicense | 63e90622efde2d703fcdadffd3a8efd4 | 30.41958 | 86 | 0.557757 | 5.40024 | false | false | false | false |
KazuCocoa/DroidTestHelper | app/src/main/java/com/kazucocoa/droidtesthelper/HandleLocaleActivity.kt | 1 | 2327 | package com.kazucocoa.droidtesthelper
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import com.kazucocoa.droidtesthelperlib.HandleLocale
import java.util.Locale
class HandleLocaleActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_handle_locale)
val handleLocale = HandleLocale()
val textView = findViewById<View>(R.id.set_for_change_locale_text) as TextView
if (hasExtraRegardingLocal(this.intent)) {
val lang = this.intent.getStringExtra(languageExt)
val coun = this.intent.getStringExtra(countryExt)
textView.text = "set with: ${lang}_$coun"
Locale(lang, coun).let { handleLocale.setLocale(it) }
} else {
textView.text = "set with: en_US(Default)"
Locale("en", "US").let { handleLocale.setLocale(it) }
}
}
companion object {
private val TAG = HandleLocaleActivity::class.java.simpleName
private const val languageExt = "LANG"
private const val countryExt = "COUNTRY"
fun hasExtraRegardingLocal(intent: Intent): Boolean {
return intent.hasExtra(languageExt) && intent.hasExtra(countryExt)
}
fun buildLaunchHandleLocalActivityIntent(context: Context, intent: Intent): Intent {
val returnIntent = Intent(context, HandleLocaleActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
action = Intent.ACTION_VIEW
}
if (!hasExtraRegardingLocal(intent)) {
return returnIntent.apply {
putExtra(languageExt, "en")
putExtra(countryExt, "US")
}
}
val language = intent.getStringExtra(languageExt)
val country = intent.getStringExtra(countryExt)
return returnIntent.apply {
putExtra(languageExt, language)
putExtra(countryExt, country)
}
}
}
}
| mit | 19e09f7bc2ccb6f66cdbc002155a172f | 31.319444 | 92 | 0.640739 | 4.598814 | false | false | false | false |
Zukkari/nirdizati-training-ui | src/main/kotlin/cs/ut/ui/controllers/training/AdvancedModeController.kt | 1 | 5871 | package cs.ut.ui.controllers.training
import cs.ut.engine.item.ModelParameter
import cs.ut.engine.item.Property
import cs.ut.ui.NirdizatiGrid
import cs.ut.ui.adapters.AdvancedModeAdapter
import cs.ut.ui.adapters.GeneratorArgument
import cs.ut.ui.adapters.PropertyValueAdapter
import cs.ut.ui.components.CheckBoxGroup
import cs.ut.ui.controllers.TrainingController
import cs.ut.util.HYPER_PARAM_CONT
import org.apache.logging.log4j.LogManager
import org.zkoss.zk.ui.Component
import org.zkoss.zk.ui.Executions
import org.zkoss.zk.ui.event.CheckEvent
import org.zkoss.zk.ui.event.Events
import org.zkoss.zul.Checkbox
import org.zkoss.zul.Hlayout
import org.zkoss.zul.Vlayout
class AdvancedModeController(gridContainer: Vlayout) : AbstractModeController(gridContainer), ModeController {
private val log = LogManager.getLogger(AdvancedModeController::class.java)
private val rowProvider = AdvancedModeAdapter()
private val grid: NirdizatiGrid<GeneratorArgument> = NirdizatiGrid(rowProvider)
private val hyperParamsContainer: Hlayout =
Executions.getCurrent().desktop.components.first { it.id == HYPER_PARAM_CONT } as Hlayout
private var hyperParameters: MutableMap<ModelParameter, MutableList<Property>> = mutableMapOf()
init {
log.debug("Initializing advanced mode controller")
gridContainer.getChildren<Component>().clear()
rowProvider.fields = grid.fields
grid.generate(parameters
.entries
.map { GeneratorArgument(it.key, it.value) })
gridContainer.appendChild(grid)
grid.fields
.asSequence()
.forEach {
val cont = it.control as CheckBoxGroup
cont.applyToAll(this::generateListener)
}
grid.sclass = "max-height max-width"
grid.hflex = "min"
grid.vflex = "min"
log.debug("Finished grid initialization")
}
/**
* Create listener when to show hyper parameter grid when checkbox is checked
*/
private fun generateListener(checkBox: Checkbox) {
val parameter = checkBox.getValue<ModelParameter>()
if (TrainingController.LEARNER == parameter.type) {
hyperParameters[parameter] = mutableListOf()
}
val handleLearner = { p: ModelParameter, e: CheckEvent ->
if (e.isChecked) {
hyperParameters[p]?.addAll(p.properties)
} else {
hyperParameters[p]?.removeAll(p.properties)
}
}
val handleOther = { p: ModelParameter, e: CheckEvent ->
hyperParameters.values.forEach {
if (e.isChecked) {
it.addAll(p.properties)
} else {
it.removeAll(p.properties)
}
}
}
checkBox.addEventListener(Events.ON_CHECK) { e ->
e as CheckEvent
log.debug("$this value changed, regenerating grid")
when (parameter.type) {
TrainingController.LEARNER -> handleLearner(parameter, e)
else -> handleOther(parameter, e)
}
if (parameter.properties.isNotEmpty()) {
hyperParamsContainer.getChildren<Component>().clear()
hyperParameters.entries.forEach { it.generateGrid() }
}
}
}
/**
* Generate a single grid based on given entry
*/
private fun Map.Entry<ModelParameter, List<Property>>.generateGrid() {
if (value.size < 2) return
log.debug("Key: $key -> value: $value")
val propGrid = NirdizatiGrid(PropertyValueAdapter)
propGrid.setColumns(
listOf(
NirdizatiGrid.ColumnArgument(key.type + "." + key.id, "min"),
NirdizatiGrid.ColumnArgument(flex = "min")
)
)
propGrid.generate(value)
propGrid.vflex = "1"
propGrid.sclass = "hyper-grid"
hyperParamsContainer.appendChild(propGrid)
}
/**
* Is given grid valid
*
* @return is all the data correct in the grid
*/
override fun isValid(): Boolean {
var isValid = grid.validate()
hyperParamsContainer.getChildren<Component>().forEach {
isValid = (it as NirdizatiGrid<*>).validate()
}
return isValid
}
/**
* Gather values from this controller
*
* @return map of collected values
*/
@Suppress("UNCHECKED_CAST")
override fun gatherValues(): Map<String, List<ModelParameter>> {
val gathered = grid.gatherValues()
val hyperParams = mutableMapOf<String, Map<String, Any>>()
hyperParamsContainer.getChildren<Component>().forEach {
it as NirdizatiGrid<*>
hyperParams[it.columns.firstChild.id] = it.gatherValues()
}
hyperParams.forEach { k, v ->
val keys = k.split(".")
if (keys.size > 1) {
val params = gathered[keys[0]] as List<*>
val copy = mutableListOf<ModelParameter>()
params.forEach { param ->
param as ModelParameter
val parameter = param.copy()
if (parameter.id == keys[1]) {
parameter.properties.clear()
v.forEach {
parameter.properties.add(Property(it.key, "", it.value.toString(), -1.0, -1.0))
}
}
copy.add(parameter)
}
gathered[keys[0]] = copy
}
}
return gathered as Map<String, List<ModelParameter>>
}
override fun preDestroy() {
hyperParamsContainer.getChildren<Component>().clear()
}
} | lgpl-3.0 | 9149e2e028fa1acf6e796f7dea127dc7 | 32.747126 | 110 | 0.588656 | 4.544118 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/home/bundles/promotional/EventViewHolder.kt | 1 | 2392 | package cm.aptoide.pt.home.bundles.promotional
import android.view.View
import cm.aptoide.aptoideviews.skeleton.Skeleton
import cm.aptoide.pt.home.bundles.base.EditorialActionBundle
import cm.aptoide.pt.home.bundles.base.HomeBundle
import cm.aptoide.pt.home.bundles.base.HomeEvent
import cm.aptoide.pt.home.bundles.editorial.EditorialHomeEvent
import cm.aptoide.pt.home.bundles.editorial.EditorialViewHolder
import cm.aptoide.pt.networking.image.ImageLoader
import kotlinx.android.synthetic.main.card_event.view.*
import rx.subjects.PublishSubject
class EventViewHolder(val view: View,
val uiEventsListener: PublishSubject<HomeEvent>) :
EditorialViewHolder(view) {
private var skeleton: Skeleton? = null
override fun setBundle(homeBundle: HomeBundle?, position: Int) {
(homeBundle as? EditorialActionBundle)?.let {
if (homeBundle.content == null) {
toggleSkeleton(true)
} else {
toggleSkeleton(false)
itemView.card_title_label_text.text = homeBundle.title
ImageLoader.with(itemView.context)
.load(homeBundle.actionItem.icon, itemView.app_background_image)
itemView.event_title.text = homeBundle.actionItem.title
itemView.setOnClickListener {
uiEventsListener.onNext(
EditorialHomeEvent(homeBundle.actionItem.cardId, homeBundle.actionItem.type,
homeBundle, position, HomeEvent.Type.EDITORIAL))
}
}
}
}
private fun toggleSkeleton(showSkeleton: Boolean) {
if (showSkeleton) {
skeleton?.showSkeleton()
itemView.card_title_label_skeletonview.visibility = View.VISIBLE
itemView.card_title_label.visibility = View.INVISIBLE
itemView.event_title_skeletonview.visibility = View.VISIBLE
itemView.event_title.visibility = View.INVISIBLE
itemView.event_ongoing.visibility = View.INVISIBLE
itemView.event_summary_skeletonview.visibility = View.VISIBLE
} else {
skeleton?.showOriginal()
itemView.card_title_label_skeletonview.visibility = View.INVISIBLE
itemView.card_title_label.visibility = View.VISIBLE
itemView.event_title_skeletonview.visibility = View.INVISIBLE
itemView.event_title.visibility = View.VISIBLE
itemView.event_ongoing.visibility = View.VISIBLE
itemView.event_summary_skeletonview.visibility = View.INVISIBLE
}
}
} | gpl-3.0 | a2388dab7d8d1eac1876ab0bf42f0fb2 | 40.258621 | 90 | 0.734114 | 4.405157 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersFragment.kt | 1 | 14240 | package eu.kanade.tachiyomi.ui.manga.chapter
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Intent
import android.os.Bundle
import android.support.v7.view.ActionMode
import android.view.*
import com.afollestad.materialdialogs.MaterialDialog
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder
import eu.kanade.tachiyomi.ui.base.decoration.DividerItemDecoration
import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment
import eu.kanade.tachiyomi.ui.manga.MangaActivity
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.getCoordinates
import eu.kanade.tachiyomi.util.getResourceDrawable
import eu.kanade.tachiyomi.util.toast
import eu.kanade.tachiyomi.widget.NpaLinearLayoutManager
import kotlinx.android.synthetic.main.fragment_manga_chapters.*
import nucleus.factory.RequiresPresenter
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
@RequiresPresenter(ChaptersPresenter::class)
class ChaptersFragment : BaseRxFragment<ChaptersPresenter>(), ActionMode.Callback, FlexibleViewHolder.OnListItemClickListener {
companion object {
/**
* Creates a new instance of this fragment.
*
* @return a new instance of [ChaptersFragment].
*/
fun newInstance(): ChaptersFragment {
return ChaptersFragment()
}
}
/**
* Adapter containing a list of chapters.
*/
private lateinit var adapter: ChaptersAdapter
/**
* Action mode for multiple selection.
*/
private var actionMode: ActionMode? = null
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_manga_chapters, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Init RecyclerView and adapter
adapter = ChaptersAdapter(this)
recycler.adapter = adapter
recycler.layoutManager = NpaLinearLayoutManager(activity)
recycler.addItemDecoration(DividerItemDecoration(
context.theme.getResourceDrawable(R.attr.divider_drawable)))
recycler.setHasFixedSize(true)
swipe_refresh.setOnRefreshListener { fetchChapters() }
fab.setOnClickListener { v ->
val chapter = presenter.getNextUnreadChapter()
if (chapter != null) {
// Create animation listener
val revealAnimationListener: Animator.AnimatorListener = object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
openChapter(chapter, true)
}
}
// Get coordinates and start animation
val coordinates = fab.getCoordinates()
if (!reveal_view.showRevealEffect(coordinates.x, coordinates.y, revealAnimationListener)) {
openChapter(chapter)
}
} else {
context.toast(R.string.no_next_chapter)
}
}
}
override fun onPause() {
// Stop recycler's scrolling when onPause is called. If the activity is finishing
// the presenter will be destroyed, and it could cause NPE
// https://github.com/inorichi/tachiyomi/issues/159
recycler.stopScroll()
super.onPause()
}
override fun onResume() {
// Check if animation view is visible
if (reveal_view.visibility == View.VISIBLE) {
// Show the unReveal effect
val coordinates = fab.getCoordinates()
reveal_view.hideRevealEffect(coordinates.x, coordinates.y, 1920)
}
super.onResume()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.chapters, menu)
menu.findItem(R.id.action_filter_unread).isChecked = presenter.onlyUnread()
menu.findItem(R.id.action_filter_downloaded).isChecked = presenter.onlyDownloaded()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_display_mode -> showDisplayModeDialog()
R.id.manga_download -> showDownloadDialog()
R.id.action_filter_unread -> {
item.isChecked = !item.isChecked
presenter.setReadFilter(item.isChecked)
}
R.id.action_filter_downloaded -> {
item.isChecked = !item.isChecked
presenter.setDownloadedFilter(item.isChecked)
}
R.id.action_filter_empty -> {
presenter.setReadFilter(false)
presenter.setDownloadedFilter(false)
activity.supportInvalidateOptionsMenu();
}
R.id.action_sort -> presenter.revertSortOrder()
else -> return super.onOptionsItemSelected(item)
}
return true
}
fun onNextManga(manga: Manga) {
// Set initial values
setReadFilter()
setDownloadedFilter()
}
fun onNextChapters(chapters: List<Chapter>) {
// If the list is empty, fetch chapters from source if the conditions are met
// We use presenter chapters instead because they are always unfiltered
if (presenter.chapters.isEmpty())
initialFetchChapters()
destroyActionModeIfNeeded()
adapter.setItems(chapters)
}
private fun initialFetchChapters() {
// Only fetch if this view is from the catalog and it hasn't requested previously
if (isCatalogueManga && !presenter.hasRequested) {
fetchChapters()
}
}
fun fetchChapters() {
swipe_refresh.isRefreshing = true
presenter.fetchChaptersFromSource()
}
fun onFetchChaptersDone() {
swipe_refresh.isRefreshing = false
}
fun onFetchChaptersError(error: Throwable) {
swipe_refresh.isRefreshing = false
context.toast(error.message)
}
val isCatalogueManga: Boolean
get() = (activity as MangaActivity).isCatalogueManga
fun openChapter(chapter: Chapter, hasAnimation: Boolean = false) {
presenter.onOpenChapter(chapter)
val intent = ReaderActivity.newIntent(activity)
if (hasAnimation) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
}
startActivity(intent)
}
private fun showDisplayModeDialog() {
// Get available modes, ids and the selected mode
val modes = listOf(getString(R.string.show_title), getString(R.string.show_chapter_number))
val ids = intArrayOf(Manga.DISPLAY_NAME, Manga.DISPLAY_NUMBER)
val selectedIndex = if (presenter.manga.displayMode == Manga.DISPLAY_NAME) 0 else 1
MaterialDialog.Builder(activity)
.title(R.string.action_display_mode)
.items(modes)
.itemsIds(ids)
.itemsCallbackSingleChoice(selectedIndex) { dialog, itemView, which, text ->
// Save the new display mode
presenter.setDisplayMode(itemView.id)
// Refresh ui
adapter.notifyDataSetChanged()
true
}
.show()
}
private fun showDownloadDialog() {
// Get available modes
val modes = listOf(getString(R.string.download_1), getString(R.string.download_5), getString(R.string.download_10),
getString(R.string.download_unread), getString(R.string.download_all))
MaterialDialog.Builder(activity)
.title(R.string.manga_download)
.negativeText(android.R.string.cancel)
.items(modes)
.itemsCallback { dialog, view, i, charSequence ->
var chapters: MutableList<Chapter> = arrayListOf()
// i = 0: Download 1
// i = 1: Download 5
// i = 2: Download 10
// i = 3: Download unread
// i = 4: Download all
for (chapter in presenter.chapters) {
if (!chapter.isDownloaded) {
if (i == 4 || (i != 4 && !chapter.read)) {
chapters.add(chapter)
}
}
}
if (chapters.size > 0) {
if (!presenter.sortOrder()) {
chapters.reverse()
}
when (i) {
// Set correct chapters size if desired
0 -> chapters = chapters.subList(0, 1)
1 -> {
if (chapters.size >= 5)
chapters = chapters.subList(0, 5)
}
2 -> {
if (chapters.size >= 10)
chapters = chapters.subList(0, 10)
}
}
onDownload(Observable.from(chapters))
}
}
.show()
}
fun onChapterStatusChange(download: Download) {
getHolder(download.chapter)?.notifyStatus(download.status)
}
private fun getHolder(chapter: Chapter): ChaptersHolder? {
return recycler.findViewHolderForItemId(chapter.id) as? ChaptersHolder
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.chapter_selection, menu)
adapter.mode = FlexibleAdapter.MODE_MULTI
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_select_all -> onSelectAll()
R.id.action_mark_as_read -> onMarkAsRead(getSelectedChapters())
R.id.action_mark_as_unread -> onMarkAsUnread(getSelectedChapters())
R.id.action_download -> onDownload(getSelectedChapters())
R.id.action_delete -> onDelete(getSelectedChapters())
else -> return false
}
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
adapter.mode = FlexibleAdapter.MODE_SINGLE
adapter.clearSelection()
actionMode = null
}
fun getSelectedChapters(): Observable<Chapter> {
val chapters = adapter.selectedItems.map { adapter.getItem(it) }
return Observable.from(chapters)
}
fun destroyActionModeIfNeeded() {
actionMode?.finish()
}
protected fun onSelectAll() {
adapter.selectAll()
setContextTitle(adapter.selectedItemCount)
}
fun onMarkAsRead(chapters: Observable<Chapter>) {
presenter.markChaptersRead(chapters, true)
}
fun onMarkAsUnread(chapters: Observable<Chapter>) {
presenter.markChaptersRead(chapters, false)
}
fun onMarkPreviousAsRead(chapter: Chapter) {
presenter.markPreviousChaptersAsRead(chapter)
}
fun onDownload(chapters: Observable<Chapter>) {
DownloadService.start(activity)
val observable = chapters.doOnCompleted { adapter.notifyDataSetChanged() }
presenter.downloadChapters(observable)
destroyActionModeIfNeeded()
}
fun onDelete(chapters: Observable<Chapter>) {
val size = adapter.selectedItemCount
val dialog = MaterialDialog.Builder(activity)
.title(R.string.deleting)
.progress(false, size, true)
.cancelable(false)
.show()
val observable = chapters
.concatMap { chapter ->
presenter.deleteChapter(chapter)
Observable.just(chapter)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { chapter ->
dialog.incrementProgress(1)
chapter.status = Download.NOT_DOWNLOADED
}
.doOnCompleted { adapter.notifyDataSetChanged() }
.doAfterTerminate { dialog.dismiss() }
presenter.deleteChapters(observable)
destroyActionModeIfNeeded()
}
override fun onListItemClick(position: Int): Boolean {
val item = adapter.getItem(position) ?: return false
if (actionMode != null && adapter.mode == FlexibleAdapter.MODE_MULTI) {
toggleSelection(position)
return true
} else {
openChapter(item)
return false
}
}
override fun onListItemLongClick(position: Int) {
if (actionMode == null)
actionMode = baseActivity.startSupportActionMode(this)
toggleSelection(position)
}
private fun toggleSelection(position: Int) {
adapter.toggleSelection(position, false)
val count = adapter.selectedItemCount
if (count == 0) {
actionMode?.finish()
} else {
setContextTitle(count)
actionMode?.invalidate()
}
}
private fun setContextTitle(count: Int) {
actionMode?.title = getString(R.string.label_selected, count)
}
fun setReadFilter() {
this.activity.supportInvalidateOptionsMenu()
}
fun setDownloadedFilter() {
this.activity.supportInvalidateOptionsMenu()
}
}
| apache-2.0 | 718fbc58317240c73b97b22e2615fd88 | 34.511222 | 127 | 0.604213 | 5.15009 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/ui/download/PhotoFragment.kt | 1 | 10824 | package com.nutrition.express.ui.download
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.ActionMode
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.facebook.drawee.backends.pipeline.Fresco
import com.nutrition.express.R
import com.nutrition.express.application.TumbApp.Companion.app
import com.nutrition.express.common.CommonRVAdapter
import com.nutrition.express.common.CommonViewHolder
import com.nutrition.express.databinding.FragmentDownloadPhotoBinding
import com.nutrition.express.databinding.ItemDownloadPhotoBinding
import com.nutrition.express.imageviewer.PhotoViewActivity
import com.nutrition.express.model.data.bean.LocalPhoto
import com.nutrition.express.util.FileUtils.deleteFile
import com.nutrition.express.util.FileUtils.imageDir
import com.nutrition.express.util.FileUtils.publicImageDir
import com.nutrition.express.util.dp2Pixels
import com.nutrition.express.util.getBoolean
import com.nutrition.express.util.putBoolean
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
class PhotoFragment : Fragment() {
private val SHOW_USER_PHOTO = "SUP"
private val halfWidth = app.width / 2
private var adapter: CommonRVAdapter? = null
private var binding: FragmentDownloadPhotoBinding? = null
private var userPhoto: ArrayList<LocalPhoto> = ArrayList()
private var allPhoto: ArrayList<LocalPhoto> = ArrayList()
private var photoList: ArrayList<LocalPhoto> = ArrayList()
private var showUserPhoto = false
private var isChoiceState = false
private var checkedCount = 0
private var actionMode: ActionMode? = null
private val callback: ActionMode.Callback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.menu_multi_choice, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.delete -> {
showDeleteDialog()
return true
}
R.id.select_all -> {
checkAllPhotos()
adapter?.notifyDataSetChanged()
return true
}
}
return false
}
override fun onDestroyActionMode(mode: ActionMode) {
finishMultiChoice()
adapter?.notifyDataSetChanged()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
showUserPhoto = getBoolean(SHOW_USER_PHOTO, false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = FragmentDownloadPhotoBinding.inflate(inflater, container, false)
binding.recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (newState == RecyclerView.SCROLL_STATE_IDLE || newState == RecyclerView.SCROLL_STATE_DRAGGING) {
Fresco.getImagePipeline().resume()
} else {
Fresco.getImagePipeline().pause()
}
}
})
if (showUserPhoto) {
initPhotoDataUser()
} else {
initPhotoDataAll()
}
val adapter = CommonRVAdapter.adapter {
addViewType(LocalPhoto::class, R.layout.item_download_photo) { PhotoViewHolder(it) }
}
adapter.resetData(photoList.toTypedArray(), false)
binding.recyclerView.adapter = adapter
this.binding = binding
this.adapter = adapter
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
adapter = null
binding = null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_download_photo, menu)
val menuItem = menu.findItem(R.id.show_user_photo)
menuItem.isChecked = showUserPhoto
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.show_user_photo) {
item.isChecked = !item.isChecked
showUserPhoto = item.isChecked
if (showUserPhoto) {
initPhotoDataUser()
} else {
initPhotoDataAll()
}
adapter?.resetData(photoList.toTypedArray(), false)
putBoolean(SHOW_USER_PHOTO, showUserPhoto)
return true
}
return super.onOptionsItemSelected(item)
}
private fun initPhotoDataUser() {
if (userPhoto.isEmpty()) {
val userPhotoDir = imageDir
if (userPhotoDir.isDirectory) {
getPhotoFile(userPhotoDir, userPhoto)
sortPhotoData(userPhoto)
}
}
photoList = userPhoto
}
private fun initPhotoDataAll() {
if (allPhoto.isEmpty()) {
allPhoto = ArrayList()
val publicPhotoDir = publicImageDir
if (publicPhotoDir.isDirectory) {
getPhotoFile(publicPhotoDir, allPhoto)
sortPhotoData(allPhoto)
}
}
photoList = allPhoto
}
private fun getPhotoFile(dir: File, list: MutableList<LocalPhoto>) {
val files = dir.listFiles() ?: return
var tmp: LocalPhoto
for (file in files) {
if (file.isDirectory) {
getPhotoFile(file, list)
} else {
tmp = LocalPhoto(file)
if (tmp.isValid) {
list.add(tmp)
}
}
}
}
private fun sortPhotoData(photos: MutableList<LocalPhoto>) {
photos.sortWith(Comparator { o1, o2 ->
val x = o1.file.lastModified()
val y = o2.file.lastModified()
if (x < y) 1 else if (x == y) 0 else -1
})
}
private fun startMultiChoice() {
photoList.forEach { it.isChecked = false }
actionMode = (activity as DownloadedActivity).startSupportActionMode(callback)
checkedCount = 0
isChoiceState = true
}
private fun finishMultiChoice() {
actionMode?.finish()
actionMode = null
isChoiceState = false
}
private fun onItemChecked(localPhoto: LocalPhoto) {
localPhoto.isChecked = !localPhoto.isChecked
if (localPhoto.isChecked) {
checkedCount++
} else {
checkedCount--
}
actionMode?.title = checkedCount.toString()
}
private fun deleteCheckedPhotos() {
userPhoto.removeAll {
if (it.isChecked) {
deleteFile(it.file)
return@removeAll true
}
return@removeAll false
}
allPhoto.removeAll {
if (it.isChecked) {
deleteFile(it.file)
return@removeAll true
}
return@removeAll false
}
adapter?.resetData(photoList.toTypedArray(), false)
}
private fun checkAllPhotos() {
photoList.forEach{ it.isChecked = true }
checkedCount = photoList.size
actionMode?.title = checkedCount.toString()
adapter?.notifyDataSetChanged()
}
private fun showDeleteDialog() {
context?.let {
AlertDialog.Builder(it).run {
setPositiveButton(R.string.delete_positive) {
dialog, which ->
deleteCheckedPhotos()
finishMultiChoice()
}
setNegativeButton(R.string.pic_cancel, null)
setTitle(R.string.download_photo_delete_title)
show()
}
}
}
fun scrollToTop() {
binding?.recyclerView?.scrollToPosition(0)
}
inner class PhotoViewHolder constructor(view: View) : CommonViewHolder<LocalPhoto>(view) {
private val binding = ItemDownloadPhotoBinding.bind(view)
private val defaultWidth = halfWidth - dp2Pixels(view.context, 8)
private lateinit var photo: LocalPhoto
init {
binding.photoView.setOnClickListener {
if (isChoiceState) {
onItemChecked(photo)
if (photo.isChecked) {
binding.checkView.visibility = View.VISIBLE
} else {
binding.checkView.visibility = View.GONE
}
return@setOnClickListener
}
val intent = Intent(activity, PhotoViewActivity::class.java)
val options: ActivityOptions = ActivityOptions.makeSceneTransitionAnimation(
activity, binding.photoView, photo.uri.path)
intent.putExtra("transition_name", photo.uri.path)
intent.putExtra("photo_source", photo.uri)
startActivity(intent, options.toBundle())
}
binding.photoView.setOnLongClickListener {
if (actionMode != null) {
return@setOnLongClickListener true
}
startMultiChoice()
onItemChecked(photo)
binding.checkView.visibility = View.VISIBLE
return@setOnLongClickListener true
}
}
override fun bindView(localPhoto: LocalPhoto) {
photo = localPhoto
val height: Int = localPhoto.height * defaultWidth / localPhoto.width
val params: ViewGroup.LayoutParams = binding.photoView.layoutParams ?: ViewGroup.LayoutParams(defaultWidth, height)
params.width = defaultWidth
params.height = height
binding.photoView.layoutParams = params
binding.photoView.setImageURI(localPhoto.uri, context)
if (isChoiceState && photo.isChecked) {
binding.checkView.visibility = View.VISIBLE
} else {
binding.checkView.visibility = View.GONE
}
}
}
} | apache-2.0 | 7395cbee33878200b55b0ba5f5395395 | 34.491803 | 127 | 0.607446 | 5.086466 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/parsing/AtomTypes/XVariableAtom.kt | 1 | 2051 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[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.wildplot.android.parsing.AtomTypes
import com.wildplot.android.parsing.Atom.AtomType
import com.wildplot.android.parsing.ExpressionFormatException
import com.wildplot.android.parsing.TopLevelParser
import com.wildplot.android.parsing.TreeElement
class XVariableAtom(private val parser: TopLevelParser) : TreeElement {
private val atomType = AtomType.VARIABLE
@get:Throws(ExpressionFormatException::class)
override val value: Double
get() = if (atomType !== AtomType.INVALID) {
parser.x
} else {
throw ExpressionFormatException("Number is Invalid, cannot parse")
}
override val isVariable: Boolean
get() = true
}
| gpl-3.0 | b829faed6475575f01067064fcfff383 | 55.972222 | 90 | 0.50902 | 5.843305 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/BackupManagerTest.kt | 1 | 4264 | /*
* 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.anki
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.libanki.utils.Time
import com.ichi2.testutils.MockTime
import com.ichi2.utils.StrictMock.Companion.strictMock
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.*
import org.mockito.kotlin.any
import org.mockito.kotlin.whenever
import java.io.File
@RunWith(AndroidJUnit4::class)
open class BackupManagerTest {
@Test
fun failsIfNoBackupsAllowed() {
// arrange
val bm = passingBackupManagerSpy
doReturn(true).whenever(bm).hasDisabledBackups(any())
// act
val performBackupResult = performBackup(bm)
// assert
assertThat("should fail if backups are disabled", performBackupResult, equalTo(false))
verify(bm, times(1)).performBackupInBackground(anyString(), anyInt(), any())
verify(bm, times(1)).hasDisabledBackups(any())
verifyNoMoreInteractions(bm)
}
/** Meta test: ensuring passingBackupManagerSpy passes */
@Test
fun testPassingSpy() {
val bm = passingBackupManagerSpy
val result = performBackup(bm)
verify(bm, times(1)).performBackupInNewThread(any(), any())
assertThat("PerformBackup should pass", result, equalTo(true))
}
@Test
fun noBackupPerformedIfNoBackupNecessary() {
val bm = passingBackupManagerSpy
doReturn(true).whenever(bm).isBackupUnnecessary(any(), any())
val result = performBackup(bm)
assertThat("should fail if backups not necessary", result, equalTo(false))
verify(bm, times(1)).isBackupUnnecessary(any(), any())
}
@Test
fun noBackupPerformedIfBackupAlreadyExists() {
val file = strictMock(File::class.java)
doReturn(true).whenever(file).exists()
val bm = getPassingBackupManagerSpy(file)
val result = performBackup(bm)
assertThat("should fail if backups exists", result, equalTo(false))
}
@Test
fun noBackupPerformedIfCollectionTooSmall() {
val bm = passingBackupManagerSpy
doReturn(true).whenever(bm).collectionIsTooSmallToBeValid(any())
val result = performBackup(bm)
assertThat("should fail if collection too small", result, equalTo(false))
}
private fun performBackup(bm: BackupManager, time: Time = MockTime(100000000)): Boolean {
return bm.performBackupInBackground("/AnkiDroid/", 100, time)
}
/** Returns a spy of BackupManager which would pass */
private val passingBackupManagerSpy: BackupManager
get() = getPassingBackupManagerSpy(null)
/** Returns a spy of BackupManager which would pass */
private fun getPassingBackupManagerSpy(backupFileMock: File?): BackupManager {
val spy = spy(BackupManager.createInstance())
doReturn(true).whenever(spy).hasFreeDiscSpace(any())
doReturn(false).whenever(spy).collectionIsTooSmallToBeValid(any())
doNothing().whenever(spy).performBackupInNewThread(any(), any())
doReturn(null).whenever(spy).getLastBackupDate(any())
val f = backupFileMock ?: this.backupFileMock
doReturn(f).whenever(spy).getBackupFile(any(), any())
return spy
}
// strict mock
private val backupFileMock: File
get() {
val f = strictMock(File::class.java)
doReturn(false).whenever(f).exists()
return f
}
}
| gpl-3.0 | acfefa1d7a710f644e454c3d351d6f0c | 33.387097 | 94 | 0.69348 | 4.359918 | false | true | false | false |
Samourai-Wallet/samourai-wallet-android | app/src/main/java/com/samourai/wallet/tx/TxDetailsActivity.kt | 1 | 15517 | package com.samourai.wallet.tx
import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.transition.AutoTransition
import android.transition.TransitionManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.samourai.wallet.MainActivity2
import com.samourai.wallet.R
import com.samourai.wallet.SamouraiActivity
import com.samourai.wallet.SamouraiWallet
import com.samourai.wallet.api.APIFactory
import com.samourai.wallet.api.Tx
import com.samourai.wallet.bip47.BIP47Meta
import com.samourai.wallet.bip47.paynym.WebUtil
import com.samourai.wallet.send.RBFUtil
import com.samourai.wallet.send.SendActivity
import com.samourai.wallet.send.boost.CPFPTask
import com.samourai.wallet.send.boost.RBFTask
import com.samourai.wallet.util.DateUtil
import com.samourai.wallet.util.FormatsUtil
import com.samourai.wallet.widgets.CircleImageView
import com.squareup.picasso.Picasso
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.*
import org.bitcoinj.core.Coin
import org.json.JSONException
import org.json.JSONObject
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
class TxDetailsActivity : SamouraiActivity() {
private var payNymAvatar: CircleImageView? = null
private var payNymUsername: TextView? = null
private var amount: TextView? = null
private var txStatus: TextView? = null
private var txId: TextView? = null
private var txDate: TextView? = null
private var bottomButton: MaterialButton? = null
private var minerFee: TextView? = null
private var minerFeeRate: TextView? = null
private var tx: Tx? = null
private var BTCDisplayAmount: String? = null
private var SatDisplayAmount: String? = null
private var paynymDisplayName: String? = null
private var rbfTask: RBFTask? = null
private var progressBar: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tx)
setSupportActionBar(findViewById(R.id.toolbar))
if (intent.hasExtra("TX")) {
try {
val TxJsonObject = JSONObject(intent.getStringExtra("TX"))
tx = Tx(TxJsonObject)
} catch (e: JSONException) {
e.printStackTrace()
}
}
payNymUsername = findViewById(R.id.tx_paynym_username)
amount = findViewById(R.id.tx_amount)
payNymAvatar = findViewById(R.id.img_paynym_avatar)
txId = findViewById(R.id.transaction_id)
txStatus = findViewById(R.id.tx_status)
txDate = findViewById(R.id.tx_date)
bottomButton = findViewById(R.id.btn_bottom_button)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
progressBar = findViewById(R.id.progressBar)
minerFee = findViewById(R.id.tx_miner_fee_paid)
minerFeeRate = findViewById(R.id.tx_miner_fee_rate)
amount?.setOnClickListener { toggleUnits() }
setTx()
bottomButton?.setOnClickListener {
if (isBoostingAvailable) {
doBoosting()
} else {
refundOrPayAgain()
}
}
txId?.setOnClickListener { view: View ->
MaterialAlertDialogBuilder(this)
.setTitle(R.string.app_name)
.setMessage(R.string.txid_to_clipboard)
.setCancelable(false)
.setPositiveButton(R.string.yes) { _: DialogInterface?, _: Int ->
val clipboard = [email protected](CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("tx id", (view as TextView).text)
clipboard.setPrimaryClip(clip)
Toast.makeText(this@TxDetailsActivity, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show()
}.setNegativeButton(R.string.no) { _: DialogInterface?, _: Int -> }.show()
}
}
private fun refundOrPayAgain() {
val intent = Intent(this, SendActivity::class.java)
intent.putExtra("pcode", tx!!.paymentCode)
if (!isSpend) {
intent.putExtra("amount", tx!!.amount)
}
startActivity(intent)
}
private fun setTx() {
calculateBTCDisplayAmount(tx!!.amount.toLong())
calculateSatoshiDisplayAmount(tx!!.amount.toLong())
amount?.text = BTCDisplayAmount
bottomButton!!.visibility = View.GONE
if (tx!!.confirmations <= 3) {
txStatus!!.setTextColor(ContextCompat.getColor(this, R.color.tx_broadcast_offline_bg))
val txConfirmation = getString(R.string.unconfirmed) +
" (" +
tx!!.confirmations +
"/3)"
txStatus!!.text = txConfirmation
}
if (tx!!.confirmations > 3) {
val txConfirmation = tx!!.confirmations.toString() +
" " +
getString(R.string.confirmation)
txStatus!!.setTextColor(ContextCompat.getColor(this, R.color.text_secondary))
txStatus!!.text = txConfirmation
bottomButton?.visibility = View.GONE;
}
txId!!.text = tx!!.hash
txDate!!.text = DateUtil.getInstance(this).formatted(tx!!.ts)
if (tx!!.paymentCode != null) {
bottomButton!!.visibility = View.VISIBLE
paynymDisplayName = BIP47Meta.getInstance().getDisplayLabel(tx!!.paymentCode)
showPaynym()
if (isSpend) {
bottomButton!!.setText(R.string.pay_again)
} else {
bottomButton!!.setText(R.string.refund)
}
}
if (isBoostingAvailable) {
bottomButton!!.visibility = View.VISIBLE
bottomButton!!.setText(R.string.boost_transaction_fee)
}
fetchTxDetails()
}
private fun doBoosting() {
val message = getString(R.string.options_unconfirmed_tx)
if (isRBFPossible) {
val builder = MaterialAlertDialogBuilder(this)
builder.setTitle(R.string.app_name)
builder.setMessage(message)
builder.setCancelable(true)
builder.setPositiveButton(R.string.options_bump_fee) { dialog: DialogInterface?, whichButton: Int -> RBFBoost() }
builder.setNegativeButton(R.string.cancel) { dialog: DialogInterface, whichButton: Int -> dialog.dismiss() }
builder.create().show()
return
} else {
if (isCPFPPossible) {
val builder = MaterialAlertDialogBuilder(this@TxDetailsActivity)
builder.setTitle(R.string.app_name)
builder.setMessage(message)
builder.setCancelable(true)
builder.setPositiveButton(R.string.options_bump_fee) { dialog: DialogInterface?, whichButton: Int -> CPFBoost() }
builder.setNegativeButton(R.string.cancel) { dialog: DialogInterface, whichButton: Int -> dialog.dismiss() }
builder.create().show()
}
}
}
private fun CPFBoost() {
progressBar?.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
val cpfp = CPFPTask(applicationContext, tx!!.hash)
try {
val message = cpfp.checkCPFP()
withContext(Dispatchers.Main) {
val dlg: MaterialAlertDialogBuilder= MaterialAlertDialogBuilder(this@TxDetailsActivity)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok) { _, _ ->
doCPFPSpend(cpfp)
}.setNegativeButton(R.string.cancel) { _, _ ->
cpfp.reset()
}
if (!isFinishing) {
dlg.show()
}
}
} catch (e: CPFPTask.CPFPException) {
withContext(Dispatchers.Main) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
e.printStackTrace()
withContext(Dispatchers.Main) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_SHORT).show()
}
}
}
.invokeOnCompletion {
if(it != null){
}
runBlocking {
withContext(Dispatchers.Main){
progressBar?.visibility = View.GONE
}
}
}
}
private fun doCPFPSpend(cpfpTaskKt: CPFPTask) {
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
progressBar?.visibility = View.VISIBLE
}
try {
cpfpTaskKt.doCPFP()
} catch (ex: Exception) {
throw CancellationException(ex.message)
}
}.invokeOnCompletion {
runBlocking {
withContext(Dispatchers.Main){
progressBar?.visibility = View.GONE
if (it != null) {
Toast.makeText(this@TxDetailsActivity, it.message, Toast.LENGTH_SHORT).show()
} else {
bottomButton?.visibility = View.GONE
Toast.makeText(this@TxDetailsActivity, R.string.cpfp_spent, Toast.LENGTH_SHORT).show()
val intent = Intent(this@TxDetailsActivity, MainActivity2::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
[email protected](intent)
}
}
}
}
}
private fun RBFBoost() {
if (rbfTask == null || rbfTask!!.status == AsyncTask.Status.FINISHED) {
rbfTask = RBFTask(this)
rbfTask!!.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx!!.hash)
}
}
private val isBoostingAvailable: Boolean
private get() = tx!!.confirmations < 1
private val isSpend: Boolean
private get() = tx!!.amount < 0
private fun fetchTxDetails() {
toggleProgress(View.VISIBLE)
makeTxNetworkRequest()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<JSONObject> {
override fun onSubscribe(d: Disposable) {}
override fun onNext(jsonObject: JSONObject) {
toggleProgress(View.INVISIBLE)
try {
setFeeInfo(jsonObject)
} catch (e: JSONException) {
e.printStackTrace()
}
}
override fun onError(e: Throwable) {
e.printStackTrace()
toggleProgress(View.INVISIBLE)
}
override fun onComplete() {}
})
}
/**
* @param jsonObject
* @throws JSONException
*/
@Throws(JSONException::class)
private fun setFeeInfo(jsonObject: JSONObject) {
if (jsonObject.has("fees")) {
minerFee!!.text = jsonObject.getString("fees") + " sats"
}
if (jsonObject.has("feerate")) {
minerFeeRate!!.text = jsonObject.getString("vfeerate") + " sats"
}
}
private fun makeTxNetworkRequest(): Observable<JSONObject> {
return Observable.create { emitter: ObservableEmitter<JSONObject> -> emitter.onNext(APIFactory.getInstance(this@TxDetailsActivity).getTxInfo(tx!!.hash)) }
}
private fun calculateBTCDisplayAmount(value: Long) {
BTCDisplayAmount = FormatsUtil.formatBTC(value)
}
private fun toggleProgress(Visibility: Int) {
progressBar!!.visibility = Visibility
}
private fun toggleUnits() {
TransitionManager.beginDelayedTransition(amount!!.rootView.rootView as ViewGroup, AutoTransition())
if (amount?.text?.contains("BTC")!!) {
amount!!.text = SatDisplayAmount
} else {
amount!!.text = BTCDisplayAmount
}
}
private fun calculateSatoshiDisplayAmount(value: Long) {
SatDisplayAmount = FormatsUtil.formatSats(value)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_item_block_explore -> {
doExplorerView()
}
android.R.id.home -> {
finish()
}
}
return super.onOptionsItemSelected(item)
}
/**
* Opens external BlockExplorer
*/
private fun doExplorerView() {
var blockExplorer = "https://m.oxt.me/transaction/"
if (SamouraiWallet.getInstance().isTestNet) {
blockExplorer = "https://blockstream.info/testnet/"
}
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(blockExplorer + tx!!.hash))
startActivity(browserIntent)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.tx_details_menu, menu)
return super.onCreateOptionsMenu(menu)
}
private fun showPaynym() {
TransitionManager.beginDelayedTransition(payNymAvatar!!.rootView.rootView as ViewGroup, AutoTransition())
payNymUsername!!.visibility = View.VISIBLE
payNymAvatar!!.visibility = View.VISIBLE
payNymUsername!!.text = paynymDisplayName
Picasso.get()
.load(WebUtil.PAYNYM_API + tx!!.paymentCode + "/avatar")
.into(payNymAvatar)
}
/***
* checks tx can be boosted using
* Replace-by-fee method
* @return boolean
*/
private val isRBFPossible: Boolean
private get() = tx!!.confirmations < 1 && tx!!.amount < 0.0 && RBFUtil.getInstance().contains(tx!!.hash)
/***
* checks tx can be boosted using
* child pays for parent method
* @return boolean
*/
private val isCPFPPossible: Boolean
private get() {
val a = tx!!.confirmations < 1 && tx!!.amount >= 0.0
val b = tx!!.confirmations < 1 && tx!!.amount < 0.0
return a || b
}
companion object {
private const val TAG = "TxDetailsActivity"
}
} | unlicense | b0c01ed9238697bc9b5c2a71800ff8c8 | 37.98995 | 162 | 0.595218 | 4.709256 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/note_discussion/NoteDiscussionForm.kt | 1 | 7425 | package de.westnordost.streetcomplete.quests.note_discussion
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.format.DateUtils
import android.text.format.DateUtils.MINUTE_IN_MILLIS
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.fragment.app.add
import androidx.fragment.app.commit
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osmnotes.NoteComment
import de.westnordost.streetcomplete.data.osmnotes.edits.NotesWithEditsSource
import de.westnordost.streetcomplete.data.osmnotes.NotesModule
import de.westnordost.streetcomplete.data.quest.OsmNoteQuestKey
import de.westnordost.streetcomplete.data.user.User
import de.westnordost.streetcomplete.databinding.QuestNoteDiscussionContentBinding
import de.westnordost.streetcomplete.databinding.QuestNoteDiscussionItemBinding
import de.westnordost.streetcomplete.databinding.QuestNoteDiscussionItemsBinding
import de.westnordost.streetcomplete.ktx.createBitmap
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.util.TextChangedWatcher
import de.westnordost.streetcomplete.view.CircularOutlineProvider
import de.westnordost.streetcomplete.view.ListAdapter
import de.westnordost.streetcomplete.view.RoundRectOutlineProvider
import java.io.File
import java.time.Instant
import javax.inject.Inject
class NoteDiscussionForm : AbstractQuestFormAnswerFragment<NoteAnswer>() {
override val contentLayoutResId = R.layout.quest_note_discussion_content
private val binding by contentViewBinding(QuestNoteDiscussionContentBinding::bind)
override val defaultExpanded = false
private lateinit var anonAvatar: Bitmap
@Inject internal lateinit var noteSource: NotesWithEditsSource
private val attachPhotoFragment get() =
childFragmentManager.findFragmentById(R.id.attachPhotoFragment) as? AttachPhotoFragment
private val noteText: String get() = binding.noteInput.text?.toString().orEmpty().trim()
override val buttonPanelAnswers = listOf(
AnswerItem(R.string.quest_noteDiscussion_no) { skipQuest() }
)
init {
Injector.applicationComponent.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.noteInput.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() })
otherAnswersButton?.visibility = View.GONE
anonAvatar = requireContext().getDrawable(R.drawable.ic_osm_anon_avatar)!!.createBitmap()
val osmNoteQuestKey = questKey as OsmNoteQuestKey
inflateNoteDiscussion(noteSource.get(osmNoteQuestKey.noteId)!!.comments)
if (savedInstanceState == null) {
childFragmentManager.commit { add<AttachPhotoFragment>(R.id.attachPhotoFragment) }
}
}
private fun inflateNoteDiscussion(comments: List<NoteComment>) {
val discussionView = QuestNoteDiscussionItemsBinding.inflate(layoutInflater, scrollViewChild, false).root
discussionView.isNestedScrollingEnabled = false
discussionView.layoutManager = LinearLayoutManager(
context,
RecyclerView.VERTICAL,
false
)
discussionView.adapter = NoteCommentListAdapter(comments)
scrollViewChild.addView(discussionView, 0)
}
override fun onClickOk() {
applyAnswer(NoteAnswer(noteText, attachPhotoFragment?.imagePaths.orEmpty()))
}
override fun onDiscard() {
attachPhotoFragment?.deleteImages()
}
override fun isRejectingClose(): Boolean {
val f = attachPhotoFragment
val hasPhotos = f != null && f.imagePaths.isNotEmpty()
return hasPhotos || noteText.isNotEmpty()
}
private inner class NoteCommentListAdapter(list: List<NoteComment>) : ListAdapter<NoteComment>(list) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<NoteComment> {
return NoteCommentViewHolder(
QuestNoteDiscussionItemBinding.inflate(layoutInflater, parent, false)
)
}
}
private inner class NoteCommentViewHolder(private val itemBinding: QuestNoteDiscussionItemBinding) :
ListAdapter.ViewHolder<NoteComment>(itemBinding) {
init {
val cornerRadius = resources.getDimension(R.dimen.speech_bubble_rounded_corner_radius)
val margin = resources.getDimensionPixelSize(R.dimen.horizontal_speech_bubble_margin)
val marginStart = -resources.getDimensionPixelSize(R.dimen.quest_form_speech_bubble_top_margin)
itemBinding.commentStatusText.outlineProvider = RoundRectOutlineProvider(cornerRadius)
val isRTL = itemView.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL
val marginLeft = if (isRTL) 0 else marginStart
val marginRight = if (isRTL) marginStart else 0
itemBinding.commentBubble.outlineProvider = RoundRectOutlineProvider(
cornerRadius, marginLeft, margin, marginRight, margin
)
itemBinding.commentAvatarImageContainer.outlineProvider = CircularOutlineProvider
}
override fun onBind(comment: NoteComment) {
val dateDescription = DateUtils.getRelativeTimeSpanString(comment.timestamp, Instant.now().toEpochMilli(), MINUTE_IN_MILLIS)
val userName = if (comment.user != null) comment.user.displayName else getString(R.string.quest_noteDiscussion_anonymous)
val commentActionResourceId = comment.action.actionResourceId
val hasNoteAction = commentActionResourceId != 0
itemBinding.commentStatusText.isGone = !hasNoteAction
if (hasNoteAction) {
itemBinding.commentStatusText.text = getString(commentActionResourceId, userName, dateDescription)
}
val hasComment = comment.text?.isNotEmpty() == true
itemBinding.commentView.isGone = !hasComment
if (hasComment) {
itemBinding.commentText.text = comment.text
itemBinding.commentInfoText.text = getString(R.string.quest_noteDiscussion_comment2, userName, dateDescription)
val bitmap = comment.user?.avatar ?: anonAvatar
itemBinding.commentAvatarImage.setImageBitmap(bitmap)
}
}
private val User.avatar: Bitmap? get() {
val cacheDir = NotesModule.getAvatarsCacheDirectory(requireContext())
val file = File(cacheDir.toString() + File.separator + id)
return if (file.exists()) BitmapFactory.decodeFile(file.path) else null
}
private val NoteComment.Action.actionResourceId get() = when (this) {
NoteComment.Action.CLOSED -> R.string.quest_noteDiscussion_closed2
NoteComment.Action.REOPENED -> R.string.quest_noteDiscussion_reopen2
NoteComment.Action.HIDDEN -> R.string.quest_noteDiscussion_hide2
else -> 0
}
}
override fun isFormComplete(): Boolean = noteText.isNotEmpty()
}
| gpl-3.0 | fb16bda6222bd242794d7d67589c021c | 42.934911 | 136 | 0.73697 | 5.082136 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-client-javafx/src/com/hendraanggrian/openpss/ui/wage/WageReaders.kt | 1 | 2665 | package com.hendraanggrian.openpss.ui.wage
import com.google.common.collect.LinkedHashMultimap
import java.io.File
import javafx.collections.ObservableList
import javafx.stage.FileChooser
import ktfx.collections.toObservableList
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.joda.time.DateTime
import org.joda.time.LocalDate
import org.joda.time.LocalTime
/**
* Compatible with e Clocking fingerprint reader.
* Tested name: `2.1.015`.
*/
object EClockingReader : WageReader("e Clocking", "*.xlsx", {
val multimap = LinkedHashMultimap.create<Attendee, DateTime>()
inputStream().use { stream ->
XSSFWorkbook(stream).use { workbook ->
workbook.getSheetAt(1).iterator().asSequence().drop(5).forEach { row ->
val dept = row.getCell(1).stringCellValue
val name = row.getCell(2).stringCellValue
val no = row.getCell(3).numericCellValue.toInt()
val date = LocalDate.fromDateFields(row.getCell(4).dateCellValue)
multimap.putAll(Attendee(no, name, dept), (6 until 17)
.map { row.getCell(it) }
.filter { it.cellType == CellType.NUMERIC }
.map { date.toDateTime(LocalTime.fromDateFields(it.dateCellValue)) })
}
}
}
multimap.keySet().map { attendee ->
attendee.attendances.addAllRevertible(multimap.get(attendee))
attendee
}
})
object TestReader : WageReader("Test", "*.*", {
listOf(
Attendee(1, "Without role"),
Attendee(2, "With role", "Admin")
)
})
/** A file readers that generates actions of [Attendee] given input file. */
sealed class WageReader(
/** Identifier of a reader. */
val name: String,
/** Expected file extension for [FileChooser.ExtensionFilter]. */
val extension: String,
/**
* The reading process is executed in background thread.
* During its long operation, exception throwing may happen in [read].
*/
private val internalRead: suspend File.() -> Collection<Attendee>
) {
@Throws(Exception::class)
suspend fun read(file: File): Collection<Attendee> = internalRead(file)
override fun toString(): String = name
companion object {
private inline val readers: List<WageReader>
get() = listOf(
EClockingReader,
TestReader
)
fun listAll(): ObservableList<WageReader> = readers.toObservableList()
fun of(name: String): WageReader =
readers.singleOrNull { it.name == name } ?: EClockingReader
}
}
| apache-2.0 | 8a92dd7de1d925ff23fbebf21887a646 | 31.901235 | 89 | 0.643902 | 4.250399 | false | false | false | false |
aemare/Spectrum | src/io/aemare/agents/Agents.kt | 1 | 2485 | package io.aemare.agents
import com.skype.SkypeException
import io.aemare.Constants
import java.io.BufferedReader
import java.io.FileReader
import java.util.*
import java.sql.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
object Agents {
var agents: ArrayList<String> = ArrayList()
val executor = Executors.newScheduledThreadPool(1)
val messages: ArrayList<String> = ArrayList()
fun run() {
executor.scheduleAtFixedRate({
try {
Class.forName("com.mysql.jdbc.Driver")
val query: String = "SELECT `username` FROM `agents` WHERE `status` = 1"
val url = "jdbc:mysql://${Constants.SQL_SERVER}:${Constants.SQL_PORT}/${Constants.SQL_DB}"
val conn = DriverManager.getConnection(url, Constants.SQL_USER, Constants.SQL_PASSWORD)
val stmt = conn.createStatement()
val rs: ResultSet
rs = stmt.executeQuery(query)
while (rs.next()) {
val username = rs.getString("username")
if (!agents.contains(username)) {
agents.add(username)
println(username)
}
}
conn.close()
} catch (ex: Exception) {
ex.printStackTrace()
}
}, 0, 1, TimeUnit.SECONDS)
val file = BufferedReader(FileReader("data/lines.txt"))
file.lines().forEach { i -> messages.add(i)}
file.close()
}
fun remove(agent: String) {
try {
try {
agents.remove(agent)
Class.forName("com.mysql.jdbc.Driver")
var query = "UPDATE `agents` SET `status` = 0 WHERE `username` = '$agent'"
val url = "jdbc:mysql://${Constants.SQL_SERVER}:${Constants.SQL_PORT}/${Constants.SQL_DB}"
val conn = DriverManager.getConnection(url, Constants.SQL_USER, Constants.SQL_PASSWORD)
val stmt = conn.createStatement()
stmt.executeUpdate(query)
conn.close()
} catch (se: SQLException) {
se.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
} catch (ex: SkypeException) {
ex.printStackTrace()
}
}
fun checkMessage(msg: String): Boolean {
return messages.contains(msg)
}
} | apache-2.0 | d6f4cd7b3c27e54433ecea5b711c9cf6 | 33.054795 | 106 | 0.547284 | 4.627561 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/features/payment_result/remedies/view/CvvRemedy.kt | 1 | 3139 | package com.mercadopago.android.px.internal.features.payment_result.remedies.view
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.TextView
import com.mercadopago.android.px.R
internal class CvvRemedy(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
LinearLayout(context, attrs, defStyleAttr) {
init {
configureView(context)
}
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context) : this(context, null)
var listener: Listener? = null
private var previousCvv = ""
private var length: Int = 3
private lateinit var input: TextInputEditText
private lateinit var inputContainer: TextInputLayout
private lateinit var info: TextView
private fun configureView(context: Context) {
orientation = VERTICAL
inflate(context, R.layout.px_remedies_cvv, this)
input = findViewById(R.id.input)
inputContainer = findViewById(R.id.input_container)
info = findViewById(R.id.info)
input.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {}
override fun beforeTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) {
previousCvv = text.toString()
}
override fun onTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) {
updateCvvFilledStatus(text)
}
})
}
fun init(model: Model) {
input.filters = arrayOf(InputFilter.LengthFilter(model.length))
inputContainer.hint = model.hint
info.text = model.info
length = model.length
updateCvvFilledStatus(input.text)
}
private fun updateCvvFilledStatus(text: CharSequence?) {
if (text?.length == length) {
listener?.onCvvFilled(text.toString())
} else if (previousCvv.length == length || previousCvv.isEmpty()) {
listener?.onCvvDeleted()
}
}
interface Listener {
fun onCvvFilled(cvv: String)
fun onCvvDeleted()
}
internal data class Model(val hint: String, val info: String, val length: Int) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString()!!,
parcel.readString()!!,
parcel.readInt())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(hint)
parcel.writeString(info)
parcel.writeInt(length)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Model> {
override fun createFromParcel(parcel: Parcel) = Model(parcel)
override fun newArray(size: Int) = arrayOfNulls<Model>(size)
}
}
} | mit | 42610502191a7e8a50cb3b4b9783bc47 | 33.505495 | 97 | 0.659446 | 4.582482 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/lang/alias/AliasManager.kt | 1 | 6293 | package nl.hannahsten.texifyidea.lang.alias
import com.intellij.openapi.project.Project
import nl.hannahsten.texifyidea.index.LatexDefinitionIndex
import nl.hannahsten.texifyidea.psi.LatexCommands
import java.util.concurrent.ConcurrentHashMap
/**
* Manage aliases for commands and environments.
*/
abstract class AliasManager {
/**
* Maps a command to a set of aliases including the command itself.
* Similar for environments.
*
* All elements of the set are in the map as keys as well linking to the set in which they
* are themselves. This means that the set of all keys that are aliases of each other all
* link to the same set of aliases. This ensures that you only have to modify the alias sets
* once and automatically update for all others.
*
*
* The commands are stored including the backslash.
*
*
* *Example:*
*
*
* Definitions:<br></br>
* `A := {\one, \een, \ein}`<br></br>
* `B := {\twee}`<br></br>
* `C := {\drie, \three}`
*
*
* Map:<br></br>
* `\one => A`<br></br>
* `\een => A`<br></br>
* `\ein => A`<br></br>
* `\twee => B`<br></br>
* `\three => C`<br></br>
* `\drie => C`
*/
open val aliases = ConcurrentHashMap<String, MutableSet<String>>()
/**
* We have to somehow know when we need to look for new aliases.
* We do this by keeping track of the \newcommand-like commands in the index,
* and when this changes we go gather new aliases.
*/
open var indexedCommandDefinitions = setOf<LatexCommands>()
/**
* Register a new item, which creates a new alias set.
*/
fun register(alias: String) {
require(!isRegistered(alias)) { "alias '$alias' has already been registered" }
synchronized(aliases) {
aliases[alias] = mutableSetOf(alias)
}
}
/**
* Checks if the given alias has been registered to the alias manager.
*
* @param alias
* The alias to check if it has been registered
* *E.g. `\begin`*
* @return `true` if the given alias is present in the alias manager, `false`
* otherwise.
*/
fun isRegistered(alias: String): Boolean {
synchronized(aliases) {
return aliases.containsKey(alias)
}
}
/**
* Register an alias for a given item.
*
*
* The alias will be added to the set of aliases for the given item.
*
* @param item
* An existing item to register the alias for starting with a backslash. *E.g.
* `\begin`*
* @param alias
* The alias to register for the item. This could be either
* a new item, or an existing item *E.g. `\start`*
*/
@Synchronized
fun registerAlias(item: String, alias: String) {
synchronized(aliases) {
val aliasSet = aliases[item] ?: mutableSetOf()
// If the alias is already assigned: unassign it.
if (isRegistered(alias)) {
val previousAliases = aliases[alias]
previousAliases?.remove(alias)
aliases.remove(alias)
}
aliasSet.add(alias)
aliases[alias] = aliasSet
}
}
/**
* Get an unmodifiable set with all the aliases for the given item.
*
* @param item
* An existing item to get all aliases of starting with a backslash. *E.g. `\begin`*
* @return An unmodifiable set of all aliases including the item itself. Returns the empty set if the item is not registered.
*/
fun getAliases(item: String): Set<String> {
if (!isRegistered(item)) return emptySet()
synchronized(aliases) {
return aliases[item]?.toSet() ?: emptySet()
}
}
/**
* If needed (based on the number of indexed \newcommand-like commands) check for new aliases of the given alias set. This alias can be any alias of its alias set.
* If the alias set is not yet registered, it will be registered as a new alias set.
*/
@Synchronized
fun updateAliases(aliasSet: Collection<String>, project: Project) {
// Register if needed
if (aliasSet.isEmpty()) return
val firstAlias = aliasSet.first()
var wasRegistered = false
if (!isRegistered(firstAlias)) {
register(firstAlias)
wasRegistered = true
aliasSet.forEach { registerAlias(firstAlias, it) }
}
// If the command name itself is not directly in the given set, check if it is perhaps an alias of a command in the set
// Uses projectScope now, may be improved to filesetscope
val indexedCommandDefinitions = LatexDefinitionIndex.getItems(project)
// Check if something has changed (the number of indexed command might be the same while the content is different), and if so, update the aliases.
// Also do this the first time something is registered, because then we have to update aliases as well
val hasNotChanged = this.indexedCommandDefinitions.containsAll(indexedCommandDefinitions) && indexedCommandDefinitions.containsAll(this.indexedCommandDefinitions)
if (!hasNotChanged || wasRegistered) {
// Update everything, since it is difficult to know beforehand what aliases could be added or not
// Alternatively we could save a numberOfIndexedCommandDefinitions per alias set, and only update the
// requested alias set (otherwise only the first alias set requesting an update will get it)
// We have to deepcopy the set of alias sets before iterating over it, because we want to modify aliases
synchronized(aliases) {
val deepCopy = aliases.values.map { it1 -> it1.map { it }.toSet() }.toSet()
for (copiedAliasSet in deepCopy) {
findAllAliases(copiedAliasSet, indexedCommandDefinitions)
}
}
this.indexedCommandDefinitions = indexedCommandDefinitions.toSet()
}
}
/**
* Find all aliases that are defined in the [indexedDefinitions] and register them.
*/
abstract fun findAllAliases(
aliasSet: Set<String>,
indexedDefinitions: Collection<LatexCommands>
)
} | mit | 3816f7f8b2016d3b5b11b3d3c32123d1 | 36.915663 | 170 | 0.626092 | 4.517588 | false | false | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncUserEpisodeComments.kt | 1 | 5884 | /*
* Copyright (C) 2015 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.actions.user
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.PagedAction
import net.simonvt.cathode.actions.PagedResponse
import net.simonvt.cathode.actions.user.SyncUserEpisodeComments.Params
import net.simonvt.cathode.api.entity.CommentItem
import net.simonvt.cathode.api.enumeration.CommentType
import net.simonvt.cathode.api.enumeration.ItemType
import net.simonvt.cathode.api.enumeration.ItemTypes
import net.simonvt.cathode.api.service.UsersService
import net.simonvt.cathode.common.database.forEach
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.CommentColumns
import net.simonvt.cathode.provider.ProviderSchematic.Comments
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.entity.ItemTypeString
import net.simonvt.cathode.provider.helper.CommentsHelper
import net.simonvt.cathode.provider.helper.EpisodeDatabaseHelper
import net.simonvt.cathode.provider.helper.SeasonDatabaseHelper
import net.simonvt.cathode.provider.helper.ShowDatabaseHelper
import net.simonvt.cathode.provider.helper.UserDatabaseHelper
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.settings.TraktTimestamps
import retrofit2.Call
import javax.inject.Inject
class SyncUserEpisodeComments @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper,
private val seasonHelper: SeasonDatabaseHelper,
private val episodeHelper: EpisodeDatabaseHelper,
private val userHelper: UserDatabaseHelper,
private val usersService: UsersService
) : PagedAction<Params, CommentItem>() {
override fun key(params: Params): String = "SyncUserEpisodeComments"
override fun getCall(params: Params, page: Int): Call<List<CommentItem>> =
usersService.getUserComments(CommentType.ALL, ItemTypes.EPISODES, page, LIMIT)
override suspend fun handleResponse(
params: Params,
pagedResponse: PagedResponse<Params, CommentItem>
) {
val ops = arrayListOf<ContentProviderOperation>()
val existingComments = mutableListOf<Long>()
val addedLater = mutableMapOf<Long, CommentItem>()
val localComments = context.contentResolver.query(
Comments.COMMENTS,
arrayOf(CommentColumns.ID),
CommentColumns.ITEM_TYPE + "=? AND " + CommentColumns.IS_USER_COMMENT + "=1",
arrayOf(ItemTypeString.EPISODE)
)
localComments.forEach { cursor -> existingComments.add(cursor.getLong(CommentColumns.ID)) }
localComments.close()
var profileId = -1L
var page: PagedResponse<Params, CommentItem>? = pagedResponse
do {
for (commentItem in page!!.response) {
val comment = commentItem.comment
val commentId = comment.id
// Old issue where two comments could have the same ID.
if (addedLater[commentId] != null) {
continue
}
val values = CommentsHelper.getValues(comment)
values.put(CommentColumns.IS_USER_COMMENT, true)
if (profileId == -1L) {
val profile = commentItem.comment.user
val result = userHelper.updateOrCreate(profile)
profileId = result.id
}
values.put(CommentColumns.USER_ID, profileId)
val traktId = commentItem.show!!.ids.trakt!!
val showResult = showHelper.getIdOrCreate(traktId)
val showId = showResult.showId
val episode = commentItem.episode
val seasonNumber = episode!!.season!!
val episodeNumber = episode.number!!
val seasonResult = seasonHelper.getIdOrCreate(showId, seasonNumber)
val seasonId = seasonResult.id
val episodeResult = episodeHelper.getIdOrCreate(showId, seasonId, episodeNumber)
val episodeId = episodeResult.id
values.put(CommentColumns.ITEM_TYPE, ItemType.EPISODE.toString())
values.put(CommentColumns.ITEM_ID, episodeId)
var exists = existingComments.contains(commentId)
if (!exists) {
// May have been created by user likes
val commentCursor = context.contentResolver.query(
Comments.withId(commentId),
arrayOf(CommentColumns.ID)
)
exists = commentCursor.moveToFirst()
commentCursor.close()
}
if (exists) {
existingComments.remove(commentId)
val op = ContentProviderOperation.newUpdate(Comments.withId(commentId)).withValues(values)
ops.add(op.build())
} else {
val op = ContentProviderOperation.newInsert(Comments.COMMENTS).withValues(values)
ops.add(op.build())
addedLater[commentId] = commentItem
}
}
page = page.nextPage()
} while (page != null)
for (id in existingComments) {
val op = ContentProviderOperation.newDelete(Comments.withId(id))
ops.add(op.build())
}
context.contentResolver.batch(ops)
if (params.userActivityTime > 0L) {
TraktTimestamps.getSettings(context)
.edit()
.putLong(TraktTimestamps.EPISODE_COMMENT, params.userActivityTime)
.apply()
}
}
data class Params(val userActivityTime: Long = 0L)
companion object {
private const val LIMIT = 100
}
}
| apache-2.0 | 84037e295d5d763dfd82d690ff5be472 | 35.320988 | 100 | 0.723997 | 4.460955 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/fragment/SongBookFragment.kt | 3 | 5831 | package org.worshipsongs.fragment
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.os.Parcelable
import android.view.*
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.activity.SongListActivity
import org.worshipsongs.adapter.TitleAdapter
import org.worshipsongs.domain.SongBook
import org.worshipsongs.domain.Type
import org.worshipsongs.listener.SongContentViewListener
import org.worshipsongs.registry.ITabFragment
import org.worshipsongs.service.SongBookService
/**
* Author : Madasamy
* Version : 3.x
*/
class SongBookFragment : AbstractTabFragment(), TitleAdapter.TitleAdapterListener<SongBook>, ITabFragment
{
private var state: Parcelable? = null
private var songBookService: SongBookService? = null
private var songBookList: List<SongBook>? = null
private var songBookListView: ListView? = null
private var titleAdapter: TitleAdapter<SongBook>? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
if (savedInstanceState != null)
{
state = savedInstanceState.getParcelable(STATE_KEY)
}
setHasOptionsMenu(true)
initSetUp()
}
private fun initSetUp()
{
songBookService = SongBookService(activity!!.applicationContext)
songBookList = songBookService!!.findAll()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = inflater.inflate(R.layout.songs_layout, container, false) as View
setListView(view)
return view
}
private fun setListView(view: View)
{
songBookListView = view.findViewById<View>(R.id.song_list_view) as ListView
titleAdapter = TitleAdapter((activity as AppCompatActivity?)!!, R.layout.songs_layout)
titleAdapter!!.setTitleAdapterListener(this)
titleAdapter!!.addObjects(songBookService!!.filteredSongBooks("", songBookList!!))
songBookListView!!.adapter = titleAdapter
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater)
{
inflater.inflate(R.menu.action_bar_menu, menu)
val searchManager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = menu!!.findItem(R.id.menu_search).actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity!!.componentName))
searchView.maxWidth = Integer.MAX_VALUE
searchView.queryHint = getString(R.string.action_search)
val image = searchView.findViewById<View>(R.id.search_close_btn) as ImageView
val drawable = image.drawable
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener
{
override fun onQueryTextSubmit(query: String): Boolean
{
titleAdapter!!.addObjects(songBookService!!.filteredSongBooks(query, songBookList!!))
return true
}
override fun onQueryTextChange(newText: String): Boolean
{
titleAdapter!!.addObjects(songBookService!!.filteredSongBooks(newText, songBookList!!))
return true
}
})
menu.getItem(0).isVisible = false
super.onCreateOptionsMenu(menu, inflater)
}
override fun onSaveInstanceState(outState: Bundle)
{
if (this.isAdded && songBookListView != null)
{
outState.putParcelable(STATE_KEY, songBookListView!!.onSaveInstanceState())
}
super.onSaveInstanceState(outState)
}
override fun onResume()
{
super.onResume()
if (state != null)
{
songBookListView!!.onRestoreInstanceState(state)
} else
{
titleAdapter!!.addObjects(songBookService!!.filteredSongBooks("", songBookList!!))
}
}
override fun onPause()
{
state = songBookListView!!.onSaveInstanceState()
super.onPause()
}
override fun setViews(objects: Map<String, Any>, songBook: SongBook?)
{
val titleTextView = objects[CommonConstants.TITLE_KEY] as TextView?
titleTextView!!.text = songBook!!.name
titleTextView.setOnClickListener(getOnClickListener(songBook))
setCountView((objects[CommonConstants.SUBTITLE_KEY] as TextView?)!!, songBook.noOfSongs.toString())
}
private fun getOnClickListener(songBook: SongBook): View.OnClickListener
{
return View.OnClickListener {
val intent = Intent(context, SongListActivity::class.java)
intent.putExtra(CommonConstants.TYPE, Type.SONG_BOOK.name)
intent.putExtra(CommonConstants.TITLE_KEY, songBook.name)
intent.putExtra(CommonConstants.ID, songBook.id)
startActivity(intent)
}
}
override fun defaultSortOrder(): Int
{
return 3
}
override val title: String get() { return "song_books"}
override fun checked(): Boolean
{
return true
}
override fun setListenerAndBundle(songContentViewListener: SongContentViewListener?, bundle: Bundle)
{
// Do nothing
}
companion object
{
private val STATE_KEY = "listViewState"
fun newInstance(): SongBookFragment
{
return SongBookFragment()
}
}
}
| gpl-3.0 | 510d3330d2df361d501224bf25ba3f22 | 31.943503 | 114 | 0.685474 | 5.000858 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/WriteMessageActivity.kt | 1 | 14492 | package com.pr0gramm.app.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcel
import android.text.SpannableStringBuilder
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import androidx.core.text.bold
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pr0gramm.app.R
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.api.pr0gramm.Message
import com.pr0gramm.app.api.pr0gramm.MessageConverter
import com.pr0gramm.app.databinding.FragmentWriteMessageBinding
import com.pr0gramm.app.feed.FeedItem
import com.pr0gramm.app.parcel.*
import com.pr0gramm.app.services.*
import com.pr0gramm.app.ui.base.BaseAppCompatActivity
import com.pr0gramm.app.ui.base.bindViews
import com.pr0gramm.app.ui.base.launchWhenStarted
import com.pr0gramm.app.ui.base.withViewDisabled
import com.pr0gramm.app.util.*
import com.pr0gramm.app.util.di.instance
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
/**
*/
class WriteMessageActivity : BaseAppCompatActivity("WriteMessageActivity") {
private val inboxService: InboxService by instance()
private val userService: UserService by instance()
private val voteService: VoteService by instance()
private val suggestionService: UserSuggestionService by instance()
private val views by bindViews(FragmentWriteMessageBinding::inflate)
private val receiverName: String by lazy { intent.getStringExtra(ARGUMENT_RECEIVER_NAME)!! }
private val receiverId: Long by lazy { intent.getLongExtra(ARGUMENT_RECEIVER_ID, 0) }
private val isCommentAnswer: Boolean by lazy { intent.hasExtra(ARGUMENT_COMMENT_ID) }
private val parentCommentId: Long by lazy { intent.getLongExtra(ARGUMENT_COMMENT_ID, 0) }
private val itemId: Long by lazy { intent.getLongExtra(ARGUMENT_ITEM_ID, 0) }
private val titleOverride: String? by lazy { intent.getStringExtra(ARGUMENT_TITLE) }
private val parentComments: List<ParentComment> by lazy {
intent.getParcelableExtra<ParentComments>(ARGUMENT_EXCERPTS)?.comments ?: listOf()
}
private var selectedUsers by observeChangeEx(setOf<String>()) { _, _ -> updateViewState() }
public override fun onCreate(savedInstanceState: Bundle?) {
setTheme(ThemeHelper.theme.basic)
super.onCreate(savedInstanceState)
setContentView(views)
supportActionBar?.apply {
setDisplayShowHomeEnabled(true)
setDisplayHomeAsUpEnabled(true)
}
// set title
title = titleOverride ?: getString(R.string.write_message_title, receiverName)
// and previous message
updateMessageView()
views.submit.setOnClickListener { sendMessageNow() }
views.newMessageText.addTextChangedListener(object : SimpleTextWatcher() {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
val tooShort = s.toString().trim().length < 3
views.submit.isEnabled = !tooShort
invalidateOptionsMenu()
}
})
val cacheKey = if (isCommentAnswer) "$itemId-$parentCommentId" else "msg-$receiverId"
TextViewCache.addCaching(views.newMessageText, cacheKey)
views.newMessageText.setTokenizer(UsernameTokenizer())
views.newMessageText.setAdapter(UsernameAutoCompleteAdapter(suggestionService, this,
android.R.layout.simple_dropdown_item_1line, "@"))
views.newMessageText.setAnchorView(findViewById(R.id.auto_complete_popup_anchor))
if (isCommentAnswer) {
views.newMessageText.hint = getString(R.string.comment_hint)
}
// only show if we can link to someone else
val shouldShowParentComments = this.parentComments.any {
it.user != receiverName && it.user != userService.loginState.name
}
if (shouldShowParentComments) {
// make the views visible
find<View>(R.id.authors_title).isVisible = true
views.parentComments.isVisible = true
views.parentComments.adapter = Adapter()
views.parentComments.layoutManager = LinearLayoutManager(this)
views.parentComments.itemAnimator = null
updateViewState()
}
}
override fun onPostResume() {
super.onPostResume()
AndroidUtility.showSoftKeyboard(views.newMessageText)
}
private fun updateViewState() {
val adapter = views.parentComments.adapter as Adapter
adapter.submitList(parentComments.map { comment ->
val isReceiverUser = comment.user == receiverName
val isCurrentUser = comment.user == userService.loginState.name
SelectedParentComment(comment,
enabled = !isReceiverUser && !isCurrentUser,
selected = comment.user in selectedUsers)
})
// sorted users, or empty if the list has focus
val sortedUsers = selectedUsers.sorted()
if (sortedUsers.isEmpty()) {
views.newMessageText.suffix = null
} else {
views.newMessageText.suffix = sortedUsers.joinToString(" ") { "@$it" }
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return true == when (item.itemId) {
android.R.id.home -> finish()
R.id.action_send -> sendMessageNow()
else -> super.onOptionsItemSelected(item)
}
}
override fun finish() {
// hide keyboard before closing the activity.
hideSoftKeyboard()
super.finish()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_write_message, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.action_send)?.isEnabled = views.submit.isEnabled
return true
}
private fun finishAfterSending() {
TextViewCache.invalidate(views.newMessageText)
finish()
}
private fun sendMessageNow() {
val message = getMessageText()
if (message.isEmpty()) {
showDialog(this) {
content(R.string.message_must_not_be_empty)
positive()
}
return
}
if (isCommentAnswer) {
val itemId = itemId
val parentComment = parentCommentId
launchWhenStarted(busyIndicator = true) {
withViewDisabled(views.submit) {
val newComments = withContext(NonCancellable + Dispatchers.Default) {
voteService.postComment(itemId, parentComment, message)
}
val result = Intent()
result.putExtra(RESULT_EXTRA_NEW_COMMENT, NewCommentParceler(newComments))
setResult(Activity.RESULT_OK, result)
finishAfterSending()
}
}
Track.writeComment(root = parentCommentId == 0L)
} else {
launchWhenStarted(busyIndicator = true) {
withViewDisabled(views.submit) {
withContext(NonCancellable + Dispatchers.Default) {
inboxService.send(receiverId, message)
}
finishAfterSending()
}
}
Track.writeMessage()
}
}
private fun getMessageText(): String {
return views.newMessageText.text.toString().trim()
}
private fun updateMessageView() {
// hide view by default and only show, if we found data
views.messageView.isVisible = false
val extras = intent?.extras ?: return
val message = extras.getParcelableOrNull<MessageSerializer>(ARGUMENT_MESSAGE)?.message
if (message != null) {
views.messageView.update(message, userService.name)
views.messageView.isVisible = true
}
}
companion object {
private const val ARGUMENT_MESSAGE = "WriteMessageFragment.message"
private const val ARGUMENT_RECEIVER_ID = "WriteMessageFragment.userId"
private const val ARGUMENT_RECEIVER_NAME = "WriteMessageFragment.userName"
private const val ARGUMENT_COMMENT_ID = "WriteMessageFragment.commentId"
private const val ARGUMENT_ITEM_ID = "WriteMessageFragment.itemId"
private const val ARGUMENT_EXCERPTS = "WriteMessageFragment.excerpts"
private const val ARGUMENT_TITLE = "WriteMessageFragment.title"
private const val RESULT_EXTRA_NEW_COMMENT = "WriteMessageFragment.result.newComment"
fun intent(context: Context, message: Message): Intent {
return activityIntent<WriteMessageActivity>(context) {
putExtra(ARGUMENT_RECEIVER_ID, message.senderId.toLong())
putExtra(ARGUMENT_RECEIVER_NAME, message.name)
putExtra(ARGUMENT_MESSAGE, MessageSerializer(message))
}
}
fun intent(context: Context, userId: Long, userName: String): Intent {
return activityIntent<WriteMessageActivity>(context) {
putExtra(ARGUMENT_RECEIVER_ID, userId)
putExtra(ARGUMENT_RECEIVER_NAME, userName)
}
}
fun newComment(context: Context, item: FeedItem): Intent {
return activityIntent<WriteMessageActivity>(context) {
putExtra(ARGUMENT_ITEM_ID, item.id)
putExtra(ARGUMENT_COMMENT_ID, 0L)
putExtra(ARGUMENT_TITLE, context.getString(R.string.write_comment, item.user))
}
}
fun answerToComment(
context: Context, feedItem: FeedItem, comment: Api.Comment,
parentComments: List<ParentComment>): Intent {
return answerToComment(context, MessageConverter.of(feedItem, comment), parentComments)
}
fun answerToComment(
context: Context, message: Message,
parentComments: List<ParentComment> = listOf()): Intent {
val itemId = message.itemId
val commentId = message.id
return intent(context, message).apply {
putExtra(ARGUMENT_ITEM_ID, itemId)
putExtra(ARGUMENT_COMMENT_ID, commentId)
putExtra(ARGUMENT_EXCERPTS, ParentComments(parentComments))
}
}
fun getNewCommentFromActivityResult(data: Intent): Api.NewComment {
return data.extras
?.getParcelableOrNull<NewCommentParceler>(RESULT_EXTRA_NEW_COMMENT)
?.value
?: throw IllegalArgumentException("no comment found in Intent")
}
}
data class ParentComment(val user: String, val excerpt: String) {
companion object {
fun ofComment(comment: Api.Comment): ParentComment {
val cleaned = comment.content.replace("\\s+".toRegex(), " ")
val content = if (cleaned.length < 120) cleaned else cleaned.take(120) + "…"
return ParentComment(comment.name, content)
}
}
}
private data class SelectedParentComment(
val comment: ParentComment, val enabled: Boolean, val selected: Boolean)
private inner class Adapter : AsyncListAdapter<SelectedParentComment, ViewHolder>(ItemCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = parent.layoutInflater.inflate(R.layout.row_comment_excerpt, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.update(getItem(position))
}
}
private class ItemCallback : DiffUtil.ItemCallback<SelectedParentComment>() {
override fun areItemsTheSame(oldItem: SelectedParentComment, newItem: SelectedParentComment): Boolean {
return oldItem.comment === newItem.comment
}
override fun areContentsTheSame(oldItem: SelectedParentComment, newItem: SelectedParentComment): Boolean {
return oldItem == newItem
}
}
private inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val excerptTextView: CheckedTextView = itemView as CheckedTextView
fun update(parentComment: SelectedParentComment) {
excerptTextView.isChecked = parentComment.selected
excerptTextView.isEnabled = parentComment.enabled
excerptTextView.text = SpannableStringBuilder().apply {
bold {
append(parentComment.comment.user)
}
append(" ")
append(parentComment.comment.excerpt)
}
excerptTextView.setOnClickListener {
if (excerptTextView.isEnabled) {
val user = parentComment.comment.user
if (user in selectedUsers) {
selectedUsers = selectedUsers - user
} else {
selectedUsers = selectedUsers + user
}
}
}
}
}
class ParentComments(val comments: List<ParentComment>) : DefaultParcelable {
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeValues(comments) { comment ->
writeString(comment.user)
writeString(comment.excerpt)
}
}
companion object CREATOR : SimpleCreator<ParentComments>(javaClassOf()) {
override fun createFromParcel(source: Parcel): ParentComments {
val comments = source.readValues {
ParentComment(
user = source.readStringNotNull(),
excerpt = source.readStringNotNull(),
)
}
return ParentComments(comments)
}
}
}
}
| mit | 2f894b726ba00e853cf5aae414150cc5 | 36.345361 | 114 | 0.636784 | 5.02079 | false | false | false | false |
pjq/rpi | android/app/src/main/java/me/pjq/rpicar/MainNavigationActivity.kt | 1 | 6199 | package me.pjq.rpicar
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import android.text.TextUtils
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import me.pjq.rpicar.realm.Settings
class MainNavigationActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, AboutFragment.OnFragmentInteractionListener {
private var onBackKeyListener: OnBackKeyListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_navigation)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.addDrawerListener(toggle)
toggle.syncState()
val navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)
initSettings()
initFirstFragment()
}
private fun initSettings() {
DataManager.init(applicationContext)
val settings = DataManager.realm.where(Settings::class.java).findFirst()
if (null != settings && !TextUtils.isEmpty(settings.getHost())) {
CarControllerApiService.Config.HOST = settings.getHost()
}
}
private fun initFirstFragment() {
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = CarControllerMainFragment.newInstance()
fragmentTransaction.replace(R.id.content, fragment)
fragmentTransaction.commitAllowingStateLoss()
}
override fun onBackPressed() {
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main_navigation, menu);
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_camera) {
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = CarControllerMainFragment.newInstance()
fragmentTransaction.replace(R.id.content, fragment)
// fragmentTransaction.addToBackStack(SettingsFragment.class.getSimpleName());
fragmentTransaction.commitAllowingStateLoss()
onBackKeyListener = null
} else if (id == R.id.nav_slideshow) {
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = CaptureVideoFragment.newInstance()
fragmentTransaction.replace(R.id.content, fragment)
// fragmentTransaction.addToBackStack(CaptureVideoFragment.class.getSimpleName());
fragmentTransaction.commitAllowingStateLoss()
onBackKeyListener = fragment
} else if (id == R.id.nav_settings) {
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = SettingsFragment.newInstance()
fragmentTransaction.replace(R.id.content, fragment)
// fragmentTransaction.addToBackStack(SettingsFragment.class.getSimpleName());
fragmentTransaction.commitAllowingStateLoss()
// setTitle("Settings");
onBackKeyListener = null
} else if (id == R.id.nav_about) {
val fragmentTransaction = fragmentManager.beginTransaction()
val fragment = AboutFragment.newInstance()
fragmentTransaction.replace(R.id.content, fragment)
// fragmentTransaction.addToBackStack(AboutFragment.class.getSimpleName());
fragmentTransaction.commitAllowingStateLoss()
onBackKeyListener = null
} else if (id == R.id.nav_temp) {
val intent = Intent()
intent.setClass(this, TemperatureChartTimeActivity::class.java)
startActivity(intent)
onBackKeyListener = null
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
}
override fun onFragmentInteraction(uri: Uri) {}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (KeyEvent.KEYCODE_BACK == keyCode) {
if (null != onBackKeyListener) {
return onBackKeyListener!!.onBackKeyDown()
}
}
return super.onKeyDown(keyCode, event)
}
interface OnBackKeyListener {
fun onBackKeyDown(): Boolean
}
}
| apache-2.0 | c1e89dbffe7498b063864f4f13ffd977 | 39.51634 | 146 | 0.677367 | 5.330181 | false | false | false | false |
mkgithub10/kotlinWebJS | src/main/kotlinWebJS/main.kt | 1 | 1603 |
package kotlinWebJS
import kotlin.browser.document
// using JQUERY on kotlin, memo: import jquery library!
@native("$")
val jquery : dynamic = noImpl
fun main(args: Array<String>) {
// creating a Kotlin application that compiles down to JavaScript
val el = document.createElement("div")
el.appendChild(document.createTextNode("example"))
document.body!!.appendChild(el)
val playersFromApi = "http://localhost:8080/"
// to do: fix the getJSON call -> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
jquery.getJSON(playersFromApi) { players ->
val playersTable = jquery("#playersTable")
players.forEach { player ->
playersTable.append("""
<tr>
<td><a href=${player.username}>${player.nickname}</a></td>
</tr>""")
}
}
// ---------------------------------------------------------------
println("kotlin from js:")
println("equivalent to 'console.log()' ¿? yes and no, look at the result on ../web/js/app.js")
// ---------------------------------------------------------------
js("console.log('js from kotlin:')")
val explanation = "" +
"Language Injection support in IntelliJ IDEA for Kotlin. " +
"And while this applies to any string and any language, " +
"not just JavaScript, it definitely proves useful when using js, " +
"allowing this.."
js("console.log('${explanation}')") // Language Injection: func 'js'
} | gpl-3.0 | e002acad5a8ba5d433d83da7ece84b24 | 37.166667 | 161 | 0.568664 | 4.603448 | false | false | false | false |
EricssonResearch/scott-eu | lyo-services/webapp-whc/src/main/java/se/ericsson/cf/scott/sandbox/whc/xtra/services/WhcAdminService.kt | 1 | 2323 | package se.ericsson.cf.scott.sandbox.whc.xtra.services
import eu.scott.warehouse.lib.OslcHelper
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import se.ericsson.cf.scott.sandbox.whc.WarehouseControllerManager
import se.ericsson.cf.scott.sandbox.whc.xtra.WhcConfig
import se.ericsson.cf.scott.sandbox.whc.xtra.clients.TwinClient
import se.ericsson.cf.scott.sandbox.whc.xtra.managers.PlanningManager
import se.ericsson.cf.scott.sandbox.whc.xtra.planning.PlanRequestHelper
import se.ericsson.cf.scott.sandbox.whc.xtra.repository.TwinRepository
import java.util.concurrent.TimeUnit
import javax.ws.rs.POST
import javax.ws.rs.Path
import javax.ws.rs.core.Response
/**
* A REST resource with misc admin endpoints
*
*/
@Path("admin")
class WhcAdminService {
companion object {
val log: Logger = LoggerFactory.getLogger(WhcAdminService::class.java)
}
// TODO Andrew@2019-03-12: inject this
private val twinsRepository: TwinRepository
get() = WarehouseControllerManager.getTwinRepository()
/**
* POSTING to this resource shall create one plan per robot and send them out.
*/
@POST
@Path("plan_trigger")
fun plan(): Response {
// triggerPlanning()
runAsync(this::triggerPlanning)
return Response.noContent().build()
}
// TODO Andrew@2019-03-12: move to the lib
private fun runAsync(function: () -> Unit) {
log.trace("Scheduling function execution w/o delay")
WarehouseControllerManager.getExecService()
.execute {
try {
function.invoke()
} catch (e: Throwable) {
log.error("PlanningManager threw an exception: ${ExceptionUtils.getStackTrace(e)}")
}
}
}
private fun triggerPlanning() {
log.trace("triggerSamplePlanning() called")
val planRequestHelper = PlanRequestHelper(OslcHelper(WhcConfig.getBaseUri()))
val twinClient = TwinClient()
val planRepository = WarehouseControllerManager.getPlanRepository()
val planningManager = PlanningManager(planRequestHelper, twinClient, planRepository)
planningManager.planForEachTwin(twinsRepository)
log.trace("triggerSamplePlanning() finished")
}
}
| apache-2.0 | 317da48083961a97f5c8204e80f44a0c | 34.738462 | 99 | 0.708136 | 4.025997 | false | false | false | false |
alidili/Demos | NanoHttpdDemo/app/src/main/java/tech/yangle/nanohttpd/LocalServer.kt | 1 | 4077 | package tech.yangle.nanohttpd
import android.util.Log
import fi.iki.elonen.NanoHTTPD
import fi.iki.elonen.NanoHTTPD.Response.Status.NOT_FOUND
import fi.iki.elonen.NanoHTTPD.Response.Status.OK
import java.io.File
import java.io.FileInputStream
/**
* 本地服务
* <p>
* Created by YangLe on 2022/9/2.
* Website:http://www.yangle.tech
*/
class LocalServer private constructor() : NanoHTTPD("127.0.0.1", 8888) {
// 资源路径
private var mResourcePath = ""
companion object {
private var instance: LocalServer? = null
private const val TAG = "LocalServer"
private const val MIME_PLAINTEXT = "text/plain"
private const val MIME_HTML = "text/html"
private const val MIME_JS = "application/javascript"
private const val MIME_CSS = "text/css"
private const val MIME_PNG = "image/png"
private const val MIME_JPEG = "image/jpeg"
private const val MIME_ICON = "image/x-icon"
private const val MIME_MP4 = "video/mp4"
private const val MIME_GIF = "image/gif"
private const val MIME_MP3 = "audio/mpeg"
private const val MIME_SVG = "image/svg+xml"
private const val MIME_WOFF = "application/font-woff"
fun getInstance(): LocalServer {
if (instance == null) {
instance = LocalServer()
}
return instance!!
}
}
override fun serve(session: IHTTPSession?): Response {
if (session == null) {
return newFixedLengthResponse(NOT_FOUND, MIME_PLAINTEXT, "session == null")
}
val url = session.uri
try {
val file = File(mResourcePath + url)
val length = file.length()
val inputStream = FileInputStream(file)
if (url.contains(".js")) {
return newFixedLengthResponse(OK, MIME_JS, inputStream, length)
} else if (url.contains(".css")) {
return newFixedLengthResponse(OK, MIME_CSS, inputStream, length)
} else if (url.contains(".htm") || url.contains(".html")) {
return newFixedLengthResponse(OK, MIME_HTML, inputStream, length)
} else if (url.contains(".png")) {
return newFixedLengthResponse(OK, MIME_PNG, inputStream, length)
} else if (url.contains(".jpg") || url.contains(".jpeg")) {
return newFixedLengthResponse(OK, MIME_JPEG, inputStream, length)
} else if (url.contains(".ico")) {
return newFixedLengthResponse(OK, MIME_ICON, inputStream, length)
} else if (url.contains(".gif")) {
return newFixedLengthResponse(OK, MIME_GIF, inputStream, length)
} else if (url.contains(".mp3")) {
return newFixedLengthResponse(OK, MIME_MP3, inputStream, length)
} else if (url.contains(".mp4")) {
return newFixedLengthResponse(OK, MIME_MP4, inputStream, length)
} else if (url.contains(".json")) {
return newFixedLengthResponse(OK, MIME_PLAINTEXT, inputStream, length)
} else if (url.contains(".svg")) {
return newFixedLengthResponse(OK, MIME_SVG, inputStream, length)
} else if (url.contains(".woff")) {
return newFixedLengthResponse(OK, MIME_WOFF, inputStream, length)
} else {
return newFixedLengthResponse(OK, "*/*", inputStream, length)
}
} catch (e: Exception) {
return newFixedLengthResponse(NOT_FOUND, MIME_PLAINTEXT, "${e.message}")
}
}
/**
* 启动服务
*/
fun startServer() {
try {
start()
} catch (e: Exception) {
Log.e(TAG, "[startServer] Exception:${e.message}")
}
}
/**
* 停止服务
*/
fun stopServer() {
stop()
}
/**
* 设置资源路径
*
* @param path 资源路径
*/
fun setResourcePath(path: String) {
this.mResourcePath = path
}
} | apache-2.0 | 9d7b2b69fe99ab228022afd34de06327 | 31.451613 | 87 | 0.574696 | 4.134635 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/download/DownloadNotificationManager.kt | 1 | 3191 | package cc.aoeiuv020.panovel.download
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.main.MainActivity
import cc.aoeiuv020.panovel.settings.DownloadSettings
import cc.aoeiuv020.panovel.util.NotificationChannelId
import cc.aoeiuv020.panovel.util.NotifyLoopProxy
import org.jetbrains.anko.intentFor
class DownloadNotificationManager(
private val ctx: Context,
novel: Novel
) {
private val enable: Boolean get() = DownloadSettings.downloadProgress
private val proxy: NotifyLoopProxy = NotifyLoopProxy(ctx)
// 太早了Intent不能用,
private val nb: NotificationCompat.Builder by lazy {
val intent = ctx.intentFor<MainActivity>()
val pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0)
val notificationBuilder = NotificationCompat.Builder(ctx, NotificationChannelId.download)
.setOnlyAlertOnce(true)
.setAutoCancel(true)
.setContentTitle(novel.name)
.setContentIntent(pendingIntent)
notificationBuilder.apply {
setSmallIcon(android.R.drawable.stat_sys_download)
}
notificationBuilder
}
fun downloadStart(left: Int) {
val exists = 0
val downloads = 0
val errors = 0
val progress = ((exists + downloads + errors).toFloat() / ((exists + downloads + errors) + left) * 100).toInt()
nb.setContentText(ctx.getString(R.string.downloading_placeholder, exists, downloads, errors, left))
.setProgress(100, progress, false)
if (enable) {
proxy.start(nb.build())
} else {
// 以防万一通知开始了不结束,
cancelNotification()
}
}
fun downloading(exists: Int, downloads: Int, errors: Int, left: Int) {
val progress = ((exists + downloads + errors).toFloat() / ((exists + downloads + errors) + left) * 100).toInt()
nb.setContentText(ctx.getString(R.string.downloading_placeholder, exists, downloads, errors, left))
.setProgress(100, progress, false)
if (enable) {
proxy.modify(nb.build())
} else {
// 以防万一通知开始了不结束,
cancelNotification()
}
}
fun downloadComplete(exists: Int, downloads: Int, errors: Int) {
nb.setContentText(ctx.getString(R.string.download_complete_placeholder, exists, downloads, errors))
.setProgress(0, 0, false)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
if (enable) {
proxy.complete(nb.build())
} else {
// 以防万一通知开始了不结束,
cancelNotification()
}
}
fun cancelNotification(cancelDelay: Long = NotifyLoopProxy.DEFAULT_CANCEL_DELAY) {
proxy.cancel(cancelDelay)
}
@Suppress("UNUSED_PARAMETER")
fun error(message: String, t: Throwable) {
// 出意外了直接停止通知循环,
proxy.error()
}
}
| gpl-3.0 | ba631533665a6b45c3c81bfd8906db45 | 35.152941 | 119 | 0.643996 | 4.322082 | false | false | false | false |
dawidfiruzek/Android-Kotlin-Template | {{ cookiecutter.repo_name }}/core/src/main/java/{{ cookiecutter.core_package_dir }}/domain/UseCaseExecutorImpl.kt | 1 | 2658 | package {{ cookiecutter.core_package_name }}.domain
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import org.reactivestreams.Subscription
class UseCaseExecutorImpl(
private val subscribeOnScheduler: Scheduler,
private val observeOnScheduler: Scheduler
) : UseCaseExecutor {
private val compositeDisposable = CompositeDisposable()
override fun execute(
completable: Completable,
onComplete: Action,
onError: Consumer<Throwable>) {
compositeDisposable.add(
completable
.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
.subscribe(onComplete, onError)
)
}
override fun <Return> execute(
single: Single<Return>,
onSuccess: Consumer<Return>,
onError: Consumer<Throwable>) {
compositeDisposable.add(
single
.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
.subscribe(onSuccess, onError)
)
}
override fun <Return> execute(
observable: Observable<Return>,
onSuccess: Consumer<Return>,
onError: Consumer<Throwable>,
onComplete: Action?,
onSubscribe: Consumer<Disposable>?) {
var o = observable
onComplete?.let { o = o.doOnComplete(it) }
onSubscribe?.let { o = o.doOnSubscribe(it) }
compositeDisposable.add(
o.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
.subscribe(onSuccess, onError)
)
}
override fun <Return> execute(
flowable: Flowable<Return>,
onSuccess: Consumer<Return>,
onError: Consumer<Throwable>,
onComplete: Action?,
onSubscribe: Consumer<Subscription>?) {
var f = flowable
onComplete?.let { f = f.doOnComplete(it) }
onSubscribe?.let { f = f.doOnSubscribe(it) }
compositeDisposable.add(
f.subscribeOn(subscribeOnScheduler)
.observeOn(observeOnScheduler)
.subscribe(onSuccess, onError)
)
}
override fun clear() {
compositeDisposable.clear()
}
} | mit | d942e432affead73e84680b43012f992 | 31.426829 | 59 | 0.600451 | 5.667377 | false | false | false | false |
liceoArzignano/app_bold | app/src/main/kotlin/it/liceoarzignano/bold/database/DBHandler.kt | 1 | 1930 | package it.liceoarzignano.bold.database
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteOpenHelper
import android.provider.BaseColumns
abstract class DBHandler<T : DBItem>
protected constructor(context: Context, name: String, version: Int) :
SQLiteOpenHelper(context, name, null, version) {
fun add(item: T) {
if (item.id == -1L) {
item.id = count.toLong()
}
val db = writableDatabase
db.insert(tableName, null, getValues(item, true))
}
fun update(item: T) {
val db = writableDatabase
db.update(tableName, getValues(item, false), "$KEY_ID=?",
arrayOf(item.id.toString()))
}
fun delete(id: Long) {
val db = writableDatabase
db.delete(tableName, "$KEY_ID=?", arrayOf(id.toString()))
}
fun refillTable(items: List<T>) {
val db = writableDatabase
val list = all
for (item in list) {
db.delete(tableName, "$KEY_ID=?", arrayOf(item.id.toString()))
}
for (item in items) {
db.insert(tableName, null, getValues(item, true))
}
}
fun clearTable() {
val db = writableDatabase
val list = all
for (item in list) {
db.delete(tableName, "$KEY_ID=?", arrayOf(item.id.toString()))
}
}
private val count: Int
get() {
val db = readableDatabase
val cursor = db.rawQuery("SELECT * FROM $tableName", null)
val count = cursor.count
cursor.close()
return count
}
protected abstract val all: List<T>
abstract operator fun get(id: Long): T?
protected abstract fun getValues(item: T, withId: Boolean): ContentValues
protected abstract val tableName: String
companion object {
@JvmStatic val KEY_ID = BaseColumns._ID
}
}
| lgpl-3.0 | 1b86827a546d2e908a89fa28052fa194 | 26.971014 | 77 | 0.592746 | 4.288889 | false | false | false | false |
americanexpress/bucketlist | examples/src/main/kotlin/io/aexp/bucketlist/examples/contributorsvstime/ExportContributorsVsTimeData.kt | 1 | 7207 | package io.aexp.bucketlist.examples.contributorsvstime
import de.erichseifert.gral.data.DataSource
import de.erichseifert.gral.data.DataTable
import de.erichseifert.gral.io.data.DataWriterFactory
import io.aexp.bucketlist.BucketListClient
import io.aexp.bucketlist.data.PullRequestActivity
import io.aexp.bucketlist.data.PullRequestCommit
import io.aexp.bucketlist.data.PullRequestState
import io.aexp.bucketlist.examples.getBitBucketClient
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import rx.Observable
import rx.observables.GroupedObservable
import rx.schedulers.Schedulers
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.time.Duration
import java.util.concurrent.TimeUnit
/**
* This example downloads the activity and commits for every PR in the specified repo that has been merged and writes
* some of the aggregated data into a tsv for later use
*
* We wanted to know how the length of time that a PR stayed open related to the number of people who contribute to it.
* For each PR, we collected all of the commits and created a set of committers. Then we calculate the duration of the
* PR and grouped the PRs by number of committers.
*
* To make a box and whisker plot of the tsv, use RenderContributorsVsTimeBoxWhiskerPlot
*
* Usage:
* - make a properties file containing 'username', 'password', and 'url' info for your Bitbucket-Server instance.
* - invoke with <path to props file> <project key> <repo slug> <output file>
*/
object ExportContributorsVsTimeData {
val logger: Logger = LoggerFactory.getLogger(javaClass)
@JvmStatic fun main(args: Array<String>) {
if (args.size != 4) {
System.err!!.println("Must have 4 arguments: <config file> <project key> <repo slug> <output file>")
System.exit(1)
}
val configPath = Paths.get(args[0])
val client = getBitBucketClient(configPath)
val projectKey = args[1]
val repoSlug = args[2]
val boxPlotDataTable = getDataTable()
val durationsByCommitters = getPrDurationsByCommitters(client, projectKey, repoSlug)
durationsByCommitters.flatMap({ durations ->
durations.collect({ -> ContributorCountStats(durations.key) },
{ statsHolder, record ->
val fractionalHours = record.duration.toMillis().toDouble() / TimeUnit.HOURS.toMillis(1)
logger.info("Recorded duration of $fractionalHours fractional hours for ${record.committers} committers")
statsHolder.stats.addValue(fractionalHours)
})
}).toSortedList({ stats1, stats2 -> stats1.contributorCount.compareTo(stats2.contributorCount) })
.toBlocking()
.first()
.forEachIndexed {
i, statsHolder ->
boxPlotDataTable.add(i,
statsHolder.stats.getPercentile(50.0),
statsHolder.stats.min,
statsHolder.stats.getPercentile(25.0),
statsHolder.stats.getPercentile(75.0),
statsHolder.stats.max)
}
writeData(boxPlotDataTable, Paths.get(args[3]))
logger.info("Done")
System.exit(0)
}
private fun getPrDurationsByCommitters(client: BucketListClient, projectKey: String, repoSlug: String)
: Observable<GroupedObservable<Int, PrWithCommitsAndDuration>> {
// Get all the PRs that have been merged
val prsWithActivity = client.getPrs(projectKey, repoSlug, PullRequestState.MERGED)
.flatMap({ prs -> Observable.from(prs.values) })
.flatMap({ pr ->
// Get the activity for each PR, so we can calculate open duration
client.getPrActivity(projectKey, repoSlug, pr.id)
.flatMap({ page -> Observable.from(page.values) })
.toSortedList({ activity1, activity2 -> activity1.createdAt.compareTo(activity2.createdAt) })
.map({ activities -> PrWithActivities(pr.id, activities) })
})
return prsWithActivity.flatMap({ prWithActivity ->
// Get a set of committers and store the count in a new data object
getPrCommitters(prWithActivity.prId, client, projectKey, repoSlug)
.map({ authors ->
PrWithCommitsAndDuration(prWithActivity.duration, authors.count())
})
})
// Group the data objects, by number of contributors
.groupBy({
prWithCommitsAndDurations ->
prWithCommitsAndDurations.committers
})
}
/**
* Fetch all the commits for a given PR and collect the authors into a set
*
* @return a set of all the people who committed to a PR
*/
private fun getPrCommitters(prId: Long, client: BucketListClient, projectKey: String, repoSlug: String)
: Observable<MutableSet<String>> {
val authors: MutableSet<String> = hashSetOf()
logger.info("Getting commits for PR $prId")
return client.getPrCommits(projectKey, repoSlug, prId)
.flatMap({ commits -> Observable.from(commits.values) })
.observeOn(Schedulers.trampoline())
.reduce(authors, { set, commit: PullRequestCommit ->
set.add(commit.author.name)
set
})
}
/**
* Wrapper to bundle a PR with its Activity so we can calculate duration
*/
private class PrWithActivities(val prId: Long, val activities: List<PullRequestActivity>) {
val duration: Duration
get() = Duration.between(activities.first().createdAt, activities.last().createdAt)
}
/**
* Wrapper to bundle the number of committers on a PR with a duration
*/
private class PrWithCommitsAndDuration(val duration: Duration, val committers: Int) {}
/**
* Wrapper to bundle stats for groups of PRs (grouped by number of committers)
*/
private class ContributorCountStats(val contributorCount: Int, val stats: DescriptiveStatistics = DescriptiveStatistics()) {}
/**
* @return DataTable configured with the appropriate columns for a box and whisker plot
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
private fun getDataTable(): DataTable {
return DataTable(Integer::class.java,
Double::class.java,
Double::class.java,
Double::class.java,
Double::class.java,
Double::class.java)
}
/**
* Write the populated DataSource into tsv for later graphing
*/
private fun writeData(ds: DataSource, path: Path) {
val dataWriter = DataWriterFactory.getInstance().get("text/tab-separated-values")
Files.newOutputStream(path).use { w ->
dataWriter.write(ds, w)
}
}
}
| apache-2.0 | b7affb8ba2ceeb60e07439ac11742d3a | 41.146199 | 129 | 0.635077 | 4.529855 | false | false | false | false |
StephaneBg/ScoreItProject | data/src/main/java/com/sbgapps/scoreit/cache/model/PlayerData.kt | 1 | 1145 | /*
* Copyright 2018 Stéphane Baiget
*
* 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.sbgapps.scoreit.cache.model
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "players",
foreignKeys = [(ForeignKey(
entity = UniversalGameData::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("gameId"),
onDelete = ForeignKey.CASCADE
))]
)
data class PlayerData(
@PrimaryKey(autoGenerate = true) val id: Long? = null,
val gameId: Long,
var name: String,
var color: Int
) | apache-2.0 | fd773ea6aadc66bb5b3b8f89b57d0681 | 29.131579 | 75 | 0.715035 | 4.205882 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/client/MonitorAsync.kt | 2 | 10739 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.client
import android.graphics.Bitmap
import android.os.IBinder
import edu.berkeley.boinc.rpc.AccountIn
import edu.berkeley.boinc.rpc.AccountManager
import edu.berkeley.boinc.rpc.AccountOut
import edu.berkeley.boinc.rpc.AcctMgrInfo
import edu.berkeley.boinc.rpc.GlobalPreferences
import edu.berkeley.boinc.rpc.HostInfo
import edu.berkeley.boinc.rpc.ImageWrapper
import edu.berkeley.boinc.rpc.Notice
import edu.berkeley.boinc.rpc.Project
import edu.berkeley.boinc.rpc.ProjectConfig
import edu.berkeley.boinc.rpc.ProjectInfo
import edu.berkeley.boinc.rpc.Result
import edu.berkeley.boinc.rpc.Transfer
import edu.berkeley.boinc.utils.ErrorCodeDescription
import edu.berkeley.boinc.utils.TaskRunner
class MonitorAsync(monitor: IMonitor?) : IMonitor {
val monitor = monitor!!
fun quitClientAsync(callback: ((Boolean) -> Unit)? = null) =
TaskRunner(callback, {quitClient()})
fun runBenchmarksAsync(callback: ((Boolean) -> Unit)? = null) =
TaskRunner(callback, {runBenchmarks()})
fun setGlobalPreferencesAsync(prefs: GlobalPreferences, callback: ((Boolean) -> Unit)? = null) =
TaskRunner(callback, {setGlobalPreferences(prefs)})
fun setCcConfigAsync(config: String, callback: ((Boolean) -> Unit)? = null) =
TaskRunner(callback, {setCcConfig(config)})
fun getProjectInfoAsync(url: String, callback: ((ProjectInfo?) -> Unit)? = null) =
TaskRunner(callback, {getProjectInfo(url)})
fun setRunModeAsync(mode: Int, callback: ((Boolean) -> Unit)? = null) =
TaskRunner(callback, {setRunMode(mode)})
fun setNetworkModeAsync(mode: Int, callback: ((Boolean) -> Unit)? = null) =
TaskRunner(callback, {setNetworkMode(mode)})
fun getAccountManagersAsync(callback: ((List<AccountManager>) -> Unit)? = null) =
TaskRunner(callback, {accountManagers})
override fun asBinder(): IBinder {
return monitor.asBinder()
}
override fun attachProject(url: String, projectName: String, authenticator: String): Boolean {
return monitor.attachProject(url, projectName, authenticator)
}
override fun checkProjectAttached(url: String): Boolean {
return monitor.checkProjectAttached(url)
}
override fun lookupCredentials(credentials: AccountIn): AccountOut {
return monitor.lookupCredentials(credentials)
}
override fun projectOp(status: Int, url: String): Boolean {
return monitor.projectOp(status, url)
}
override fun resultOp(op: Int, url: String, name: String): Boolean {
return monitor.resultOp(op, url, name)
}
override fun createAccountPolling(information: AccountIn): AccountOut {
return monitor.createAccountPolling(information)
}
override fun readAuthToken(path: String): String {
return monitor.readAuthToken(path)
}
override fun getProjectConfigPolling(url: String): ProjectConfig {
return monitor.getProjectConfigPolling(url)
}
override fun addAcctMgrErrorNum(url: String, userName: String, pwd: String): ErrorCodeDescription {
return monitor.addAcctMgrErrorNum(url, userName, pwd)
}
override fun getAcctMgrInfo(): AcctMgrInfo {
return monitor.acctMgrInfo
}
override fun synchronizeAcctMgr(url: String): Boolean {
return monitor.synchronizeAcctMgr(url)
}
override fun setRunMode(mode: Int): Boolean {
return monitor.setRunMode(mode)
}
override fun setNetworkMode(mode: Int): Boolean {
return monitor.setNetworkMode(mode)
}
override fun getEventLogMessages(seq: Int, num: Int): List<Message> {
return monitor.getEventLogMessages(seq, num)
}
override fun getMessages(seq: Int): List<Message> {
return monitor.getMessages(seq)
}
override fun getNotices(seq: Int): List<Notice> {
return monitor.getNotices(seq)
}
override fun setCcConfig(config: String): Boolean {
return monitor.setCcConfig(config)
}
override fun setGlobalPreferences(pref: GlobalPreferences): Boolean {
return monitor.setGlobalPreferences(pref)
}
override fun transferOperation(list: List<Transfer>, op: Int): Boolean {
return monitor.transferOperation(list, op)
}
override fun getServerNotices(): List<Notice> {
return monitor.serverNotices
}
override fun runBenchmarks(): Boolean {
return monitor.runBenchmarks()
}
override fun getAttachableProjects(): List<ProjectInfo> {
return monitor.attachableProjects
}
override fun getAccountManagers(): List<AccountManager> {
return monitor.accountManagers
}
override fun getProjectInfo(url: String): ProjectInfo? {
return monitor.getProjectInfo(url)
}
override fun setDomainName(deviceName: String): Boolean {
return monitor.setDomainName(deviceName)
}
override fun boincMutexAcquired(): Boolean {
return monitor.boincMutexAcquired()
}
override fun forceRefresh() {
return monitor.forceRefresh()
}
override fun isStationaryDeviceSuspected(): Boolean {
return monitor.isStationaryDeviceSuspected
}
override fun getBatteryChargeStatus(): Int {
return monitor.batteryChargeStatus
}
override fun getAuthFilePath(): String {
return monitor.authFilePath
}
override fun getBoincPlatform(): Int {
return monitor.boincPlatform
}
override fun cancelNoticeNotification() {
return monitor.cancelNoticeNotification()
}
override fun getWelcomeStateFile(): Boolean {
return monitor.welcomeStateFile
}
override fun setWelcomeStateFile() {
return monitor.setWelcomeStateFile()
}
override fun quitClient(): Boolean {
return monitor.quitClient()
}
override fun getAcctMgrInfoPresent(): Boolean {
return monitor.acctMgrInfoPresent
}
override fun getSetupStatus(): Int {
return monitor.setupStatus
}
override fun getComputingStatus(): Int {
return monitor.computingStatus
}
override fun getComputingSuspendReason(): Int {
return monitor.computingSuspendReason
}
override fun getNetworkSuspendReason(): Int {
return monitor.networkSuspendReason
}
override fun getCurrentStatusTitle(): String {
return monitor.currentStatusTitle
}
override fun getCurrentStatusDescription(): String {
return monitor.currentStatusDescription
}
override fun getHostInfo(): HostInfo {
return monitor.hostInfo
}
override fun getPrefs(): GlobalPreferences {
return monitor.prefs
}
override fun getProjects(): List<Project> {
return monitor.projects
}
override fun getClientAcctMgrInfo(): AcctMgrInfo {
return monitor.clientAcctMgrInfo
}
override fun getTransfers(): List<Transfer> {
return monitor.transfers
}
override fun getTasks(start: Int, count: Int, isActive: Boolean): List<Result> {
return monitor.getTasks(start, count, isActive)
}
override fun getTasksCount(): Int {
return monitor.tasksCount
}
override fun getProjectIconByName(name: String): Bitmap? {
return monitor.getProjectIconByName(name)
}
override fun getProjectIcon(id: String): Bitmap? {
return monitor.getProjectIcon(id)
}
override fun getProjectStatus(url: String): String {
return monitor.getProjectStatus(url)
}
override fun getRssNotices(): List<Notice> {
return monitor.rssNotices
}
override fun getSlideshowForProject(url: String): List<ImageWrapper> {
return monitor.getSlideshowForProject(url)
}
override fun setAutostart(isAutoStart: Boolean) {
monitor.autostart = isAutoStart
}
override fun setShowNotificationForNotices(isShow: Boolean) {
monitor.showNotificationForNotices = isShow
}
override fun getShowAdvanced(): Boolean {
return monitor.showAdvanced
}
override fun getIsRemote(): Boolean {
return monitor.isRemote
}
override fun getAutostart(): Boolean {
return monitor.autostart
}
override fun getShowNotificationForNotices(): Boolean {
return monitor.showNotificationForNotices
}
override fun getLogLevel(): Int {
return monitor.logLevel
}
override fun setLogLevel(level: Int) {
monitor.logLevel = level
}
override fun getLogCategories(): List<String> {
return monitor.logCategories
}
override fun setLogCategories(categories: List<String>) {
monitor.logCategories = categories
}
override fun setPowerSourceAc(src: Boolean) {
monitor.powerSourceAc = src
}
override fun setPowerSourceUsb(src: Boolean) {
monitor.powerSourceUsb = src
}
override fun setPowerSourceWireless(src: Boolean) {
monitor.powerSourceWireless = src
}
override fun getStationaryDeviceMode(): Boolean {
return monitor.stationaryDeviceMode
}
override fun getPowerSourceAc(): Boolean {
return monitor.powerSourceAc
}
override fun getPowerSourceUsb(): Boolean {
return monitor.powerSourceUsb
}
override fun getPowerSourceWireless(): Boolean {
return monitor.powerSourceWireless
}
override fun setShowAdvanced(isShow: Boolean) {
monitor.showAdvanced = isShow
}
override fun setIsRemote(isRemote: Boolean) {
monitor.isRemote = isRemote
}
override fun setStationaryDeviceMode(mode: Boolean) {
monitor.stationaryDeviceMode = mode
}
override fun getSuspendWhenScreenOn(): Boolean {
return monitor.suspendWhenScreenOn
}
override fun setSuspendWhenScreenOn(swso: Boolean) {
monitor.suspendWhenScreenOn = swso
}
}
| lgpl-3.0 | fd64d220e6f4d0fba55b2ef9fc95b462 | 27.790885 | 103 | 0.689729 | 4.620912 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/base/CollapsingToolbarActivity.kt | 1 | 2278 | package de.xikolo.controllers.base
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import butterknife.BindView
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.CollapsingToolbarLayout
import de.xikolo.R
import de.xikolo.R.id.appbar
import de.xikolo.R.id.collapsing_toolbar
abstract class CollapsingToolbarActivity : BaseActivity() {
companion object {
val TAG: String = CollapsingToolbarActivity::class.java.simpleName
}
@BindView(R.id.toolbar_image)
lateinit var imageView: ImageView
@BindView(appbar)
lateinit var appBarLayout: AppBarLayout
@BindView(collapsing_toolbar)
protected lateinit var collapsingToolbar: CollapsingToolbarLayout
@BindView(R.id.scrim_top)
lateinit var scrimTop: View
@BindView(R.id.scrim_bottom)
lateinit var scrimBottom: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_blank_collapsing)
setupActionBar(true)
enableOfflineModeToolbar(false)
}
protected fun lockCollapsingToolbar(title: String) {
appBarLayout.setExpanded(false, false)
val lp = appBarLayout.layoutParams as CoordinatorLayout.LayoutParams
lp.height = actionBarHeight + statusBarHeight
collapsingToolbar.isTitleEnabled = false
toolbar?.title = title
scrimTop.visibility = View.INVISIBLE
scrimBottom.visibility = View.INVISIBLE
}
private val statusBarHeight: Int
get() {
var result = 0
val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
result = application.resources.getDimensionPixelSize(resourceId)
}
return result
}
private val actionBarHeight: Int
get() {
val styledAttributes = theme.obtainStyledAttributes(
intArrayOf(android.R.attr.actionBarSize))
val result = styledAttributes.getDimension(0, 0f).toInt()
styledAttributes.recycle()
return result
}
}
| bsd-3-clause | 3664098fc60082144021fd8d60cdaf74 | 28.973684 | 93 | 0.697981 | 4.995614 | false | false | false | false |
drakeet/MultiType | sample/src/main/kotlin/com/drakeet/multitype/sample/payload/HeavyItemViewBinder.kt | 1 | 2675 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype.sample.payload
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewBinder
import com.drakeet.multitype.sample.R
/**
* @author Drakeet Xu
*/
internal class HeavyItemViewBinder : ItemViewBinder<HeavyItem, HeavyItemViewBinder.ViewHolder>() {
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
return ViewHolder(inflater.inflate(R.layout.item_heavy, parent, false))
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, item: HeavyItem) {
holder.firstText.text = item.text
holder.endText.text = "currentTimeMillis: " + System.currentTimeMillis()
holder.item = item
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, item: HeavyItem, payloads: List<Any>) {
if (payloads.isEmpty()) {
super.onBindViewHolder(holder, item, payloads)
} else {
holder.firstText.text = "Just update the first text: " + payloads[0]
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener {
var firstText: TextView = itemView.findViewById(R.id.first_text)
var endText: TextView = itemView.findViewById(R.id.end_text)
var item: HeavyItem? = null
init {
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
override fun onClick(v: View) {
Toast.makeText(v.context, "Update with a payload", Toast.LENGTH_SHORT).show()
adapter.notifyItemChanged(bindingAdapterPosition, "la la la (payload)")
}
override fun onLongClick(v: View): Boolean {
Toast.makeText(v.context, "Full update", Toast.LENGTH_SHORT).show()
item!!.text = "full full full"
adapter.notifyItemChanged(bindingAdapterPosition)
return true
}
}
}
| apache-2.0 | 8ab175e455de40b186fa7dd5be978cd6 | 33.74026 | 126 | 0.737196 | 4.252782 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/helpers/ErrorMessageDictionary.kt | 1 | 2266 | package com.sapuseven.untis.helpers
import android.content.res.Resources
import com.sapuseven.untis.R
object ErrorMessageDictionary {
/* Original app used the following error codes at the time of writing (may change over time):
InvalidSchool(-8500),
NoSpecifiedUser(-8502),
InvalidPassword(-8504),
NoRight(-8509),
LockedAccess(-8511),
RequiredAuthentication(-8520),
AuthenticationError(-8521),
NoPublicAccess(-8523),
InvalidClientTime(-8524),
InvalidUserStatus(-8525),
InvalidUserRole(-8526),
InvalidTimeTableType(-7001),
InvalidElementId(-7002),
InvalidPersonType(-7003),
InvalidDate(-7004),
UnspecifiedError(-8998);
*/
const val ERROR_CODE_TOO_MANY_RESULTS = -6003
const val ERROR_CODE_INVALID_SCHOOLNAME = -8500
const val ERROR_CODE_INVALID_CREDENTIALS = -8504
const val ERROR_CODE_NO_RIGHT = -8509
const val ERROR_CODE_USER_LOCKED = -8511
const val ERROR_CODE_NO_PUBLIC_ACCESS_AVAILABLE = -8523
const val ERROR_CODE_INVALID_CLIENT_TIME = -8524
const val ERROR_CODE_NO_SERVER_FOUND = 100
const val ERROR_CODE_WEBUNTIS_NOT_INSTALLED = 101
@JvmOverloads
fun getErrorMessage(resources: Resources, code: Int?, fallback: String? = null): String {
return when (code) {
ERROR_CODE_TOO_MANY_RESULTS -> resources.getString(R.string.errormessagedictionary_too_many_results)
ERROR_CODE_INVALID_SCHOOLNAME -> resources.getString(R.string.errormessagedictionary_invalid_school)
ERROR_CODE_INVALID_CREDENTIALS -> resources.getString(R.string.errormessagedictionary_invalid_credentials)
ERROR_CODE_NO_RIGHT -> resources.getString(R.string.errormessagedictionary_no_right)
ERROR_CODE_USER_LOCKED -> resources.getString(R.string.errormessagedictionary_user_locked)
ERROR_CODE_NO_PUBLIC_ACCESS_AVAILABLE -> resources.getString(R.string.errormessagedictionary_no_public_access)
ERROR_CODE_INVALID_CLIENT_TIME -> resources.getString(R.string.errormessagedictionary_invalid_time_settings)
ERROR_CODE_NO_SERVER_FOUND -> resources.getString(R.string.errormessagedictionary_invalid_server_url)
ERROR_CODE_WEBUNTIS_NOT_INSTALLED -> resources.getString(R.string.errormessagedictionary_server_webuntis_not_installed)
else -> fallback ?: resources.getString(R.string.errormessagedictionary_generic)
}
}
}
| gpl-3.0 | 730322a5f7696edf813a67cf27f935ee | 42.576923 | 122 | 0.777582 | 3.260432 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/SensitiveContentWarningDialogFragment.kt | 1 | 2997 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AlertDialog
import org.mariotaku.ktextension.getNullableTypedArray
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.*
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.onShow
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.util.IntentUtils
class SensitiveContentWarningDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
val context = activity ?: return
val args = arguments ?: return
val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY)
val current = args.getParcelable<ParcelableMedia>(EXTRA_CURRENT_MEDIA)
val status = args.getParcelable<ParcelableStatus>(EXTRA_STATUS)
val option = args.getBundle(EXTRA_ACTIVITY_OPTIONS)
val newDocument = args.getBoolean(EXTRA_NEW_DOCUMENT)
val media: Array<ParcelableMedia> = args.getNullableTypedArray(EXTRA_MEDIA) ?: emptyArray()
IntentUtils.openMediaDirectly(context, accountKey, media, current, option, newDocument,
status)
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
val builder = AlertDialog.Builder(context)
builder.setTitle(android.R.string.dialog_alert_title)
builder.setMessage(R.string.sensitive_content_warning)
builder.setPositiveButton(android.R.string.ok, this)
builder.setNegativeButton(android.R.string.cancel, null)
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
return dialog
}
} | gpl-3.0 | 37321eb8a97d6b50ec9a770d85228987 | 41.225352 | 107 | 0.717718 | 4.561644 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/PageSummaryForEdit.kt | 1 | 837 | package org.wikipedia.suggestededits
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.wikipedia.Constants
import org.wikipedia.gallery.ExtMetadata
import org.wikipedia.page.PageTitle
import org.wikipedia.util.ImageUrlUtil
@Parcelize
data class PageSummaryForEdit(
var title: String,
var lang: String,
var pageTitle: PageTitle,
var displayTitle: String?,
var description: String?,
var thumbnailUrl: String?,
var extract: String? = null,
var extractHtml: String? = null,
var timestamp: String? = null,
var user: String? = null,
var metadata: ExtMetadata? = null
) : Parcelable {
fun getPreferredSizeThumbnailUrl(): String = ImageUrlUtil.getUrlForPreferredSize(thumbnailUrl!!, Constants.PREFERRED_CARD_THUMBNAIL_SIZE)
}
| apache-2.0 | 0131b670bcb21f13a7ebf54281eb5139 | 32.48 | 141 | 0.716846 | 4.624309 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/css/Types.kt | 1 | 17751 | package pl.wendigo.chrome.api.css
/**
*
*
* @link [CSS#StyleSheetId](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-StyleSheetId) type documentation.
*/
typealias StyleSheetId = String
/**
* Stylesheet type: "injected" for stylesheets injected via extension, "user-agent" for user-agent
stylesheets, "inspector" for stylesheets created by the inspector (i.e. those holding the "via
inspector" rules), "regular" for regular stylesheets.
*
* @link [CSS#StyleSheetOrigin](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-StyleSheetOrigin) type documentation.
*/
@kotlinx.serialization.Serializable
enum class StyleSheetOrigin {
@kotlinx.serialization.SerialName("injected")
INJECTED,
@kotlinx.serialization.SerialName("user-agent")
USER_AGENT,
@kotlinx.serialization.SerialName("inspector")
INSPECTOR,
@kotlinx.serialization.SerialName("regular")
REGULAR;
}
/**
* CSS rule collection for a single pseudo style.
*
* @link [CSS#PseudoElementMatches](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-PseudoElementMatches) type documentation.
*/
@kotlinx.serialization.Serializable
data class PseudoElementMatches(
/**
* Pseudo element type.
*/
val pseudoType: pl.wendigo.chrome.api.dom.PseudoType,
/**
* Matches of CSS rules applicable to the pseudo style.
*/
val matches: List<RuleMatch>
)
/**
* Inherited CSS rule collection from ancestor node.
*
* @link [CSS#InheritedStyleEntry](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-InheritedStyleEntry) type documentation.
*/
@kotlinx.serialization.Serializable
data class InheritedStyleEntry(
/**
* The ancestor node's inline style, if any, in the style inheritance chain.
*/
val inlineStyle: CSSStyle? = null,
/**
* Matches of CSS rules matching the ancestor node in the style inheritance chain.
*/
val matchedCSSRules: List<RuleMatch>
)
/**
* Match data for a CSS rule.
*
* @link [CSS#RuleMatch](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-RuleMatch) type documentation.
*/
@kotlinx.serialization.Serializable
data class RuleMatch(
/**
* CSS rule in the match.
*/
val rule: CSSRule,
/**
* Matching selector indices in the rule's selectorList selectors (0-based).
*/
val matchingSelectors: List<Int>
)
/**
* Data for a simple selector (these are delimited by commas in a selector list).
*
* @link [CSS#Value](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-Value) type documentation.
*/
@kotlinx.serialization.Serializable
data class Value(
/**
* Value text.
*/
val text: String,
/**
* Value range in the underlying resource (if available).
*/
val range: SourceRange? = null
)
/**
* Selector list data.
*
* @link [CSS#SelectorList](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-SelectorList) type documentation.
*/
@kotlinx.serialization.Serializable
data class SelectorList(
/**
* Selectors in the list.
*/
val selectors: List<Value>,
/**
* Rule selector text.
*/
val text: String
)
/**
* CSS stylesheet metainformation.
*
* @link [CSS#CSSStyleSheetHeader](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSStyleSheetHeader) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSStyleSheetHeader(
/**
* The stylesheet identifier.
*/
val styleSheetId: StyleSheetId,
/**
* Owner frame identifier.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId,
/**
* Stylesheet resource URL.
*/
val sourceURL: String,
/**
* URL of source map associated with the stylesheet (if any).
*/
val sourceMapURL: String? = null,
/**
* Stylesheet origin.
*/
val origin: StyleSheetOrigin,
/**
* Stylesheet title.
*/
val title: String,
/**
* The backend id for the owner node of the stylesheet.
*/
val ownerNode: pl.wendigo.chrome.api.dom.BackendNodeId? = null,
/**
* Denotes whether the stylesheet is disabled.
*/
val disabled: Boolean,
/**
* Whether the sourceURL field value comes from the sourceURL comment.
*/
val hasSourceURL: Boolean? = null,
/**
* Whether this stylesheet is created for STYLE tag by parser. This flag is not set for
document.written STYLE tags.
*/
val isInline: Boolean,
/**
* Whether this stylesheet is mutable. Inline stylesheets become mutable
after they have been modified via CSSOM API.
<link> element's stylesheets become mutable only if DevTools modifies them.
Constructed stylesheets (new CSSStyleSheet()) are mutable immediately after creation.
*/
val isMutable: Boolean,
/**
* Whether this stylesheet is a constructed stylesheet (created using new CSSStyleSheet()).
*/
val isConstructed: Boolean,
/**
* Line offset of the stylesheet within the resource (zero based).
*/
val startLine: Double,
/**
* Column offset of the stylesheet within the resource (zero based).
*/
val startColumn: Double,
/**
* Size of the content (in characters).
*/
val length: Double,
/**
* Line offset of the end of the stylesheet within the resource (zero based).
*/
val endLine: Double,
/**
* Column offset of the end of the stylesheet within the resource (zero based).
*/
val endColumn: Double
)
/**
* CSS rule representation.
*
* @link [CSS#CSSRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSRule) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSRule(
/**
* The css style sheet identifier (absent for user agent stylesheet and user-specified
stylesheet rules) this rule came from.
*/
val styleSheetId: StyleSheetId? = null,
/**
* Rule selector data.
*/
val selectorList: SelectorList,
/**
* Parent stylesheet's origin.
*/
val origin: StyleSheetOrigin,
/**
* Associated style declaration.
*/
val style: CSSStyle,
/**
* Media list array (for rules involving media queries). The array enumerates media queries
starting with the innermost one, going outwards.
*/
val media: List<CSSMedia>? = null
)
/**
* CSS coverage information.
*
* @link [CSS#RuleUsage](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-RuleUsage) type documentation.
*/
@kotlinx.serialization.Serializable
data class RuleUsage(
/**
* The css style sheet identifier (absent for user agent stylesheet and user-specified
stylesheet rules) this rule came from.
*/
val styleSheetId: StyleSheetId,
/**
* Offset of the start of the rule (including selector) from the beginning of the stylesheet.
*/
val startOffset: Double,
/**
* Offset of the end of the rule body from the beginning of the stylesheet.
*/
val endOffset: Double,
/**
* Indicates whether the rule was actually used by some element in the page.
*/
val used: Boolean
)
/**
* Text range within a resource. All numbers are zero-based.
*
* @link [CSS#SourceRange](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-SourceRange) type documentation.
*/
@kotlinx.serialization.Serializable
data class SourceRange(
/**
* Start line of range.
*/
val startLine: Int,
/**
* Start column of range (inclusive).
*/
val startColumn: Int,
/**
* End line of range
*/
val endLine: Int,
/**
* End column of range (exclusive).
*/
val endColumn: Int
)
/**
*
*
* @link [CSS#ShorthandEntry](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-ShorthandEntry) type documentation.
*/
@kotlinx.serialization.Serializable
data class ShorthandEntry(
/**
* Shorthand name.
*/
val name: String,
/**
* Shorthand value.
*/
val value: String,
/**
* Whether the property has "!important" annotation (implies `false` if absent).
*/
val important: Boolean? = null
)
/**
*
*
* @link [CSS#CSSComputedStyleProperty](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSComputedStyleProperty) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSComputedStyleProperty(
/**
* Computed style property name.
*/
val name: String,
/**
* Computed style property value.
*/
val value: String
)
/**
* CSS style representation.
*
* @link [CSS#CSSStyle](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSStyle) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSStyle(
/**
* The css style sheet identifier (absent for user agent stylesheet and user-specified
stylesheet rules) this rule came from.
*/
val styleSheetId: StyleSheetId? = null,
/**
* CSS properties in the style.
*/
val cssProperties: List<CSSProperty>,
/**
* Computed values for all shorthands found in the style.
*/
val shorthandEntries: List<ShorthandEntry>,
/**
* Style declaration text (if available).
*/
val cssText: String? = null,
/**
* Style declaration range in the enclosing stylesheet (if available).
*/
val range: SourceRange? = null
)
/**
* CSS property declaration data.
*
* @link [CSS#CSSProperty](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSProperty) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSProperty(
/**
* The property name.
*/
val name: String,
/**
* The property value.
*/
val value: String,
/**
* Whether the property has "!important" annotation (implies `false` if absent).
*/
val important: Boolean? = null,
/**
* Whether the property is implicit (implies `false` if absent).
*/
val implicit: Boolean? = null,
/**
* The full property text as specified in the style.
*/
val text: String? = null,
/**
* Whether the property is understood by the browser (implies `true` if absent).
*/
val parsedOk: Boolean? = null,
/**
* Whether the property is disabled by the user (present for source-based properties only).
*/
val disabled: Boolean? = null,
/**
* The entire property range in the enclosing style declaration (if available).
*/
val range: SourceRange? = null
)
/**
* CSS media rule descriptor.
*
* @link [CSS#CSSMedia](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSMedia) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSMedia(
/**
* Media query text.
*/
val text: String,
/**
* Source of the media query: "mediaRule" if specified by a @media rule, "importRule" if
specified by an @import rule, "linkedSheet" if specified by a "media" attribute in a linked
stylesheet's LINK tag, "inlineSheet" if specified by a "media" attribute in an inline
stylesheet's STYLE tag.
*/
val source: String,
/**
* URL of the document containing the media query description.
*/
val sourceURL: String? = null,
/**
* The associated rule (@media or @import) header range in the enclosing stylesheet (if
available).
*/
val range: SourceRange? = null,
/**
* Identifier of the stylesheet containing this object (if exists).
*/
val styleSheetId: StyleSheetId? = null,
/**
* Array of media queries.
*/
val mediaList: List<MediaQuery>? = null
)
/**
* Media query descriptor.
*
* @link [CSS#MediaQuery](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-MediaQuery) type documentation.
*/
@kotlinx.serialization.Serializable
data class MediaQuery(
/**
* Array of media query expressions.
*/
val expressions: List<MediaQueryExpression>,
/**
* Whether the media query condition is satisfied.
*/
val active: Boolean
)
/**
* Media query expression descriptor.
*
* @link [CSS#MediaQueryExpression](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-MediaQueryExpression) type documentation.
*/
@kotlinx.serialization.Serializable
data class MediaQueryExpression(
/**
* Media query expression value.
*/
val value: Double,
/**
* Media query expression units.
*/
val unit: String,
/**
* Media query expression feature.
*/
val feature: String,
/**
* The associated range of the value text in the enclosing stylesheet (if available).
*/
val valueRange: SourceRange? = null,
/**
* Computed length of media query expression (if applicable).
*/
val computedLength: Double? = null
)
/**
* Information about amount of glyphs that were rendered with given font.
*
* @link [CSS#PlatformFontUsage](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-PlatformFontUsage) type documentation.
*/
@kotlinx.serialization.Serializable
data class PlatformFontUsage(
/**
* Font's family name reported by platform.
*/
val familyName: String,
/**
* Indicates if the font was downloaded or resolved locally.
*/
val isCustomFont: Boolean,
/**
* Amount of glyphs that were rendered with this font.
*/
val glyphCount: Double
)
/**
* Information about font variation axes for variable fonts
*
* @link [CSS#FontVariationAxis](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-FontVariationAxis) type documentation.
*/
@kotlinx.serialization.Serializable
data class FontVariationAxis(
/**
* The font-variation-setting tag (a.k.a. "axis tag").
*/
val tag: String,
/**
* Human-readable variation name in the default language (normally, "en").
*/
val name: String,
/**
* The minimum value (inclusive) the font supports for this tag.
*/
val minValue: Double,
/**
* The maximum value (inclusive) the font supports for this tag.
*/
val maxValue: Double,
/**
* The default value.
*/
val defaultValue: Double
)
/**
* Properties of a web font: https://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#font-descriptions
and additional information such as platformFontFamily and fontVariationAxes.
*
* @link [CSS#FontFace](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-FontFace) type documentation.
*/
@kotlinx.serialization.Serializable
data class FontFace(
/**
* The font-family.
*/
val fontFamily: String,
/**
* The font-style.
*/
val fontStyle: String,
/**
* The font-variant.
*/
val fontVariant: String,
/**
* The font-weight.
*/
val fontWeight: String,
/**
* The font-stretch.
*/
val fontStretch: String,
/**
* The unicode-range.
*/
val unicodeRange: String,
/**
* The src.
*/
val src: String,
/**
* The resolved platform font family
*/
val platformFontFamily: String,
/**
* Available variation settings (a.k.a. "axes").
*/
val fontVariationAxes: List<FontVariationAxis>? = null
)
/**
* CSS keyframes rule representation.
*
* @link [CSS#CSSKeyframesRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSKeyframesRule) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSKeyframesRule(
/**
* Animation name.
*/
val animationName: Value,
/**
* List of keyframes.
*/
val keyframes: List<CSSKeyframeRule>
)
/**
* CSS keyframe rule representation.
*
* @link [CSS#CSSKeyframeRule](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-CSSKeyframeRule) type documentation.
*/
@kotlinx.serialization.Serializable
data class CSSKeyframeRule(
/**
* The css style sheet identifier (absent for user agent stylesheet and user-specified
stylesheet rules) this rule came from.
*/
val styleSheetId: StyleSheetId? = null,
/**
* Parent stylesheet's origin.
*/
val origin: StyleSheetOrigin,
/**
* Associated key text.
*/
val keyText: Value,
/**
* Associated style declaration.
*/
val style: CSSStyle
)
/**
* A descriptor of operation to mutate style declaration text.
*
* @link [CSS#StyleDeclarationEdit](https://chromedevtools.github.io/devtools-protocol/tot/CSS#type-StyleDeclarationEdit) type documentation.
*/
@kotlinx.serialization.Serializable
data class StyleDeclarationEdit(
/**
* The css style sheet identifier.
*/
val styleSheetId: StyleSheetId,
/**
* The range of the style text in the enclosing stylesheet.
*/
val range: SourceRange,
/**
* New style text.
*/
val text: String
)
| apache-2.0 | 03afc6c8397012f903c23970bd06e03e | 23.383242 | 149 | 0.633429 | 4.271174 | false | false | false | false |
UnsignedInt8/d.Wallet-Core | android/lib/src/main/java/dWallet/core/infrastructure/SocketEx.kt | 1 | 1587 | package dwallet.core.infrastructure
import kotlinx.coroutines.experimental.*
import java.net.InetSocketAddress
import java.net.Socket
/**
* Created by unsignedint8 on 8/14/17.
*/
class SocketEx : Socket() {
var lastException: Exception? = null
fun connect(host: String, port: Int, timeout: Int = Int.MAX_VALUE): Boolean {
lastException = null
try {
super.connect(InetSocketAddress(host, port), timeout)
lastException = null
return true
} catch (e: Exception) {
lastException = e
}
return false
}
suspend fun connectAsync(host: String, port: Int, timeout: Int = Int.MAX_VALUE) = async(CommonPool) { connect(host, port, timeout) }
fun read(size: Int = DEFAULT_BUFFER_SIZE): ByteArray? {
lastException = null
return try {
val data = ByteArray(size)
val readBytes = inputStream.read(data)
if (readBytes == -1) return null
data.take(readBytes).toByteArray()
} catch (e: Exception) {
lastException = e
null
}
}
suspend fun readAsync(size: Int = DEFAULT_BUFFER_SIZE) = async(CommonPool) { read(size) }
fun write(data: ByteArray): Int {
lastException = null
return try {
this.outputStream.write(data)
this.outputStream.flush()
data.size
} catch (e: Exception) {
lastException = e
0
}
}
fun writeAsync(data: ByteArray) = async(CommonPool) { write(data) }
} | gpl-3.0 | cffab45855332ce5af8ee190aa66ef07 | 25.032787 | 136 | 0.582861 | 4.383978 | false | false | false | false |
kotlinz/kotlinz | src/main/kotlin/com/github/kotlinz/kotlinz/data/writer/WriterMonadOps.kt | 1 | 1165 | package com.github.kotlinz.kotlinz.data.writer
import com.github.kotlinz.kotlinz.K1
import com.github.kotlinz.kotlinz.type.group.Monoid
import com.github.kotlinz.kotlinz.type.monad.MonadOps
interface WriterMonadOps<W: Monoid<*, W>>: MonadOps<K1<Writer.T, W>>, WriterMonad<W> {
override fun <A, B> liftM(f: (A) -> B): (K1<K1<Writer.T, W>, A>) -> K1<K1<Writer.T, W>, B> {
return { m ->
val i = Writer.narrow(m)
i bind { x -> Writer.pure(type, f(x)) }
}
}
override fun <A, B, C> liftM2(f: (A, B) -> C): (K1<K1<Writer.T, W>, A>, K1<K1<Writer.T, W>, B>) -> K1<K1<Writer.T, W>, C> {
return { m1, m2 ->
val i1 = Writer.narrow(m1)
val i2 = Writer.narrow(m2)
i1 bind { x1 -> i2 bind { x2 -> Writer.pure(type, f(x1, x2)) } }
}
}
override fun <A, B, C, D> liftM3(f: (A, B, C) -> D): (K1<K1<Writer.T, W>, A>, K1<K1<Writer.T, W>, B>, K1<K1<Writer.T, W>, C>) -> K1<K1<Writer.T, W>, D> {
return { m1, m2, m3 ->
val i1 = Writer.narrow(m1)
val i2 = Writer.narrow(m2)
val i3 = Writer.narrow(m3)
i1 bind { x1 -> i2 bind { x2 -> i3 bind { x3 -> Writer.pure(type, f(x1, x2, x3)) } } }
}
}
}
| apache-2.0 | 34bbbd14e9c225bd47226f3dc0922cfe | 36.580645 | 155 | 0.560515 | 2.344064 | false | false | false | false |
dantman/gradle-mdicons | src/main/kotlin/com.tmiyamon.mdicons/Extension.kt | 1 | 3083 | package com.tmiyamon.mdicons
import com.google.gson.Gson
import java.io.File
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import org.gradle.api.Project
import com.tmiyamon.mdicons.ext.*
open class Extension() {
companion object {
val FILENAME = ".mdicons"
val PROJECT_RESOURCE_RELATIVE_PATH = pathJoin("src", "main", "res")
val CACHE_PATH = pathJoin(System.getProperty("user.home"), ".material_design_icons")
val KEY_PATTERNS = "patterns"
val KEY_ASSETS = "assets"
val KEY_RESULTS = "results"
val SUPPORTED_KEYS_FOR_MAPPING = arrayOf(KEY_PATTERNS, KEY_ASSETS, KEY_RESULTS)
fun loadPreviousConfig(project: Project): Extension {
val prevConfig = project.file(FILENAME)
try {
return if (prevConfig.exists()) {
prevConfig.withReader {
Gson().fromJson(it, javaClass<Extension>())
}
} else {
Extension()
}
} catch(e: Exception) {
return Extension()
}
}
}
val patterns = arrayListOf<String>()
val assets = arrayListOf<Asset>()
val results = arrayListOf<Result>()
fun toMap(
vararg keys: String = SUPPORTED_KEYS_FOR_MAPPING
): Map<String, Any> {
return keys.filter{ SUPPORTED_KEYS_FOR_MAPPING.contains(it) }.toMapWith { key ->
when(key) {
KEY_PATTERNS -> patterns
KEY_ASSETS -> assets
KEY_RESULTS -> results
else -> {}
}
}
}
fun toJson(): String {
return JsonBuilder(toMap()).toString()
}
fun save(project: Project): Unit {
project.file(FILENAME).withWriter { writer ->
writer.write(toJson())
}
}
fun pattern(p: String): Unit {
if (p.isNotEmpty()) {
patterns.add(p)
}
}
fun asset(map: Map<String, Any>) {
val keys = arrayOf("name", "color", "size")
if (map.keySet().intersect(setOf(*keys)).size() != keys.size()) {
warn("Failed to apply parameters(${map}) to asset. All params of name, color and size must be given")
return
}
val (names, colors, sizes) = map.valuesAt(*keys).map {
when(it) {
is Array<*> -> it.map { it.toString() }.toTypedArray()
is List<*> -> it.map { it.toString() }.toTypedArray()
is String -> arrayOf(it)
else -> null
}
}
if (arrayOf(names, colors, sizes).any { it == null }) {
warn("Failed to apply parameters(${map}) to asset. All values must be non-null String, Array or List")
return
}
assets.add(Asset(
names as Array<String>,
colors as Array<String>,
sizes as Array<String>
))
}
fun buildPattern(): String {
return ".*(${patterns.join("|")}).*"
}
}
| apache-2.0 | 594147be6e691c1796d5b08b4835ad16 | 28.361905 | 114 | 0.52384 | 4.404286 | false | false | false | false |
AndroidX/androidx | datastore/datastore-rxjava2/src/main/java/androidx/datastore/rxjava2/RxDataStoreBuilder.kt | 3 | 6961 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.rxjava2
import android.annotation.SuppressLint
import android.content.Context
import androidx.datastore.core.DataMigration
import androidx.datastore.core.DataStoreFactory
import androidx.datastore.core.Serializer
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.dataStoreFile
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.rx2.asCoroutineDispatcher
import kotlinx.coroutines.rx2.await
import java.io.File
import java.util.concurrent.Callable
/**
* Builder class for an RxDataStore that works on a single process.
*/
@SuppressLint("TopLevelBuilder")
public class RxDataStoreBuilder<T : Any> {
/**
* Create a RxDataStoreBuilder with the callable which returns the File that DataStore acts on.
* The user is responsible for ensuring that there is never more than one DataStore acting on
* a file at a time.
*
* @param produceFile Function which returns the file that the new DataStore will act on. The
* function must return the same path every time. No two instances of DataStore should act on
* the same file at the same time.
* @param serializer the serializer for the type that this DataStore acts on.
*/
public constructor(produceFile: Callable<File>, serializer: Serializer<T>) {
this.produceFile = produceFile
this.serializer = serializer
}
/**
* Create a RxDataStoreBuilder with the Context and name from which to derive the DataStore
* file. The file is generated by File(this.filesDir, "datastore/$fileName"). The user is
* responsible for ensuring that there is never more than one DataStore acting on a file at a
* time.
*
* @param context the context from which we retrieve files directory.
* @param fileName the filename relative to Context.applicationContext.filesDir that DataStore
* acts on. The File is obtained from [dataStoreFile]. It is created in the "/datastore"
* subdirectory.
* @param serializer the serializer for the type that this DataStore acts on.
*/
public constructor(context: Context, fileName: String, serializer: Serializer<T>) {
this.context = context
this.name = fileName
this.serializer = serializer
}
// Either produceFile or context & name must be set, but not both. This is enforced by the
// two constructors.
private var produceFile: Callable<File>? = null
private var context: Context? = null
private var name: String? = null
// Required. This is enforced by the constructors.
private var serializer: Serializer<T>? = null
// Optional
private var ioScheduler: Scheduler = Schedulers.io()
private var corruptionHandler: ReplaceFileCorruptionHandler<T>? = null
private val dataMigrations: MutableList<DataMigration<T>> = mutableListOf()
/**
* Set the Scheduler on which to perform IO and transform operations. This is converted into
* a CoroutineDispatcher before being added to DataStore.
*
* This parameter is optional and defaults to Schedulers.io().
*
* @param ioScheduler the scheduler on which IO and transform operations are run
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun setIoScheduler(ioScheduler: Scheduler): RxDataStoreBuilder<T> =
apply { this.ioScheduler = ioScheduler }
/**
* Sets the corruption handler to install into the DataStore.
*
* This parameter is optional and defaults to no corruption handler.
*
* @param corruptionHandler
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun setCorruptionHandler(corruptionHandler: ReplaceFileCorruptionHandler<T>):
RxDataStoreBuilder<T> = apply { this.corruptionHandler = corruptionHandler }
/**
* Add an RxDataMigration to the DataStore. Migrations are run in the order they are added.
*
* @param rxDataMigration the migration to add.
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun addRxDataMigration(rxDataMigration: RxDataMigration<T>): RxDataStoreBuilder<T> =
apply {
this.dataMigrations.add(DataMigrationFromRxDataMigration(rxDataMigration))
}
/**
* Add a DataMigration to the Datastore. Migrations are run in the order they are added.
*
* @param dataMigration the migration to add
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun addDataMigration(dataMigration: DataMigration<T>): RxDataStoreBuilder<T> = apply {
this.dataMigrations.add(dataMigration)
}
/**
* Build the DataStore.
*
* @return the DataStore with the provided parameters
*/
public fun build(): RxDataStore<T> {
val scope = CoroutineScope(ioScheduler.asCoroutineDispatcher() + Job())
val delegateDs = if (produceFile != null) {
DataStoreFactory.create(
produceFile = { produceFile!!.call() },
serializer = serializer!!,
scope = scope,
corruptionHandler = corruptionHandler,
migrations = dataMigrations
)
} else if (context != null && name != null) {
DataStoreFactory.create(
produceFile = { context!!.dataStoreFile(name!!) },
serializer = serializer!!,
scope = scope,
corruptionHandler = corruptionHandler,
migrations = dataMigrations
)
} else {
error("Either produceFile or context and name must be set. This should never happen.")
}
return RxDataStore.create(delegateDs, scope)
}
}
internal class DataMigrationFromRxDataMigration<T>(private val migration: RxDataMigration<T>) :
DataMigration<T> {
override suspend fun shouldMigrate(currentData: T): Boolean {
return migration.shouldMigrate(currentData).await()
}
override suspend fun migrate(currentData: T): T {
return migration.migrate(currentData).await()
}
override suspend fun cleanUp() {
migration.cleanUp().await()
}
}
| apache-2.0 | 912b4525a0159ea9794a40bcfde56c35 | 37.247253 | 99 | 0.69286 | 4.997128 | false | false | false | false |
micabytes/lib_game | src/main/java/com/micabytes/map/HexMap.kt | 2 | 6803 | /*
* Copyright 2013 MicaByte Systems
*
* 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.micabytes.map
import android.content.Context
import android.graphics.*
import com.google.android.gms.common.util.Hex
import com.micabytes.gfx.SurfaceRenderer
import com.micabytes.util.Array2D
import timber.log.Timber
import kotlin.math.max
/**
* HexMap superclass
*
* This implementation works for pointy-side up HexMaps. Needs to be adjusted
* if it is going to be used for flat-side up maps.
*/
abstract class HexMap protected constructor(protected val zones: Array2D<HexTile?>) {
var scaleFactor: Float = 0.toFloat()
val viewPortOrigin = Point()
val viewPortSize = Point()
val destRect = Rect()
var windowLeft: Int = 0
var windowTop: Int = 0
var windowRight: Int = 0
var windowBottom: Int = 0
val tilePaint = Paint()
protected val canvas = Canvas()
var standardOrientation = true
val renderHeight: Int
get() = mapHeight * tileRect.height()
val renderWidth: Int
get() = mapWidth * tileRect.width()
val tileHeight: Int
get() = tileRect.height()
val tileWidth: Int
get() = tileRect.width()
init {
tilePaint.isAntiAlias = true
tilePaint.isFilterBitmap = true
tilePaint.isDither = true
val select = Paint()
select.style = Paint.Style.STROKE
select.color = Color.RED
select.strokeWidth = 2f
}
open fun drawBase(con: Context, p: SurfaceRenderer.ViewPort) {
if (p.bitmap == null) {
Timber.e("Viewport bitmap is null in HexMap")
return
}
canvas.setBitmap(p.bitmap)
scaleFactor = p.zoom
val yOffset = tileRect.height() - tileSlope
p.getOrigin(viewPortOrigin)
p.getSize(viewPortSize)
windowLeft = viewPortOrigin.x
windowTop = viewPortOrigin.y
windowRight = viewPortOrigin.x + viewPortSize.x
windowBottom = viewPortOrigin.y + viewPortSize.y
var xOffset: Int
if (standardOrientation) {
// Clip tiles not in view
var iMn = windowLeft / tileRect.width() - 1
if (iMn < 0) iMn = 0
var jMn = windowTop / (tileRect.height() - tileSlope) - 1
if (jMn < 0) jMn = 0
var iMx = windowRight / tileRect.width() + 2
if (iMx >= mapWidth) iMx = mapWidth
var jMx = windowBottom / (tileRect.height() - tileSlope) + 2
if (jMx >= mapHeight) jMx = mapHeight
// Draw Tiles
for (i in iMn until iMx) {
for (j in jMn until jMx) {
if (zones[i, j] != null) {
xOffset = if (j % 2 == 0) tileRect.width() / 2 else 0
destRect.left = ((i * tileRect.width() - windowLeft - xOffset) / scaleFactor).toInt()
destRect.top = ((j * (tileRect.height() - tileSlope) - windowTop - yOffset) / scaleFactor).toInt()
destRect.right = ((i * tileRect.width() + tileRect.width() - windowLeft - xOffset) / scaleFactor).toInt()
destRect.bottom = ((j * (tileRect.height() - tileSlope) + tileRect.height() - windowTop - yOffset) / scaleFactor).toInt()
zones[i, j]?.drawBase(canvas, tileRect, destRect, tilePaint)
}
}
}
} else {
// Clip tiles not in view
var iMn = mapWidth - windowRight / tileRect.width() - 2
if (iMn < 0) iMn = 0
var jMn = mapHeight - (windowBottom / (tileRect.height() - tileSlope) + 2)
if (jMn < 0) jMn = 0
var iMx = mapWidth - (windowLeft / tileRect.width() + 1)
if (iMx >= mapWidth) iMx = mapWidth - 1
var jMx = mapHeight - (windowTop / (tileRect.height() - tileSlope) + 1)
if (jMx >= mapHeight) jMx = mapHeight - 1
// Draw Tiles
for (i in iMx downTo iMn) {
for (j in jMx downTo jMn) {
if (zones[i, j] != null) {
xOffset = if (j % 2 == 1) tileRect.width() / 2 else 0
destRect.left = (((mapWidth - i - 1) * tileRect.width() - windowLeft - xOffset) / scaleFactor).toInt()
destRect.top = (((mapHeight - j - 1) * (tileRect.height() - tileSlope) - windowTop - yOffset) / scaleFactor).toInt()
destRect.right = (((mapWidth - i - 1) * tileRect.width() + tileRect.width() - windowLeft - xOffset) / scaleFactor).toInt()
destRect.bottom = (((mapHeight - j - 1) * (tileRect.height() - tileSlope) + tileRect.height() - windowTop - yOffset) / scaleFactor).toInt()
zones[i, j]?.drawBase(canvas, tileRect, destRect, tilePaint)
}
}
}
}
}
abstract fun drawLayer(context: Context, p: SurfaceRenderer.ViewPort)
abstract fun drawFinal(context: Context, p: SurfaceRenderer.ViewPort)
abstract fun getViewPortOrigin(x: Int, y: Int, p: SurfaceRenderer.ViewPort): Point
internal fun distance(from: HexTile, to: HexTile): Int =
(Math.abs(from.cubeX - to.cubeX) + Math.abs(from.cubeY - to.cubeY) + Math.abs(from.cubeZ - to.cubeZ)) / 2
fun get(cube: Triple<Int, Int, Int>): HexTile? {
val pos = cubeToOddR(cube)
return zones[pos.first, pos.second]
}
fun hex_linedraw(a: HexTile, b: HexTile): List<HexTile> {
val N = distance(a, b)
val results = ArrayList<HexTile>()
val step: Double = 1.0 / max(N, 1);
for (i in 0..N) {
val cube = cube_round(
hex_lerp(
Triple(a.cubeX.toDouble(), a.cubeY.toDouble(), a.cubeZ.toDouble()),
Triple(b.cubeX.toDouble(), b.cubeY.toDouble(), b.cubeZ.toDouble()),
step * i
)
)
val tile = get(cube)
if (tile != null) results.add(tile)
}
return results;
}
fun isLineOfSight(a: HexTile, b: HexTile): Boolean {
val N = distance(a, b)
val step: Double = 1.0 / max(N, 1);
for (i in 1 until N) {
val cube1 = cube_round(hex_lerp(Triple(a.cubeX + 1e-6, a.cubeY + 1e-6, a.cubeZ - 2e-6), Triple(b.cubeX + 1e-6, b.cubeY + 1e-6, b.cubeZ - 2e-6), step * i))
val cube2 = cube_round(hex_lerp(Triple(a.cubeX - 1e-6, a.cubeY - 1e-6, a.cubeZ + 2e-6), Triple(b.cubeX - 1e-6, b.cubeY - 1e-6, b.cubeZ + 2e-6), step * i))
val tile1 = get(cube1)
val tile2 = get(cube2)
if ((tile1 != a && tile1 != b && tile1?.isOpaque() == true) &&
(tile2 != a && tile2 != b && tile2?.isOpaque() == true)
)
return false
}
return true
}
companion object {
var mapWidth = 0
var mapHeight = 0
var tileSlope = 0
var tileRect = Rect()
}
}
| apache-2.0 | bab91ae0d6027e641a2529de74438fd4 | 35.972826 | 160 | 0.622078 | 3.372831 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.