content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// 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.usages.impl
import com.intellij.util.containers.ContainerUtil
internal class UsageFilteringRuleStateImpl(
private val sharedState: MutableSet<String>
) : UsageFilteringRuleState {
private val localState: MutableSet<String> = ContainerUtil.newConcurrentSet()
init {
localState.addAll(sharedState)
}
/**
* @return whether [ruleId] is active locally, e.g. in the current usage view
*/
override fun isActive(ruleId: String): Boolean = localState.contains(ruleId)
/**
* Sets [ruleId] state to [active] propagating it to [sharedState].
*/
override fun setActive(ruleId: String, active: Boolean) {
if (active) {
localState.add(ruleId)
sharedState.add(ruleId)
}
else {
localState.remove(ruleId)
sharedState.remove(ruleId)
}
}
}
| platform/usageView/src/com/intellij/usages/impl/UsageFilteringRuleStateImpl.kt | 3098107585 |
package be.bluexin.mekre.items.crafting
import be.bluexin.mekre.MetalType
import be.bluexin.mekre.items.IItemVariant
import be.bluexin.mekre.items.MItem
import net.minecraft.item.ItemStack
/**
* Part of mek_re by Bluexin, released under GNU GPLv3.
*
* @author Bluexin
*/
object Ingot : MItem("ingot"), IItemVariant<MetalType> {
override fun get(variant: MetalType, amount: Int) = ItemStack(this, amount, variant.ordinal)
override val variants: Array<MetalType>
get() = MetalType.values()
}
| src/main/java/be/bluexin/mekre/items/crafting/Ingot.kt | 850379555 |
package nestedInlineFun
fun main() {
val a = 1
foo {
val b = 2
//Breakpoint!
val c = 0
}
}
inline fun foo(block: () -> Unit) {
val x = 3
bar(1, block)
}
inline fun bar(count: Int, block: () -> Unit) {
var i = count
while (i-- > 0) {
block()
}
}
// SHOW_KOTLIN_VARIABLES
// PRINT_FRAME | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/nestedInlineFun.kt | 1534121281 |
// 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.debugger
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.cancelledPromise
import org.jetbrains.debugger.values.ObjectValue
import org.jetbrains.debugger.values.ValueManager
abstract class DeclarativeScope<VALUE_MANAGER : ValueManager>(type: ScopeType, description: String? = null) : ScopeBase(type, description) {
protected abstract val childrenManager: VariablesHost<VALUE_MANAGER>
override val variablesHost: VariablesHost<*>
get() = childrenManager
protected fun loadScopeObjectProperties(value: ObjectValue): Promise<List<Variable>> {
if (childrenManager.valueManager.isObsolete) {
return cancelledPromise()
}
return value.properties.onSuccess { childrenManager.updateCacheStamp() }
}
} | platform/script-debugger/backend/src/debugger/DeclarativeScope.kt | 2870347130 |
// MOVE: down
// class A
class A {
// fun foo
<caret>fun foo() {
}
init {
}
} | plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/classBodyDeclarations/function/functionAtClassInitializer1.kt | 4220631752 |
package com.cognifide.gradle.aem.common
import com.cognifide.gradle.aem.AemExtension
import com.cognifide.gradle.aem.AemTask
import com.cognifide.gradle.aem.test.AemTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class CommonPluginTest : AemTest() {
@Test
fun `plugin registers extension`() = usingProject {
plugins.apply(CommonPlugin.ID)
extensions.getByName(AemExtension.NAME)
extensions.getByType(AemExtension::class.java).apply {
val instances = instanceManager.defined.get()
assertEquals(2, instances.size)
instances[0].apply {
assertEquals("local-author", name)
assertTrue(author)
assertNotNull(json)
}
instances[1].apply {
assertEquals("local-publish", name)
assertTrue(publish)
assertNotNull(json)
}
assertEquals("/apps/test/install", packageOptions.installPath.get())
}
assertTrue(
tasks.none { it.group == AemTask.GROUP },
"Common plugin should not provide any tasks which belongs to group AEM."
)
}
}
| src/test/kotlin/com/cognifide/gradle/aem/common/CommonPluginTest.kt | 3075445117 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower.compose.plantdetail
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.ScrollState
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
// Value obtained empirically so that the header buttons don't surpass the header container
private val HeaderTransitionOffset = 190.dp
/**
* Class that contains derived state for when the toolbar should be shown
*/
data class PlantDetailsScroller(
val scrollState: ScrollState,
val namePosition: Float
) {
val toolbarTransitionState = MutableTransitionState(ToolbarState.HIDDEN)
fun getToolbarState(density: Density): ToolbarState {
// When the namePosition is placed correctly on the screen (position > 1f) and it's
// position is close to the header, then show the toolbar.
return if (namePosition > 1f &&
scrollState.value > (namePosition - getTransitionOffset(density))
) {
toolbarTransitionState.targetState = ToolbarState.SHOWN
ToolbarState.SHOWN
} else {
toolbarTransitionState.targetState = ToolbarState.HIDDEN
ToolbarState.HIDDEN
}
}
private fun getTransitionOffset(density: Density): Float = with(density) {
HeaderTransitionOffset.toPx()
}
}
// Toolbar state related classes and functions to achieve the CollapsingToolbarLayout animation
enum class ToolbarState { HIDDEN, SHOWN }
val ToolbarState.isShown
get() = this == ToolbarState.SHOWN
| app/src/main/java/com/google/samples/apps/sunflower/compose/plantdetail/PlantDetailScroller.kt | 1296316720 |
package com.marverenic.reader.ui.home.categories
import android.content.Context
import android.databinding.BaseObservable
import android.databinding.Bindable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import com.marverenic.reader.BR
import com.marverenic.reader.R
import com.marverenic.reader.model.Category
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
class CategoriesViewModel(context: Context,
categories: List<Category>? = null)
: BaseObservable() {
var categories: List<Category>? = categories
set(value) {
adapter.categories = value.orEmpty()
field = value
}
var refreshing: Boolean = (categories == null)
set(value) {
if (value != field) {
refreshSubject.onNext(value)
field = value
notifyPropertyChanged(BR.refreshing)
}
}
@Bindable get() = field
private val refreshSubject = BehaviorSubject.createDefault(refreshing)
val adapter: CategoryAdapter by lazy(mode = LazyThreadSafetyMode.NONE) {
CategoryAdapter().also {
it.categories = categories.orEmpty()
}
}
val layoutManager = LinearLayoutManager(context)
val swipeRefreshColors = intArrayOf(
ContextCompat.getColor(context, R.color.colorPrimary),
ContextCompat.getColor(context, R.color.colorPrimaryDark),
ContextCompat.getColor(context, R.color.colorAccent)
)
fun getRefreshObservable(): Observable<Boolean> = refreshSubject
} | app/src/main/java/com/marverenic/reader/ui/home/categories/CategoriesViewModel.kt | 3741257886 |
// GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.BuildTriggerCause as model_BuildTriggerCause
import io.fabric8.openshift.api.model.GitLabWebHookCause as model_GitLabWebHookCause
fun model_BuildTriggerCause.`gitlabWebHook`(block: model_GitLabWebHookCause.() -> Unit = {}) {
if(this.`gitlabWebHook` == null) {
this.`gitlabWebHook` = model_GitLabWebHookCause()
}
this.`gitlabWebHook`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/gitlabWebHook.kt | 1041499977 |
package com.angusmorton.kedux
import java.util.concurrent.atomic.AtomicBoolean
internal class StoreImpl <S, A>(
override var state: S,
private val reducer: (S, A) -> S,
private val isDispatching: AtomicBoolean = AtomicBoolean(false),
private val subscribers: MutableList<(S) -> Unit> = mutableListOf()
) : Store<S, A> {
override fun dispatch(action: A): A {
if (this.isDispatching.get()) {
throw IllegalStateException("Already dispatching - Check that you're not dispatching an action inside a Reducer, and check that may not dispatch actions")
}
try {
this.isDispatching.set(true)
this.state = this.reducer(this.state, action)
} finally {
this.isDispatching.set(false)
}
// Notify all subscribers
subscribers.forEach { it(this.state) }
return action
}
override fun subscribe(subscriber: (S) -> Unit): Subscription {
this.subscribers.add(subscriber)
return Subscription.create { this.subscribers.remove(subscriber) }
}
} | src/main/kotlin/com/angusmorton/kedux/StoreImpl.kt | 2356863683 |
// GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.ConfigMapFileReference as model_ConfigMapFileReference
import io.fabric8.openshift.api.model.InfrastructureSpec as model_InfrastructureSpec
fun model_InfrastructureSpec.`cloudConfig`(block: model_ConfigMapFileReference.() -> Unit = {}) {
if(this.`cloudConfig` == null) {
this.`cloudConfig` = model_ConfigMapFileReference()
}
this.`cloudConfig`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/cloudConfig.kt | 2313038221 |
package io.vertx.kotlin.ext.web.client
import io.vertx.ext.web.client.WebClientOptions
import io.vertx.core.http.Http2Settings
import io.vertx.core.http.HttpVersion
import io.vertx.core.net.JdkSSLEngineOptions
import io.vertx.core.net.JksOptions
import io.vertx.core.net.OpenSSLEngineOptions
import io.vertx.core.net.PemKeyCertOptions
import io.vertx.core.net.PemTrustOptions
import io.vertx.core.net.PfxOptions
import io.vertx.core.net.ProxyOptions
/**
* A function providing a DSL for building [io.vertx.ext.web.client.WebClientOptions] objects.
*
*
* @param alpnVersions
* @param connectTimeout
* @param crlPaths
* @param crlValues
* @param decoderInitialBufferSize
* @param defaultHost
* @param defaultPort
* @param enabledCipherSuites
* @param enabledSecureTransportProtocols
* @param followRedirects Configure the default behavior of the client to follow HTTP <code>30x</code> redirections.
* @param forceSni
* @param http2ClearTextUpgrade
* @param http2ConnectionWindowSize
* @param http2MaxPoolSize
* @param http2MultiplexingLimit
* @param idleTimeout
* @param initialSettings
* @param jdkSslEngineOptions
* @param keepAlive
* @param keyStoreOptions
* @param localAddress
* @param logActivity
* @param maxChunkSize
* @param maxHeaderSize
* @param maxInitialLineLength
* @param maxPoolSize
* @param maxRedirects
* @param maxWaitQueueSize
* @param maxWebsocketFrameSize
* @param maxWebsocketMessageSize
* @param metricsName
* @param openSslEngineOptions
* @param pemKeyCertOptions
* @param pemTrustOptions
* @param pfxKeyCertOptions
* @param pfxTrustOptions
* @param pipelining
* @param pipeliningLimit
* @param protocolVersion
* @param proxyOptions
* @param receiveBufferSize
* @param reuseAddress
* @param reusePort
* @param sendBufferSize
* @param sendUnmaskedFrames
* @param soLinger
* @param ssl
* @param tcpCork
* @param tcpFastOpen
* @param tcpKeepAlive
* @param tcpNoDelay
* @param tcpQuickAck
* @param trafficClass
* @param trustAll
* @param trustStoreOptions
* @param tryUseCompression
* @param useAlpn
* @param usePooledBuffers
* @param userAgent Sets the Web Client user agent header. Defaults to Vert.x-WebClient/<version>.
* @param userAgentEnabled Sets whether the Web Client should send a user agent header. Defaults to true.
* @param verifyHost
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.web.client.WebClientOptions original] using Vert.x codegen.
*/
fun WebClientOptions(
alpnVersions: Iterable<HttpVersion>? = null,
connectTimeout: Int? = null,
crlPaths: Iterable<String>? = null,
crlValues: Iterable<io.vertx.core.buffer.Buffer>? = null,
decoderInitialBufferSize: Int? = null,
defaultHost: String? = null,
defaultPort: Int? = null,
enabledCipherSuites: Iterable<String>? = null,
enabledSecureTransportProtocols: Iterable<String>? = null,
followRedirects: Boolean? = null,
forceSni: Boolean? = null,
http2ClearTextUpgrade: Boolean? = null,
http2ConnectionWindowSize: Int? = null,
http2MaxPoolSize: Int? = null,
http2MultiplexingLimit: Int? = null,
idleTimeout: Int? = null,
initialSettings: io.vertx.core.http.Http2Settings? = null,
jdkSslEngineOptions: io.vertx.core.net.JdkSSLEngineOptions? = null,
keepAlive: Boolean? = null,
keyStoreOptions: io.vertx.core.net.JksOptions? = null,
localAddress: String? = null,
logActivity: Boolean? = null,
maxChunkSize: Int? = null,
maxHeaderSize: Int? = null,
maxInitialLineLength: Int? = null,
maxPoolSize: Int? = null,
maxRedirects: Int? = null,
maxWaitQueueSize: Int? = null,
maxWebsocketFrameSize: Int? = null,
maxWebsocketMessageSize: Int? = null,
metricsName: String? = null,
openSslEngineOptions: io.vertx.core.net.OpenSSLEngineOptions? = null,
pemKeyCertOptions: io.vertx.core.net.PemKeyCertOptions? = null,
pemTrustOptions: io.vertx.core.net.PemTrustOptions? = null,
pfxKeyCertOptions: io.vertx.core.net.PfxOptions? = null,
pfxTrustOptions: io.vertx.core.net.PfxOptions? = null,
pipelining: Boolean? = null,
pipeliningLimit: Int? = null,
protocolVersion: HttpVersion? = null,
proxyOptions: io.vertx.core.net.ProxyOptions? = null,
receiveBufferSize: Int? = null,
reuseAddress: Boolean? = null,
reusePort: Boolean? = null,
sendBufferSize: Int? = null,
sendUnmaskedFrames: Boolean? = null,
soLinger: Int? = null,
ssl: Boolean? = null,
tcpCork: Boolean? = null,
tcpFastOpen: Boolean? = null,
tcpKeepAlive: Boolean? = null,
tcpNoDelay: Boolean? = null,
tcpQuickAck: Boolean? = null,
trafficClass: Int? = null,
trustAll: Boolean? = null,
trustStoreOptions: io.vertx.core.net.JksOptions? = null,
tryUseCompression: Boolean? = null,
useAlpn: Boolean? = null,
usePooledBuffers: Boolean? = null,
userAgent: String? = null,
userAgentEnabled: Boolean? = null,
verifyHost: Boolean? = null): WebClientOptions = io.vertx.ext.web.client.WebClientOptions().apply {
if (alpnVersions != null) {
this.setAlpnVersions(alpnVersions.toList())
}
if (connectTimeout != null) {
this.setConnectTimeout(connectTimeout)
}
if (crlPaths != null) {
for (item in crlPaths) {
this.addCrlPath(item)
}
}
if (crlValues != null) {
for (item in crlValues) {
this.addCrlValue(item)
}
}
if (decoderInitialBufferSize != null) {
this.setDecoderInitialBufferSize(decoderInitialBufferSize)
}
if (defaultHost != null) {
this.setDefaultHost(defaultHost)
}
if (defaultPort != null) {
this.setDefaultPort(defaultPort)
}
if (enabledCipherSuites != null) {
for (item in enabledCipherSuites) {
this.addEnabledCipherSuite(item)
}
}
if (enabledSecureTransportProtocols != null) {
for (item in enabledSecureTransportProtocols) {
this.addEnabledSecureTransportProtocol(item)
}
}
if (followRedirects != null) {
this.setFollowRedirects(followRedirects)
}
if (forceSni != null) {
this.setForceSni(forceSni)
}
if (http2ClearTextUpgrade != null) {
this.setHttp2ClearTextUpgrade(http2ClearTextUpgrade)
}
if (http2ConnectionWindowSize != null) {
this.setHttp2ConnectionWindowSize(http2ConnectionWindowSize)
}
if (http2MaxPoolSize != null) {
this.setHttp2MaxPoolSize(http2MaxPoolSize)
}
if (http2MultiplexingLimit != null) {
this.setHttp2MultiplexingLimit(http2MultiplexingLimit)
}
if (idleTimeout != null) {
this.setIdleTimeout(idleTimeout)
}
if (initialSettings != null) {
this.setInitialSettings(initialSettings)
}
if (jdkSslEngineOptions != null) {
this.setJdkSslEngineOptions(jdkSslEngineOptions)
}
if (keepAlive != null) {
this.setKeepAlive(keepAlive)
}
if (keyStoreOptions != null) {
this.setKeyStoreOptions(keyStoreOptions)
}
if (localAddress != null) {
this.setLocalAddress(localAddress)
}
if (logActivity != null) {
this.setLogActivity(logActivity)
}
if (maxChunkSize != null) {
this.setMaxChunkSize(maxChunkSize)
}
if (maxHeaderSize != null) {
this.setMaxHeaderSize(maxHeaderSize)
}
if (maxInitialLineLength != null) {
this.setMaxInitialLineLength(maxInitialLineLength)
}
if (maxPoolSize != null) {
this.setMaxPoolSize(maxPoolSize)
}
if (maxRedirects != null) {
this.setMaxRedirects(maxRedirects)
}
if (maxWaitQueueSize != null) {
this.setMaxWaitQueueSize(maxWaitQueueSize)
}
if (maxWebsocketFrameSize != null) {
this.setMaxWebsocketFrameSize(maxWebsocketFrameSize)
}
if (maxWebsocketMessageSize != null) {
this.setMaxWebsocketMessageSize(maxWebsocketMessageSize)
}
if (metricsName != null) {
this.setMetricsName(metricsName)
}
if (openSslEngineOptions != null) {
this.setOpenSslEngineOptions(openSslEngineOptions)
}
if (pemKeyCertOptions != null) {
this.setPemKeyCertOptions(pemKeyCertOptions)
}
if (pemTrustOptions != null) {
this.setPemTrustOptions(pemTrustOptions)
}
if (pfxKeyCertOptions != null) {
this.setPfxKeyCertOptions(pfxKeyCertOptions)
}
if (pfxTrustOptions != null) {
this.setPfxTrustOptions(pfxTrustOptions)
}
if (pipelining != null) {
this.setPipelining(pipelining)
}
if (pipeliningLimit != null) {
this.setPipeliningLimit(pipeliningLimit)
}
if (protocolVersion != null) {
this.setProtocolVersion(protocolVersion)
}
if (proxyOptions != null) {
this.setProxyOptions(proxyOptions)
}
if (receiveBufferSize != null) {
this.setReceiveBufferSize(receiveBufferSize)
}
if (reuseAddress != null) {
this.setReuseAddress(reuseAddress)
}
if (reusePort != null) {
this.setReusePort(reusePort)
}
if (sendBufferSize != null) {
this.setSendBufferSize(sendBufferSize)
}
if (sendUnmaskedFrames != null) {
this.setSendUnmaskedFrames(sendUnmaskedFrames)
}
if (soLinger != null) {
this.setSoLinger(soLinger)
}
if (ssl != null) {
this.setSsl(ssl)
}
if (tcpCork != null) {
this.setTcpCork(tcpCork)
}
if (tcpFastOpen != null) {
this.setTcpFastOpen(tcpFastOpen)
}
if (tcpKeepAlive != null) {
this.setTcpKeepAlive(tcpKeepAlive)
}
if (tcpNoDelay != null) {
this.setTcpNoDelay(tcpNoDelay)
}
if (tcpQuickAck != null) {
this.setTcpQuickAck(tcpQuickAck)
}
if (trafficClass != null) {
this.setTrafficClass(trafficClass)
}
if (trustAll != null) {
this.setTrustAll(trustAll)
}
if (trustStoreOptions != null) {
this.setTrustStoreOptions(trustStoreOptions)
}
if (tryUseCompression != null) {
this.setTryUseCompression(tryUseCompression)
}
if (useAlpn != null) {
this.setUseAlpn(useAlpn)
}
if (usePooledBuffers != null) {
this.setUsePooledBuffers(usePooledBuffers)
}
if (userAgent != null) {
this.setUserAgent(userAgent)
}
if (userAgentEnabled != null) {
this.setUserAgentEnabled(userAgentEnabled)
}
if (verifyHost != null) {
this.setVerifyHost(verifyHost)
}
}
| vertx-web-client/src/main/kotlin/io/vertx/kotlin/ext/web/client/WebClientOptions.kt | 3168624951 |
package ru.qdev.lnotes.mvp
import android.support.annotation.AnyThread
import android.support.annotation.MainThread
import android.support.annotation.UiThread
import com.arellomobile.mvp.InjectViewState
import com.arellomobile.mvp.MvpPresenter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import ru.qdev.lnotes.db.entity.QDVDbFolder
import ru.qdev.lnotes.db.entity.QDVDbNote
/**
* Created by Vladimir Kudashov on 04.10.18.
*/
@InjectViewState
class QDVNotesHomePresenter : MvpPresenter <QDVNotesHomeView> () {
private val state: QDVNotesHomeState = QDVNotesHomeState()
var editNoteFilterState = QDVFilterByFolderState()
init {
EventBus.getDefault().register(this)
}
@UiThread
fun doSelectFolder (filterType: QDVFilterByFolderState.FilterType, folder: QDVDbFolder?) {
editNoteFilterState = QDVFilterByFolderState()
editNoteFilterState.filterType = filterType
if (filterType == QDVFilterByFolderState.FilterType.FOLDER_ID) {
editNoteFilterState.folderId = folder?.id
} else {
editNoteFilterState.folder = folder
}
state.uiState = QDVNotesHomeState.UiState.LIST
viewState.initNotesList(editNoteFilterState)
stateChanged()
}
class DoSelectFolderEvent (val filterType: QDVFilterByFolderState.FilterType,
val folder: QDVDbFolder?)
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoSelectFolderEvent) {
doSelectFolder(event.filterType, event.folder)
}
@UiThread
fun doEditNote (note: QDVDbNote) {
state.uiState = QDVNotesHomeState.UiState.EDIT
viewState.initEditNote(note)
stateChanged()
}
class DoEditNoteEvent (val note: QDVDbNote)
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoEditNoteEvent) {
doEditNote(event.note)
}
@UiThread
fun doAddNote (folderIdForAdding: Long?) {
state.uiState = QDVNotesHomeState.UiState.EDIT
viewState.initAddNote(folderIdForAdding)
stateChanged()
}
class DoAddNoteEvent(val folderIdForAdding: Long? = null)
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoAddNoteEvent) {
doAddNote(event.folderIdForAdding)
}
@UiThread
fun doGoBack () {
if (state.uiState == QDVNotesHomeState.UiState.EDIT) {
viewState.initNotesList(editNoteFilterState)
viewState.setNavigationDrawerFolderEnabled(true)
state.uiState = QDVNotesHomeState.UiState.LIST
stateChanged()
}
}
@UiThread
private fun stateChanged(){
if (state.uiState == QDVNotesHomeState.UiState.LIST &&
QDVStatisticState.isTimeForShowUserRatingQuest()) {
viewState.showUserRatingQuest()
}
}
class DoGoBackEvent
@Subscribe(threadMode = ThreadMode.MAIN)
@MainThread
fun onEvent(event: DoGoBackEvent) {
doGoBack()
}
@AnyThread
fun onFolderNameClick() {
EventBus.getDefault().post(QDVNavigationDrawerPresenter.DoDrawerOpenOrClose())
}
@AnyThread
fun doReloadDb() {
QDVNavigationDrawerState().selectedFolderOrMenu = null
EventBus.getDefault().post(QDVMvpDbPresenter.DoCloseDatabase())
EventBus.getDefault().post(QDVMvpDbPresenter.DoReloadDatabase())
}
@AnyThread
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
} | app/src/main/java/ru/qdev/lnotes/mvp/QDVNotesHomePresenter.kt | 794638157 |
package io.kotest.engine.extensions
import io.kotest.core.Tags
import io.kotest.core.config.configuration
import io.kotest.core.extensions.DiscoveryExtension
import io.kotest.core.spec.Spec
import io.kotest.core.internal.tags.isPotentiallyActive
import io.kotest.core.internal.tags.parse
import io.kotest.core.internal.tags.activeTags
import kotlin.reflect.KClass
/**
* Filters any [Spec] that can be eagerly excluded based on the @[Tags] annotation at the class level.
*/
object TagsExcludedDiscoveryExtension : DiscoveryExtension {
fun afterScan(classes: List<KClass<out Spec>>, tags: Tags): List<KClass<out Spec>> {
return classes.filter { tags.parse().isPotentiallyActive(it) }
}
override fun afterScan(classes: List<KClass<out Spec>>): List<KClass<out Spec>> {
return afterScan(classes, configuration.activeTags())
}
}
| kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io.kotest.engine/extensions/TagsExcludedDiscoveryExtension.kt | 879366019 |
package com.ivanovsky.passnotes.domain.entity.filter
import com.ivanovsky.passnotes.data.entity.Property
class FilterByNameAndValueStrategy(
private val name: String,
private val value: String
) : PropertyFilterStrategy {
override fun apply(properties: Sequence<Property>): Sequence<Property> {
return properties.filter { it.name == name && it.value == value }
}
} | app/src/main/kotlin/com/ivanovsky/passnotes/domain/entity/filter/FilterByNameAndValueStrategy.kt | 2902598940 |
package <%= appPackage %>.domain.interactor
import <%= appPackage %>.domain.check.Preconditions
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.disposables.Disposable
/**
* Created by nelo on 16/2/17.
*/
abstract class UseCase<T, Params> {
val uiThread: Scheduler
val mExecutorThread: Scheduler
var disposables: CompositeDisposable
constructor(uiThread: Scheduler, mExecutorThread: Scheduler){
this.uiThread = uiThread
this.mExecutorThread = mExecutorThread
this.disposables = CompositeDisposable()
}
abstract fun buildUseCaseObservable(params: Params): Observable<T>
open fun execute(observer: DisposableObserver<T>, params: Params) {
Preconditions.checkNotNull(params)
Preconditions.checkNotNull(observer)
val observable: Observable<T> = this.buildUseCaseObservable(params)
.subscribeOn(mExecutorThread)
.observeOn(uiThread)
addDisposable(observable.subscribeWith(observer))
}
fun dispose() {
if (!disposables.isDisposed) {
disposables.dispose()
}
}
private fun addDisposable(disposable: Disposable) {
Preconditions.checkNotNull(disposable)
Preconditions.checkNotNull(disposables)
disposables.add(disposable)
}
} | generators/app/templates/clean-architecture/domain/src/main/kotlin/com/nelosan/clean/domain/interactor/UseCase.kt | 4133973815 |
package tel.egram.kuery.dml
import tel.egram.kuery.*
class LimitClause<T: Table>(
val limit: Any,
val subject: Subject<T>,
val whereClause: WhereClause<T>?,
val orderClause: OrderClause<T>?,
val groupClause: GroupClause<T>?,
val havingClause: HavingClause<T>?) {
inline fun offset(offset: () -> Any): OffsetClause<T> {
return OffsetClause(
offset(),
this,
subject,
whereClause,
orderClause,
groupClause,
havingClause)
}
inline fun select(projection: (T) -> Iterable<Projection>): SelectStatement<T> {
return SelectStatement(
projection(subject.table),
subject,
whereClause,
orderClause,
this,
null,
groupClause,
havingClause)
}
}
class Limit2Clause<T: Table, T2: Table>(
val limit: Any,
val joinOn2Clause: JoinOn2Clause<T, T2>,
val where2Clause: Where2Clause<T, T2>?,
val order2Clause: Order2Clause<T, T2>?,
val group2Clause: Group2Clause<T, T2>?,
val having2Clause: Having2Clause<T, T2>?) {
inline fun offset(offset: () -> Any): Offset2Clause<T, T2> {
return Offset2Clause(
offset(),
this,
joinOn2Clause,
where2Clause,
order2Clause,
group2Clause,
having2Clause)
}
inline fun select(projection: (T, T2) -> Iterable<Projection>): Select2Statement<T, T2> {
return Select2Statement(
projection(joinOn2Clause.subject.table, joinOn2Clause.table2),
joinOn2Clause,
where2Clause,
order2Clause,
this,
null,
group2Clause,
having2Clause)
}
}
class Limit3Clause<T: Table, T2: Table, T3: Table>(
val limit: Any,
val joinOn3Clause: JoinOn3Clause<T, T2, T3>,
val where3Clause: Where3Clause<T, T2, T3>?,
val order3Clause: Order3Clause<T, T2, T3>?,
val group3Clause: Group3Clause<T, T2, T3>?,
val having3Clause: Having3Clause<T, T2, T3>?) {
inline fun offset(offset: () -> Any): Offset3Clause<T, T2, T3> {
return Offset3Clause(
offset(),
this,
joinOn3Clause,
where3Clause,
order3Clause,
group3Clause,
having3Clause)
}
inline fun select(projection: (T, T2, T3) -> Iterable<Projection>): Select3Statement<T, T2, T3> {
return Select3Statement(
projection(joinOn3Clause.joinOn2Clause.subject.table, joinOn3Clause.joinOn2Clause.table2, joinOn3Clause.table3),
joinOn3Clause,
where3Clause,
order3Clause,
this,
null,
group3Clause,
having3Clause)
}
}
class Limit4Clause<T: Table, T2: Table, T3: Table, T4: Table>(
val limit: Any,
val joinOn4Clause: JoinOn4Clause<T, T2, T3, T4>,
val where4Clause: Where4Clause<T, T2, T3, T4>?,
val order4Clause: Order4Clause<T, T2, T3, T4>?,
val group4Clause: Group4Clause<T, T2, T3, T4>?,
val having4Clause: Having4Clause<T, T2, T3, T4>?) {
inline fun offset(offset: () -> Any): Offset4Clause<T, T2, T3, T4> {
return Offset4Clause(
offset(),
this,
joinOn4Clause,
where4Clause,
order4Clause,
group4Clause,
having4Clause)
}
inline fun select(projection: (T, T2, T3, T4) -> Iterable<Projection>): Select4Statement<T, T2, T3, T4> {
return Select4Statement(
projection(
joinOn4Clause.joinOn3Clause.joinOn2Clause.subject.table,
joinOn4Clause.joinOn3Clause.joinOn2Clause.table2,
joinOn4Clause.joinOn3Clause.table3,
joinOn4Clause.table4
),
joinOn4Clause,
where4Clause,
order4Clause,
this,
null,
group4Clause,
having4Clause)
}
} | core/src/tel/egram/kuery/dml/LimitClause.kt | 2701535443 |
package com.quran.mobile.feature.downloadmanager.ui.sheikhdownload
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Text
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.quran.common.search.SearchTextUtil
import com.quran.mobile.feature.downloadmanager.model.sheikhdownload.SuraOption
@Composable
fun AutoCompleteDropdown(
label: String,
initialText: String,
items: List<SuraOption>,
onItemSelected: ((Int) -> Unit)
) {
val textState = remember { mutableStateOf(TextFieldValue(initialText)) }
val isExpanded = remember { mutableStateOf(false) }
val restoreSelection = remember { mutableStateOf(false) }
val filtered by remember(items) {
derivedStateOf {
val searchTerm = SearchTextUtil.asSearchableString(
textState.value.text,
SearchTextUtil.isRtl(textState.value.text)
)
// if you typed in "١٢" for example, `toIntOrNull` would give you 12.
val numericSearchTerm = searchTerm.toIntOrNull()
items.filter {
it.searchName.contains(searchTerm, ignoreCase = true) ||
// support English numbers in Arabic search
it.number == numericSearchTerm
}
}
}
ExposedDropdownMenuBox(
expanded = isExpanded.value,
onExpandedChange = { isExpanded.value = !isExpanded.value }
) {
TextField(
value = textState.value,
onValueChange = {
if (restoreSelection.value) {
textState.value = it.copy(selection = TextRange(0, it.text.length))
restoreSelection.value = false
} else {
textState.value = it
}
},
label = { Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant) },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(
expanded = isExpanded.value
)
},
colors = ExposedDropdownMenuDefaults.textFieldColors(),
modifier = Modifier.onFocusChanged { focusState ->
if (focusState.isFocused) {
val text = textState.value.text
textState.value = textState.value.copy(selection = TextRange(0, text.length))
restoreSelection.value = true
}
}
)
if (filtered.isNotEmpty()) {
ExposedDropdownMenu(
expanded = isExpanded.value,
onDismissRequest = { isExpanded.value = false },
modifier = Modifier.heightIn(max = 150.dp)
) {
filtered.forEach {
DropdownMenuItem(
onClick = {
textState.value = textState.value.copy(text = it.name)
isExpanded.value = false
onItemSelected(it.number)
}
) {
Text(it.name, color = MaterialTheme.colorScheme.onSecondaryContainer)
}
}
}
}
}
}
| feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/sheikhdownload/AutoCompleteDropdown.kt | 794170516 |
package se.accepted.krib
/**
* IMarker
* @author Bob Dahlberg
*/
interface IMarker
| krib/src/test/java/se/accepted/krib/IMarker.kt | 835152549 |
package com.netflix.spinnaker.kork.plugins.events
import com.netflix.spinnaker.kork.plugins.remote.RemotePluginsCache
import org.springframework.context.ApplicationEvent
/**
* A Spring [ApplicationEvent] that is emitted when the remote plugins cache is changed.
*
* The remote plugins cache is the cache of resolved remote plugins with remote transport
* clients. This can optionally be used in Spinnaker services to ensure a remote
* extension point implementation has the latest cached version of the remote plugin.
*
* @param source The source of the event
* @param pluginId The plugin ID that triggered this cache refresh event
*/
data class RemotePluginCacheRefresh(
private val source: RemotePluginsCache,
val pluginId: String
) : ApplicationEvent(source)
| kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/events/RemotePluginCacheRefresh.kt | 1245413614 |
/*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.contact
import io.reactivex.disposables.CompositeDisposable
import pl.org.seva.navigator.main.data.fb.fbReader
import pl.org.seva.navigator.main.init.instance
val friendshipObservable by instance<FriendshipObservable>()
fun cleanFriendshipListeners() = friendshipObservable.clearFriendshipListeners()
fun addFriendshipListener() = friendshipObservable addFriendshipListener friendshipListener
class FriendshipObservable {
private val cd = CompositeDisposable()
infix fun addFriendshipListener(friendshipListener: FriendshipListener) = with (fbReader) {
cd.addAll(
friendshipRequestedListener()
.subscribe { friendshipListener.onPeerRequestedFriendship(it) },
friendshipAcceptedListener()
.subscribe { friendshipListener.onPeerAcceptedFriendship(it) },
friendshipDeletedListener()
.subscribe { friendshipListener.onPeerDeletedFriendship(it) })
}
fun clearFriendshipListeners() = cd.clear()
}
| navigator/src/main/kotlin/pl/org/seva/navigator/contact/FriendshipObservable.kt | 1498012138 |
package com.github.badoualy.telegram.mtproto.tl.auth
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import com.github.badoualy.telegram.tl.core.TLLongVector
import com.github.badoualy.telegram.tl.core.TLObject
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class ResPQ @JvmOverloads constructor(var nonce: ByteArray = ByteArray(0),
var serverNonce: ByteArray = ByteArray(0),
var pq: ByteArray = ByteArray(0),
var fingerprints: TLLongVector = TLLongVector()) : TLObject() {
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeByteArray(nonce, stream)
writeByteArray(serverNonce, stream)
writeTLBytes(pq, stream)
writeTLVector(fingerprints, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
nonce = readBytes(16, stream)
serverNonce = readBytes(16, stream)
pq = readTLBytes(stream)
fingerprints = readTLLongVector(stream, context)
}
override fun toString(): String {
return "resPQ#05162463"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = 85337187
}
}
| mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/auth/ResPQ.kt | 1661946399 |
package org.evomaster.core.problem.rest
import io.swagger.parser.OpenAPIParser
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class SwaggerParserTest {
@Test
fun testSchemeAndHost(){
val location = "/swagger/sut/ncs.json"
val schema = OpenAPIParser().readLocation(location, null, null).openAPI
assertEquals(1, schema.servers.size)
val url = schema.servers[0].url
assertEquals("http://localhost:8080/", url)
}
@Test
fun testHostNoScheme(){
val location = "/swagger/sut/gestaohospital.json"
val schema = OpenAPIParser().readLocation(location, null, null).openAPI
assertEquals(1, schema.servers.size)
val url = schema.servers[0].url
//technically invalid. to be used, would need to be repaired
assertEquals("//localhost:8080/", url)
}
@Test
fun testMultiSchemes(){
val location = "/swagger/sut/disease_sh_api.json"
val schema = OpenAPIParser().readLocation(location, null, null).openAPI
assertEquals(2, schema.servers.size)
assertEquals("https://disease.sh/", schema.servers[0].url)
assertEquals("http://disease.sh/", schema.servers[1].url)
}
} | core/src/test/kotlin/org/evomaster/core/problem/rest/SwaggerParserTest.kt | 79030970 |
package com.openconference.splash
import com.openconference.model.ScheduleDataAwareObservableFactory
import com.openconference.model.errormessage.ErrorMessageDeterminer
import com.openconference.util.RxPresenter
import com.openconference.util.SchedulerTransformer
import rx.Observable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
/**
*
*
* @author Hannes Dorfmann
*/
class SplashPresenter @Inject constructor(schedulerTransformer: SchedulerTransformer,
errorMessageDeterminer: ErrorMessageDeterminer, private val observableFactory: ScheduleDataAwareObservableFactory) : RxPresenter<SplashView>(
schedulerTransformer,
errorMessageDeterminer) {
fun start() {
// Preload data in background
subscribe(observableFactory.create(Observable.just(1)),
{},
{},
{}
) // no callbacks needed
// wait for two seconds
val timer = Observable.timer(1500, TimeUnit.MILLISECONDS)
subscribe(
timer,
{ // onNext
},
{
// onError
view?.finishSplash()
},
{
// onCompleted (timer just fire onCompleted)
view?.finishSplash()
}
)
}
} | app/src/main/java/com/openconference/splash/SplashPresenter.kt | 2969584296 |
package com.antonioleiva.weatherapp.data.db
object CityForecastTable {
const val NAME = "CityForecast"
const val ID = "_id"
const val CITY = "city"
const val COUNTRY = "country"
}
object DayForecastTable {
const val NAME = "DayForecast"
const val ID = "_id"
const val DATE = "date"
const val DESCRIPTION = "description"
const val HIGH = "high"
const val LOW = "low"
const val ICON_URL = "iconUrl"
const val CITY_ID = "cityId"
} | app/src/main/java/com/antonioleiva/weatherapp/data/db/Tables.kt | 2137361032 |
/*
Copyright (C) 2013-2020 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.admin.handlers
import ch.qos.logback.classic.Level
import com.hotels.styx.api.Eventual
import com.hotels.styx.api.HttpInterceptor
import com.hotels.styx.api.HttpRequest
import com.hotels.styx.api.HttpRequest.post
import com.hotels.styx.api.HttpResponse
import com.hotels.styx.api.HttpResponse.response
import com.hotels.styx.api.HttpResponseStatus.ACCEPTED
import com.hotels.styx.api.HttpResponseStatus.CREATED
import com.hotels.styx.api.HttpResponseStatus.INTERNAL_SERVER_ERROR
import com.hotels.styx.api.HttpResponseStatus.NO_CONTENT
import com.hotels.styx.api.HttpResponseStatus.OK
import com.hotels.styx.requestContext
import com.hotels.styx.support.matchers.LoggingTestSupport
import io.kotlintest.shouldBe
import io.kotlintest.specs.FeatureSpec
import reactor.core.publisher.toMono
import java.util.Optional
import java.util.concurrent.atomic.AtomicReference
class UrlPatternRouterTest : FeatureSpec({
val LOGGER = LoggingTestSupport(UrlPatternRouter::class.java);
val router = UrlPatternRouter.Builder()
.get("/admin/apps/:appId") { request, context ->
Eventual.of(
response(OK)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build())
}
.get("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(OK)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build())
}
.post("/admin/apps/:appId") { request, context ->
Eventual.of(
response(CREATED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build()
)
}
.post("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(CREATED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build()
)
}
.put("/admin/apps/:appId") { request, context ->
Eventual.of(
response(NO_CONTENT)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build()
)
}
.put("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(NO_CONTENT)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build()
)
}
.delete("/admin/apps/:appId") { request, context ->
Eventual.of(
response(ACCEPTED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.build()
)
}
.delete("/admin/apps/:appId/origin/:originId") { request, context ->
Eventual.of(
response(ACCEPTED)
.header("appId", UrlPatternRouter.placeholders(context)["appId"])
.header("originId", UrlPatternRouter.placeholders(context)["originId"])
.build()
)
}
.build()
feature("Request routing") {
scenario("GET requests") {
val response1 = router.handle(HttpRequest.get("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe OK
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.get("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe OK
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
scenario("POST requests") {
val response1 = router.handle(HttpRequest.post("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe CREATED
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.post("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe CREATED
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
scenario("PUT requests") {
val response1 = router.handle(HttpRequest.put("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe NO_CONTENT
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.put("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe NO_CONTENT
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
scenario("DELETE requests") {
val response1 = router.handle(HttpRequest.delete("/admin/apps/234").build(), requestContext())
.toMono()
.block()
response1!!.status() shouldBe ACCEPTED
response1.header("appId") shouldBe Optional.of("234")
response1.header("originId") shouldBe Optional.empty()
val response2 = router.handle(HttpRequest.delete("/admin/apps/234/origin/123").build(), requestContext())
.toMono()
.block()
response2!!.status() shouldBe ACCEPTED
response2.header("appId") shouldBe Optional.of("234")
response2.header("originId") shouldBe Optional.of("123")
}
}
feature("Route Callbacks Invocation") {
scenario("Catches and logs user exceptions") {
val contextCapture = AtomicReference<HttpInterceptor.Context>()
val router = UrlPatternRouter.Builder()
.post("/admin/apps/:appId/:originId") { request, context -> throw RuntimeException("Something went wrong") }
.build()
val response = router.handle(post("/admin/apps/appx/appx-01").build(), requestContext())
.toMono()
.block()
response!!.status() shouldBe INTERNAL_SERVER_ERROR
LOGGER.lastMessage().level shouldBe Level.ERROR
LOGGER.lastMessage().formattedMessage shouldBe "ERROR: POST /admin/apps/appx/appx-01"
}
}
feature("Placeholders") {
scenario("Are exposed in HTTP context") {
val contextCapture = AtomicReference<HttpInterceptor.Context>()
val router = UrlPatternRouter.Builder()
.post("/admin/apps/:appId/:originId") { request, context ->
contextCapture.set(context)
Eventual.of<HttpResponse>(response(OK).build())
}
.build()
val response = router.handle(post("/admin/apps/appx/appx-01").build(), requestContext())
.toMono()
.block()
response!!.status() shouldBe OK
val placeholders = UrlPatternRouter.placeholders(contextCapture.get())
placeholders["appId"] shouldBe "appx"
placeholders["originId"] shouldBe "appx-01"
}
}
}) | components/proxy/src/test/kotlin/com/hotels/styx/admin/handlers/UrlPatternRouterTest.kt | 1809341339 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.api
/** Returns whether or not the receiving [Class] represents a [ReadConnection]. */
val Class<*>.isReadConnection: Boolean
get() = ReadConnection::class.java.isAssignableFrom(this)
/** Returns whether or not the receiving [Class] represents a [WriteConnection]. */
val Class<*>.isWriteConnection: Boolean
get() = WriteConnection::class.java.isAssignableFrom(this)
| java/com/google/android/libraries/pcc/chronicle/api/ConnectionUtils.kt | 3049548105 |
package edu.kit.iti.formal.automation.datatypes.values
/*-
* #%L
* iec61131lang
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program isType distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.automation.datatypes.RecordType
import java.util.*
/**
* Created by weigl on 10.06.14.
*/
data class RecordValue(
var fieldValues: MutableMap<String, Value<*, *>> = HashMap()) {
constructor(recordType: RecordType) : this() {
for (field in recordType.fields) {
//TODO factory for getting values of initializations
//fieldValues[field.name] = field.typeDeclaration.initialization
}
}
}
| lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/values/RecordValue.kt | 689249637 |
package hello.repository
import hello.model.Message
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
interface MessageRepository: JpaRepository<Message, Long> {
@Query("select m from Message m where m.subject like ?1%")
fun findBySubject(subject: String): List<Message>
} | src/main/kotlin/hello/repository/Repository.kt | 942030332 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dev
import com.almasb.fxgl.app.scene.GameView
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.collection.PropertyMap
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.dsl.isReleaseMode
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.EntityWorldListener
import com.almasb.fxgl.logging.Logger
import com.almasb.fxgl.logging.LoggerLevel
import com.almasb.fxgl.logging.LoggerOutput
import com.almasb.fxgl.physics.*
import com.almasb.fxgl.scene.SceneService
import javafx.scene.Group
import javafx.scene.shape.*
/**
* Provides developer options when the application is in DEVELOPER or DEBUG modes.
* In RELEASE mode all public functions are NO-OP and return immediately.
*
* @author Almas Baimagambetov ([email protected])
*/
class DevService : EngineService() {
private lateinit var sceneService: SceneService
private lateinit var devPane: DevPane
private val console by lazy { Console() }
val isConsoleOpen: Boolean
get() = console.isOpen()
val isDevPaneOpen: Boolean
get() = devPane.isOpen
private val consoleOutput = object : LoggerOutput {
override fun append(message: String) {
console.pushMessage(message)
}
override fun close() { }
}
private val isDevEnabled: Boolean
get() = !isReleaseMode() && FXGL.getSettings().isDeveloperMenuEnabled
override fun onInit() {
if (!isDevEnabled)
return
devPane = DevPane(sceneService, FXGL.getSettings())
}
fun openConsole() {
if (!isDevEnabled)
return
console.open()
}
fun closeConsole() {
if (!isDevEnabled)
return
console.close()
}
fun openDevPane() {
if (!isDevEnabled)
return
devPane.open()
}
fun closeDevPane() {
if (!isDevEnabled)
return
devPane.close()
}
fun pushDebugMessage(message: String) {
if (!isDevEnabled)
return
devPane.pushMessage(message)
}
override fun onMainLoopStarting() {
if (!isDevEnabled)
return
Logger.addOutput(consoleOutput, LoggerLevel.DEBUG)
FXGL.getSettings().devShowBBox.addListener { _, _, isSelected ->
if (isSelected) {
FXGL.getGameWorld().entities.forEach {
addDebugView(it)
}
} else {
FXGL.getGameWorld().entities.forEach {
removeDebugView(it)
}
}
}
FXGL.getGameWorld().addWorldListener(object : EntityWorldListener {
override fun onEntityAdded(entity: Entity) {
if (FXGL.getSettings().devShowBBox.value) {
addDebugView(entity)
}
}
override fun onEntityRemoved(entity: Entity) {
if (FXGL.getSettings().devShowBBox.value) {
removeDebugView(entity)
}
}
})
}
private val debugViews = hashMapOf<Entity, GameView>()
private fun addDebugView(entity: Entity) {
val group = Group()
entity.boundingBoxComponent.hitBoxesProperty().forEach {
val shape: Shape = when (val data = it.shape) {
is CircleShapeData -> {
Circle(data.radius, data.radius, data.radius)
}
is BoxShapeData -> {
val bboxView = Rectangle()
bboxView.widthProperty().value = data.width
bboxView.heightProperty().value = data.height
bboxView.visibleProperty().bind(
bboxView.widthProperty().greaterThan(0).and(bboxView.heightProperty().greaterThan(0))
)
bboxView
}
is PolygonShapeData -> {
Polygon(*data.points.flatMap { listOf(it.x, it.y) }.toDoubleArray())
}
is ChainShapeData -> {
Polyline(*data.points.flatMap { listOf(it.x, it.y) }.toDoubleArray())
}
is Box3DShapeData -> {
// not implemented
Rectangle()
}
}
shape.fill = null
shape.translateX = it.minX
shape.translateY = it.minY
shape.strokeWidth = 2.0
shape.strokeProperty().bind(FXGL.getSettings().devBBoxColor)
group.children += shape
}
entity.viewComponent.addChild(group)
val view = GameView(group, Int.MAX_VALUE)
debugViews[entity] = view
}
private fun removeDebugView(entity: Entity) {
debugViews.remove(entity)?.let { view ->
entity.viewComponent.removeChild(view.node)
}
}
override fun onGameReady(vars: PropertyMap) {
if (!isDevEnabled)
return
devPane.onGameReady(vars)
}
} | fxgl/src/main/kotlin/com/almasb/fxgl/dev/DevService.kt | 1730518991 |
/*
* 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.shops.bukkit.database.table
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterId
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.shops.bukkit.RPKShopsBukkit
import com.rpkit.shops.bukkit.database.create
import com.rpkit.shops.bukkit.database.jooq.Tables.RPKIT_SHOP_COUNT
import com.rpkit.shops.bukkit.shopcount.RPKShopCount
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
import java.util.logging.Level.SEVERE
/**
* Represents the shop count table.
*/
class RPKShopCountTable(private val database: Database, private val plugin: RPKShopsBukkit) : Table {
private val characterCache = if (plugin.config.getBoolean("caching.rpkit_shop_count.character_id.enabled")) {
database.cacheManager.createCache(
"rpk-shops-bukkit.rpkit_shop_count.character_id",
Int::class.javaObjectType,
RPKShopCount::class.java,
plugin.config.getLong("caching.rpkit_shop_count.character_id.size")
)
} else {
null
}
fun insert(entity: RPKShopCount): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.insertInto(
RPKIT_SHOP_COUNT,
RPKIT_SHOP_COUNT.CHARACTER_ID,
RPKIT_SHOP_COUNT.COUNT
)
.values(
characterId.value,
entity.count
)
.execute()
characterCache?.set(characterId.value, entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to insert shop count", exception)
throw exception
}
}
fun update(entity: RPKShopCount): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.update(RPKIT_SHOP_COUNT)
.set(RPKIT_SHOP_COUNT.COUNT, entity.count)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.execute()
characterCache?.set(characterId.value, entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to update shop count", exception)
throw exception
}
}
/**
* Gets the shop count for a character.
* If there is no shop count for the given character
*
* @param character The character
* @return The shop count for the character, or null if there is no shop count for the given character
*/
operator fun get(character: RPKCharacter): CompletableFuture<RPKShopCount?> {
val characterId = character.id ?: return CompletableFuture.completedFuture(null)
if (characterCache?.containsKey(characterId.value) == true) {
return CompletableFuture.completedFuture(characterCache[characterId.value])
} else {
return CompletableFuture.supplyAsync {
val result = database.create
.select(
RPKIT_SHOP_COUNT.CHARACTER_ID,
RPKIT_SHOP_COUNT.COUNT
)
.from(RPKIT_SHOP_COUNT)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.fetchOne() ?: return@supplyAsync null
val shopCount = RPKShopCount(
character,
result.get(RPKIT_SHOP_COUNT.COUNT)
)
characterCache?.set(characterId.value, shopCount)
return@supplyAsync shopCount
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get shop count", exception)
throw exception
}
}
}
fun delete(entity: RPKShopCount): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
return runAsync {
database.create
.deleteFrom(RPKIT_SHOP_COUNT)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.execute()
characterCache?.remove(characterId.value)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete shop count", exception)
throw exception
}
}
fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_SHOP_COUNT)
.where(RPKIT_SHOP_COUNT.CHARACTER_ID.eq(characterId.value))
.execute()
characterCache?.remove(characterId.value)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete shop count for character id", exception)
throw exception
}
} | bukkit/rpk-shops-bukkit/src/main/kotlin/com/rpkit/shops/bukkit/database/table/RPKShopCountTable.kt | 2938263328 |
/*
* 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.moderation.bukkit.ticket
import com.rpkit.core.location.RPKLocation
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.database.table.RPKTicketTable
import com.rpkit.moderation.bukkit.event.ticket.RPKBukkitTicketCreateEvent
import com.rpkit.moderation.bukkit.event.ticket.RPKBukkitTicketDeleteEvent
import com.rpkit.moderation.bukkit.event.ticket.RPKBukkitTicketUpdateEvent
import com.rpkit.players.bukkit.profile.RPKProfile
import java.time.LocalDateTime
import java.util.concurrent.CompletableFuture
class RPKTicketServiceImpl(override val plugin: RPKModerationBukkit) : RPKTicketService {
override fun getTicket(id: RPKTicketId): CompletableFuture<out RPKTicket?> {
return plugin.database.getTable(RPKTicketTable::class.java)[id]
}
override fun getOpenTickets(): CompletableFuture<List<RPKTicket>> {
return plugin.database.getTable(RPKTicketTable::class.java).getOpenTickets()
}
override fun getClosedTickets(): CompletableFuture<List<RPKTicket>> {
return plugin.database.getTable(RPKTicketTable::class.java).getClosedTickets()
}
override fun addTicket(ticket: RPKTicket): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitTicketCreateEvent(ticket, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
plugin.database.getTable(RPKTicketTable::class.java).insert(event.ticket).join()
}
}
override fun createTicket(
reason: String,
issuer: RPKProfile,
resolver: RPKProfile?,
location: RPKLocation?,
openDate: LocalDateTime,
closeDate: LocalDateTime?,
isClosed: Boolean
): CompletableFuture<RPKTicket> {
val ticket = RPKTicketImpl(
null,
reason,
issuer,
resolver,
location,
openDate,
closeDate,
isClosed
)
return addTicket(ticket).thenApply { ticket }
}
override fun updateTicket(ticket: RPKTicket): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitTicketUpdateEvent(ticket, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
plugin.database.getTable(RPKTicketTable::class.java).update(event.ticket).join()
}
}
override fun removeTicket(ticket: RPKTicket): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitTicketDeleteEvent(ticket, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
plugin.database.getTable(RPKTicketTable::class.java).delete(event.ticket).join()
}
}
} | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/ticket/RPKTicketServiceImpl.kt | 1773442383 |
/*-
* ========================LICENSE_START=================================
* ids-api
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.api.router.graph
class GraphData {
private val nodes: MutableSet<Node> = LinkedHashSet()
private val links: MutableSet<Edge> = LinkedHashSet()
fun addNode(node: Node) {
nodes.add(node)
}
fun addEdge(edge: Edge) {
links.add(edge)
}
fun getNodes(): Set<Node> {
return nodes
}
fun getLinks(): Set<Edge> {
return links
}
}
| ids-api/src/main/java/de/fhg/aisec/ids/api/router/graph/GraphData.kt | 2366522585 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.action.movement
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.action.animation.AnimationAction
import uk.co.nickthecoder.tickle.action.animation.Ease
import uk.co.nickthecoder.tickle.action.animation.LinearEase
import uk.co.nickthecoder.tickle.action.animation.lerp
open class MoveBy(
val position: Vector2d,
val amount: Vector2d,
seconds: Double,
ease: Ease = LinearEase())
: AnimationAction(seconds, ease) {
var initialPosition = Vector2d()
var finalPosition = Vector2d()
override fun storeInitialValue() {
initialPosition.set(position)
initialPosition.add(amount, finalPosition)
}
override fun update(t: Double) {
lerp(initialPosition, finalPosition, t, position)
}
}
open class MoveXBy(
val position: Vector2d,
val amount: Double,
seconds: Double,
ease: Ease = LinearEase.instance)
: AnimationAction(seconds, ease) {
var initialPosition = 0.0
var finalPosition = 0.0
override fun storeInitialValue() {
initialPosition = position.x
finalPosition = initialPosition + amount
}
override fun update(t: Double) {
position.x = lerp(initialPosition, finalPosition, t)
}
}
open class MoveYBy(
val position: Vector2d,
val amount: Double,
seconds: Double,
ease: Ease = LinearEase.instance)
: AnimationAction(seconds, ease) {
var initialPosition = 0.0
var finalPosition = 0.0
override fun storeInitialValue() {
initialPosition = position.y
finalPosition = initialPosition + amount
}
override fun update(t: Double) {
position.y = lerp(initialPosition, finalPosition, t)
}
}
| tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/MoveBy.kt | 1500294185 |
package domain.processing.entities.objects
import domain.global.entities.NamedEntity
import domain.global.validators.EntityValidator
import domain.global.validators.StepValidator
import domain.global.validators.Validable
import org.neo4j.ogm.annotation.NodeEntity
import org.neo4j.ogm.annotation.Property
import org.neo4j.ogm.annotation.Relationship
/**
* The Step class is the Step entity saved into the DB.
*
* A step has one parameter at least and may have substeps.
*
* Created by Christian Sperandio on 09/04/2016.
*
*/
@NodeEntity(label = "Step")
class StepEntity(_name: String = "") : NamedEntity(_name), Validable<StepEntity> {
@Property
var state: RunningState? = null
@Relationship(type = "HAS_STEP", direction = Relationship.OUTGOING)
var steps: Set<StepEntity>? = null
@Relationship(type = "HAS_PARAMETER", direction = Relationship.OUTGOING)
var parameters: Set<ParameterEntity>? = null
@Relationship(type = "PRODUCES", direction = Relationship.OUTGOING)
var outputs: Set<OutputEntity>? = null
@Property
var complete: Boolean = false
override fun toString(): String {
return "[Step ID=$id Name=$name}"
}
/**
* Returns an instance of the validator checks the validity of the step before saving into the DB.
*/
override fun buildValidator(): EntityValidator<StepEntity> {
return StepValidator()
}
/**
* Resets the id of the current steps and the id for all its parameters and substeps.
*/
override fun resetId() {
id = null
parameters?.forEach { it.resetId() }
steps?.forEach {
it.resetId()
}
outputs?.forEach { it.resetId() }
}
}
| src/main/kotlin/domain/processing/entities/objects/StepEntity.kt | 3163422609 |
package org.rapidpm.microservice.demo.model
/**
* Created by svenruppert on 07.06.15.
*/
public class DataHolder {
public var txtA: String? = null
public var txtb: String? = null
}
| modules/example002/src/main/java/org/rapidpm/microservice/demo/model/DataHolder.kt | 3148501023 |
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.vfs.VirtualFile
import org.eclipse.jgit.api.MergeCommand.FastForwardMode
import org.eclipse.jgit.api.MergeResult
import org.eclipse.jgit.api.MergeResult.MergeStatus
import org.eclipse.jgit.api.errors.CheckoutConflictException
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException
import org.eclipse.jgit.api.errors.JGitInternalException
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.dircache.DirCacheCheckout
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.merge.MergeMessageFormatter
import org.eclipse.jgit.merge.MergeStrategy
import org.eclipse.jgit.merge.ResolveMerger
import org.eclipse.jgit.merge.SquashMessageFormatter
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.revwalk.RevWalkUtils
import org.eclipse.jgit.transport.RemoteConfig
import org.eclipse.jgit.treewalk.FileTreeIterator
import org.jetbrains.settingsRepository.*
import java.io.IOException
import java.text.MessageFormat
import java.util.ArrayList
open class Pull(val manager: GitRepositoryManager, val indicator: ProgressIndicator, val commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()) {
val repository = manager.repository
// we must use the same StoredConfig instance during the operation
val config = repository.getConfig()
val remoteConfig = RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME)
fun pull(mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE, commitMessage: String? = null, prefetchedRefToMerge: Ref? = null): UpdateResult? {
indicator.checkCanceled()
LOG.debug("Pull")
val repository = manager.repository
val repositoryState = repository.getRepositoryState()
if (repositoryState != RepositoryState.SAFE) {
LOG.warn(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState, repositoryState.name()))
}
val refToMerge = prefetchedRefToMerge ?: fetch() ?: return null
val mergeResult = merge(refToMerge, mergeStrategy, commitMessage = commitMessage)
val mergeStatus = mergeResult.mergeStatus
if (LOG.isDebugEnabled()) {
LOG.debug(mergeStatus.toString())
}
if (mergeStatus == MergeStatus.CONFLICTING) {
val mergedCommits = mergeResult.mergedCommits
assert(mergedCommits.size() == 2)
val conflicts = mergeResult.conflicts!!
var unresolvedFiles = conflictsToVirtualFiles(conflicts)
val mergeProvider = JGitMergeProvider(repository, mergedCommits[0]!!, mergedCommits[1]!!, conflicts)
val resolvedFiles: List<VirtualFile>
val mergedFiles = ArrayList<String>()
while (true) {
resolvedFiles = resolveConflicts(unresolvedFiles, mergeProvider)
for (file in resolvedFiles) {
mergedFiles.add(file.getPath())
}
if (resolvedFiles.size() == unresolvedFiles.size()) {
break
}
else {
unresolvedFiles.removeAll(mergedFiles)
}
}
repository.commit()
return mergeResult.result.toMutable().addChanged(mergedFiles)
}
else if (!mergeStatus.isSuccessful()) {
throw IllegalStateException(mergeResult.toString())
}
else {
return mergeResult.result
}
}
fun fetch(prevRefUpdateResult: RefUpdate.Result? = null): Ref? {
indicator.checkCanceled()
val repository = manager.repository
val fetchResult = repository.fetch(remoteConfig, manager.credentialsProvider, indicator.asProgressMonitor()) ?: return null
if (LOG.isDebugEnabled()) {
printMessages(fetchResult)
for (refUpdate in fetchResult.getTrackingRefUpdates()) {
LOG.debug(refUpdate.toString())
}
}
indicator.checkCanceled()
var hasChanges = false
for (fetchRefSpec in remoteConfig.getFetchRefSpecs()) {
val refUpdate = fetchResult.getTrackingRefUpdate(fetchRefSpec.getDestination())
if (refUpdate == null) {
LOG.debug("No ref update for $fetchRefSpec")
continue
}
val refUpdateResult = refUpdate.getResult()
// we can have more than one fetch ref spec, but currently we don't worry about it
if (refUpdateResult == RefUpdate.Result.LOCK_FAILURE || refUpdateResult == RefUpdate.Result.IO_FAILURE) {
if (prevRefUpdateResult == refUpdateResult) {
throw IOException("Ref update result " + refUpdateResult.name() + ", we have already tried to fetch again, but no luck")
}
LOG.warn("Ref update result " + refUpdateResult.name() + ", trying again after 500 ms")
Thread.sleep(500)
return fetch(refUpdateResult)
}
if (!(refUpdateResult == RefUpdate.Result.FAST_FORWARD || refUpdateResult == RefUpdate.Result.NEW || refUpdateResult == RefUpdate.Result.FORCED)) {
throw UnsupportedOperationException("Unsupported ref update result")
}
if (!hasChanges) {
hasChanges = refUpdateResult != RefUpdate.Result.NO_CHANGE
}
}
if (!hasChanges) {
LOG.debug("No remote changes")
return null
}
return fetchResult.getAdvertisedRef(config.getRemoteBranchFullName()) ?: throw IllegalStateException("Could not get advertised ref")
}
fun merge(unpeeledRef: Ref,
mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE,
commit: Boolean = true,
fastForwardMode: FastForwardMode = FastForwardMode.FF,
squash: Boolean = false,
forceMerge: Boolean = false,
commitMessage: String? = null): MergeResultEx {
indicator.checkCanceled()
val head = repository.getRef(Constants.HEAD) ?: throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
// Check for FAST_FORWARD, ALREADY_UP_TO_DATE
val revWalk = RevWalk(repository)
var dirCacheCheckout: DirCacheCheckout? = null
try {
// handle annotated tags
val ref = repository.peel(unpeeledRef)
var objectId = ref.getPeeledObjectId()
if (objectId == null) {
objectId = ref.getObjectId()
}
val srcCommit = revWalk.lookupCommit(objectId)
val headId = head.getObjectId()
if (headId == null) {
revWalk.parseHeaders(srcCommit)
dirCacheCheckout = DirCacheCheckout(repository, repository.lockDirCache(), srcCommit.getTree())
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
val refUpdate = repository.updateRef(head.getTarget().getName())
refUpdate.setNewObjectId(objectId)
refUpdate.setExpectedOldObjectId(null)
refUpdate.setRefLogMessage("initial pull", false)
if (refUpdate.update() != RefUpdate.Result.NEW) {
throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
}
return MergeResultEx(srcCommit, MergeStatus.FAST_FORWARD, arrayOf<ObjectId?>(null, srcCommit), ImmutableUpdateResult(dirCacheCheckout.getUpdated().keySet(), dirCacheCheckout.getRemoved()))
}
val refLogMessage = StringBuilder("merge ")
refLogMessage.append(ref.getName())
val headCommit = revWalk.lookupCommit(headId)
if (!forceMerge && revWalk.isMergedInto(srcCommit, headCommit)) {
return MergeResultEx(headCommit, MergeStatus.ALREADY_UP_TO_DATE, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
//return MergeResult(headCommit, srcCommit, array(headCommit, srcCommit), MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null)
}
else if (!forceMerge && fastForwardMode != FastForwardMode.NO_FF && revWalk.isMergedInto(headCommit, srcCommit)) {
// FAST_FORWARD detected: skip doing a real merge but only update HEAD
refLogMessage.append(": ").append(MergeStatus.FAST_FORWARD)
dirCacheCheckout = DirCacheCheckout(repository, headCommit.getTree(), repository.lockDirCache(), srcCommit.getTree())
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
val newHead: ObjectId
val mergeStatus: MergeStatus
if (squash) {
newHead = headId
mergeStatus = MergeStatus.FAST_FORWARD_SQUASHED
val squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit)
repository.writeSquashCommitMsg(SquashMessageFormatter().format(squashedCommits, head))
}
else {
updateHead(refLogMessage, srcCommit, headId, repository)
newHead = srcCommit
mergeStatus = MergeStatus.FAST_FORWARD
}
return MergeResultEx(newHead, mergeStatus, arrayOf<ObjectId?>(headCommit, srcCommit), ImmutableUpdateResult(dirCacheCheckout.getUpdated().keySet(), dirCacheCheckout.getRemoved()))
}
else {
if (fastForwardMode == FastForwardMode.FF_ONLY) {
return MergeResultEx(headCommit, MergeStatus.ABORTED, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
}
val mergeMessage: String
if (squash) {
mergeMessage = ""
repository.writeSquashCommitMsg(SquashMessageFormatter().format(RevWalkUtils.find(revWalk, srcCommit, headCommit), head))
}
else {
mergeMessage = commitMessageFormatter.mergeMessage(listOf(ref), head)
repository.writeMergeCommitMsg(mergeMessage)
repository.writeMergeHeads(arrayListOf(ref.getObjectId()))
}
val merger = mergeStrategy.newMerger(repository)
val noProblems: Boolean
var lowLevelResults: Map<String, org.eclipse.jgit.merge.MergeResult<*>>? = null
var failingPaths: Map<String, ResolveMerger.MergeFailureReason>? = null
var unmergedPaths: List<String>? = null
if (merger is ResolveMerger) {
merger.setCommitNames(arrayOf("BASE", "HEAD", ref.getName()))
merger.setWorkingTreeIterator(FileTreeIterator(repository))
noProblems = merger.merge(headCommit, srcCommit)
lowLevelResults = merger.getMergeResults()
failingPaths = merger.getFailingPaths()
unmergedPaths = merger.getUnmergedPaths()
}
else {
noProblems = merger.merge(headCommit, srcCommit)
}
refLogMessage.append(": Merge made by ")
refLogMessage.append(if (revWalk.isMergedInto(headCommit, srcCommit)) "recursive" else mergeStrategy.getName())
refLogMessage.append('.')
var result = if (merger is ResolveMerger) ImmutableUpdateResult(merger.getToBeCheckedOut().keySet(), merger.getToBeDeleted()) else null
if (noProblems) {
// ResolveMerger does checkout
if (merger !is ResolveMerger) {
dirCacheCheckout = DirCacheCheckout(repository, headCommit.getTree(), repository.lockDirCache(), merger.getResultTreeId())
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
result = ImmutableUpdateResult(dirCacheCheckout.getUpdated().keySet(), dirCacheCheckout.getRemoved())
}
var newHeadId: ObjectId? = null
var mergeStatus: MergeResult.MergeStatus? = null
if (!commit && squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED_NOT_COMMITTED
}
if (!commit && !squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_NOT_COMMITTED
}
if (commit && !squash) {
newHeadId = repository.commit(commitMessage, refLogMessage.toString()).getId()
mergeStatus = MergeResult.MergeStatus.MERGED
}
if (commit && squash) {
newHeadId = headCommit.getId()
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED
}
return MergeResultEx(newHeadId, mergeStatus!!, arrayOf(headCommit.getId(), srcCommit.getId()), result!!)
}
else if (failingPaths == null) {
repository.writeMergeCommitMsg(MergeMessageFormatter().formatWithConflicts(mergeMessage, unmergedPaths))
return MergeResultEx(null, MergeResult.MergeStatus.CONFLICTING, arrayOf(headCommit.getId(), srcCommit.getId()), result!!, lowLevelResults)
}
else {
repository.writeMergeCommitMsg(null)
repository.writeMergeHeads(null)
return MergeResultEx(null, MergeResult.MergeStatus.FAILED, arrayOf(headCommit.getId(), srcCommit.getId()), result!!, lowLevelResults)
}
}
}
catch (e: org.eclipse.jgit.errors.CheckoutConflictException) {
throw CheckoutConflictException(if (dirCacheCheckout == null) listOf<String>() else dirCacheCheckout.getConflicts(), e)
}
finally {
revWalk.close()
}
}
}
class MergeResultEx(val newHead: ObjectId?, val mergeStatus: MergeStatus, val mergedCommits: Array<ObjectId?>, val result: ImmutableUpdateResult, val conflicts: Map<String, org.eclipse.jgit.merge.MergeResult<*>>? = null)
private fun updateHead(refLogMessage: StringBuilder, newHeadId: ObjectId, oldHeadID: ObjectId, repository: Repository) {
val refUpdate = repository.updateRef(Constants.HEAD)
refUpdate.setNewObjectId(newHeadId)
refUpdate.setRefLogMessage(refLogMessage.toString(), false)
refUpdate.setExpectedOldObjectId(oldHeadID)
val rc = refUpdate.update()
when (rc) {
RefUpdate.Result.NEW, RefUpdate.Result.FAST_FORWARD -> return
RefUpdate.Result.REJECTED, RefUpdate.Result.LOCK_FAILURE -> throw ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc)
else -> throw JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, newHeadId.toString(), rc))
}
}
| plugins/settings-repository/src/git/pull.kt | 288969812 |
/*
* Copyright (C) 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 com.example.android.hilt.ui
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import com.example.android.hilt.LogApplication
import com.example.android.hilt.R
import com.example.android.hilt.data.LoggerLocalDataSource
import com.example.android.hilt.navigator.AppNavigator
import com.example.android.hilt.navigator.Screens
/**
* Fragment that displays buttons whose interactions are recorded.
*/
class ButtonsFragment : Fragment() {
private lateinit var logger: LoggerLocalDataSource
private lateinit var navigator: AppNavigator
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_buttons, container, false)
}
override fun onAttach(context: Context) {
super.onAttach(context)
populateFields(context)
}
private fun populateFields(context: Context) {
logger = (context.applicationContext as LogApplication).
serviceLocator.loggerLocalDataSource
navigator = (context.applicationContext as LogApplication).
serviceLocator.provideNavigator(requireActivity())
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<Button>(R.id.button1).setOnClickListener {
logger.addLog("Interaction with 'Button 1'")
}
view.findViewById<Button>(R.id.button2).setOnClickListener {
logger.addLog("Interaction with 'Button 2'")
}
view.findViewById<Button>(R.id.button3).setOnClickListener {
logger.addLog("Interaction with 'Button 3'")
}
view.findViewById<Button>(R.id.all_logs).setOnClickListener {
navigator.navigateTo(Screens.LOGS)
}
view.findViewById<Button>(R.id.delete_logs).setOnClickListener {
logger.removeLogs()
}
}
}
| app/src/main/java/com/example/android/hilt/ui/ButtonsFragment.kt | 921849759 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.grpc.kapt.generator
import com.google.api.grpc.kapt.GrpcClient
import com.google.api.grpc.kapt.GrpcServer
import com.google.api.grpc.kapt.generator.proto.ProtoInterfaceGenerator
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeAliasSpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import io.grpc.BindableService
import io.grpc.MethodDescriptor
import io.grpc.Server
import io.grpc.ServerBuilder
import io.grpc.ServerCallHandler
import io.grpc.ServerServiceDefinition
import io.grpc.ServiceDescriptor
import io.grpc.stub.ServerCalls
import io.grpc.stub.StreamObserver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Element
/**
* Generates a gRPC [io.grpc.BindableService] from an interface annotated with [GrpcServer].
*/
internal class ServerGenerator(
environment: ProcessingEnvironment,
private val clientElements: Collection<Element>
) : Generator<List<FileSpec>>(environment) {
private val protoGenerator by lazy {
ProtoInterfaceGenerator(environment)
}
override fun generate(element: Element): List<FileSpec> {
val files = mutableListOf<FileSpec>()
val annotation = element.getAnnotation(GrpcServer::class.java)
?: throw CodeGenerationException("Unsupported element: $element")
val interfaceType = element.asGeneratedInterfaceType()
// get metadata required for generation
val kmetadata = element.asKotlinMetadata()
val typeInfo = annotation.extractTypeInfo(element, annotation.suffix)
// determine marshaller to use
val marshallerType = annotation.asMarshallerType()
// determine the full service name (use the implemented interfaces, if available)
val clientInterfaceTypeInfo = getClientAnnotation(element)
val fullServiceName = clientInterfaceTypeInfo?.fullName ?: typeInfo.fullName
val provider = clientInterfaceTypeInfo?.source ?: typeInfo.source
// create the server
val server = FileSpec.builder(typeInfo.type.packageName, typeInfo.type.simpleName)
.addFunction(
FunSpec.builder("asGrpcService")
.addParameter(
ParameterSpec.builder("coroutineScope", CoroutineScope::class)
.defaultValue("%T", GlobalScope::class)
.build()
)
.receiver(interfaceType)
.returns(BindableService::class)
.addStatement("return %T(this, coroutineScope)", typeInfo.type)
.addKdoc(
"""
|Create a new service that can be bound to a gRPC server.
|
|Server methods are launched in the [coroutineScope], which is the [%T] by default.
""".trimMargin(),
GlobalScope::class.asTypeName()
)
.build()
)
.addFunction(
FunSpec.builder("asGrpcServer")
.addParameter("port", Int::class)
.addParameter(
ParameterSpec.builder("coroutineScope", CoroutineScope::class)
.defaultValue("%T", GlobalScope::class)
.build()
)
.receiver(interfaceType)
.returns(Server::class)
.addStatement(
"""
|return %T.forPort(port)
| .addService(this.asGrpcService(coroutineScope))
| .build()
""".trimMargin(),
ServerBuilder::class
)
.addKdoc(
"""
|Create a new gRPC server on the given [port] running the [%T] service.
|
|Server methods are launched in the [coroutineScope], which is the [%T] by default.
""".trimMargin(),
interfaceType,
GlobalScope::class.asTypeName()
)
.build()
)
.addFunction(
FunSpec.builder("asGrpcServer")
.addModifiers(KModifier.SUSPEND)
.addParameter("port", Int::class)
.addParameter(
"block",
LambdaTypeName.get(
receiver = CoroutineScope::class.asClassName(),
returnType = Unit::class.asTypeName()
).copy(suspending = true)
)
.receiver(interfaceType)
.addCode(
"""
|coroutineScope {
| launch {
| val server = [email protected](port, this)
| server.start()
| block()
| server.shutdown().awaitTermination()
| }
|}
|""".trimMargin()
)
.addKdoc(
"""
|Create a new gRPC server and execute the given block before shutting down.
|
|This method is intended for testing and examples.
|""".trimMargin()
)
.build()
)
.addTypeAlias(methodListTypeAlias)
.addTypeAlias(methodBindingTypeAlias)
.addFunction(methodBindingFun)
.addType(
TypeSpec.classBuilder(typeInfo.type)
.addModifiers(KModifier.PRIVATE)
.addSuperinterface(BindableService::class)
.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter("implementation", interfaceType)
.addParameter("coroutineScope", CoroutineScope::class)
.build()
)
.addProperty(
PropertySpec.builder("implementation", interfaceType)
.addModifiers(KModifier.PRIVATE)
.initializer("implementation")
.build()
)
.addProperty(
PropertySpec.builder("name", String::class)
.addModifiers(KModifier.PRIVATE)
.initializer("%S", fullServiceName)
.build()
)
.addProperty(
element.filterRpcMethods().map {
kmetadata.describeElement(it)
}.asMethodDescriptor(marshallerType, provider)
)
.addProperty(generateServiceDescriptor(provider))
.addProperty(generateServiceDefinition())
.addFunction(
FunSpec.builder("bindService")
.addModifiers(KModifier.OVERRIDE)
.returns(ServerServiceDefinition::class.asTypeName())
.addStatement("return serviceDefinition")
.build()
)
.build()
)
.addImport("kotlinx.coroutines", "launch", "runBlocking")
.addImport("kotlinx.coroutines", "coroutineScope")
val schemaDescriptorType = provider?.getSchemaDescriptorType()
if (schemaDescriptorType != null) {
server.addType(schemaDescriptorType)
}
files += server.build()
return files
}
private fun List<KotlinMethodInfo>.asMethodDescriptor(
marshallerType: TypeName,
provider: SchemaDescriptorProvider?
): PropertySpec {
val methodsInitializers = this.map { it.asMethodDescriptor(marshallerType, provider) }
return PropertySpec.builder("methods", methodListTypeAlias.type)
.addModifiers(KModifier.PRIVATE)
.initializer(with(CodeBlock.builder()) {
add("listOf(\n")
indent()
for ((idx, code) in methodsInitializers.withIndex()) {
if (idx == methodsInitializers.size - 1) {
addStatement("%L", code)
} else {
addStatement("%L,", code)
}
}
unindent()
add(")")
build()
})
.build()
}
private fun KotlinMethodInfo.asMethodDescriptor(
marshallerType: TypeName,
provider: SchemaDescriptorProvider?
): CodeBlock {
val serverCall = with(CodeBlock.builder()) {
indent()
if (rpc.type == MethodDescriptor.MethodType.SERVER_STREAMING) {
add(
"""
|%T.asyncServerStreamingCall { request: %T, responseObserver: %T ->
| coroutineScope.launch {
| try {
| for (data in implementation.%L(request)) {
| responseObserver.onNext(data)
| }
| responseObserver.onCompleted()
| } catch(t: Throwable) {
| responseObserver.onError(t)
| }
| }
|}
""".trimMargin(),
ServerCalls::class.asClassName(), rpc.inputType,
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
name
)
} else if (rpc.type == MethodDescriptor.MethodType.CLIENT_STREAMING) {
add(
"""
|%T.asyncClientStreamingCall { responseObserver: %T ->
| val requestChannel: %T = Channel()
| val requestObserver = object : %T {
| override fun onNext(value: %T) {
| runBlocking { requestChannel.send(value) }
| }
|
| override fun onError(t: Throwable) {
| requestChannel.close(t)
| }
|
| override fun onCompleted() {
| requestChannel.close()
| }
| }
|
| coroutineScope.launch {
| try {
| responseObserver.onNext(implementation.%L(requestChannel))
| } finally {
| responseObserver.onCompleted()
| }
| }
|
| requestObserver
|}
""".trimMargin(),
ServerCalls::class.asClassName(),
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
Channel::class.asClassName().parameterizedBy(rpc.inputType),
StreamObserver::class.asClassName().parameterizedBy(rpc.inputType),
rpc.inputType,
name
)
} else if (rpc.type == MethodDescriptor.MethodType.BIDI_STREAMING) {
add(
"""
|%T.asyncBidiStreamingCall { responseObserver: %T ->
| val requestChannel: %T = Channel()
| val requestObserver = object : %T {
| override fun onNext(value: %T) {
| runBlocking { requestChannel.send(value) }
| }
|
| override fun onError(t: Throwable) {
| requestChannel.close(t)
| }
|
| override fun onCompleted() {
| requestChannel.close()
| }
| }
|
| coroutineScope.launch {
| try {
| for (data in implementation.%L(requestChannel)) {
| responseObserver.onNext(data)
| }
| responseObserver.onCompleted()
| } catch(t: Throwable) {
| responseObserver.onError(t)
| }
| }
|
| requestObserver
|}
""".trimMargin(),
ServerCalls::class.asClassName(),
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
Channel::class.asClassName().parameterizedBy(rpc.inputType),
StreamObserver::class.asClassName().parameterizedBy(rpc.inputType),
rpc.inputType,
name
)
} else { // MethodDescriptor.MethodType.UNARY
add(
"""
|%T.asyncUnaryCall { request: %T, responseObserver: %T ->
| coroutineScope.launch {
| try {
| responseObserver.onNext(implementation.%L(request))
| responseObserver.onCompleted()
| } catch(t: Throwable) {
| responseObserver.onError(t)
| }
| }
|}
""".trimMargin(),
ServerCalls::class.asClassName(), rpc.inputType,
StreamObserver::class.asClassName().parameterizedBy(rpc.outputType),
name
)
}
unindent()
}.build()
return CodeBlock.of(
"""
|methodBinding(
| with(
| %T.newBuilder(
| %T.of(%T::class.java),
| %T.of(%T::class.java)
| )
| ) {
| setFullMethodName(
| MethodDescriptor.generateFullMethodName(name, %S)
| )
| setType(MethodDescriptor.MethodType.%L)
| setSchemaDescriptor(%L)
| build()
| },
| %L
|)
""".trimMargin(),
MethodDescriptor::class.asTypeName(),
marshallerType, rpc.inputType,
marshallerType, rpc.outputType,
rpc.name,
rpc.type.name,
provider?.getSchemaDescriptorFor(rpc.name) ?: "null",
serverCall
)
}
private fun generateServiceDescriptor(provider: SchemaDescriptorProvider?) =
PropertySpec.builder("serviceDescriptor", ServiceDescriptor::class.asTypeName())
.addModifiers(KModifier.PRIVATE)
.initializer(
"""
|with(
| %T.newBuilder(name)
|) {
| for ((method, _) in methods) {
| addMethod(method)
| }
| setSchemaDescriptor(%L)
| build()
|}
|""".trimMargin(),
ServiceDescriptor::class.asTypeName(),
provider?.getSchemaDescriptorFor() ?: "null"
)
.build()
private fun generateServiceDefinition() =
PropertySpec.builder("serviceDefinition", ServerServiceDefinition::class.asTypeName())
.addModifiers(KModifier.PRIVATE)
.initializer(
"""
|with(
| %T.builder(serviceDescriptor)
|) {
| for ((method, handler) in methods) {
| @Suppress("UNCHECKED_CAST")
| addMethod(method as %T, handler as %T)
| }
| build()
|}
|""".trimMargin(),
ServerServiceDefinition::class.asTypeName(),
MethodDescriptor::class.asClassName().parameterizedBy(Any::class.asTypeName(), Any::class.asTypeName()),
ServerCallHandler::class.asClassName().parameterizedBy(Any::class.asTypeName(), Any::class.asTypeName())
)
.build()
// get the matching @GrpcClient annotation for this element (if it exists)
private fun getClientAnnotation(element: Element): AnnotatedTypeInfo? {
for (superType in environment.typeUtils.directSupertypes(element.asType())) {
val clientInterface = clientElements.firstOrNull {
environment.typeUtils.isSameType(it.asType(), superType)
}
val clientAnnotation = clientInterface?.getAnnotation(GrpcClient::class.java)
if (clientAnnotation != null) {
return clientAnnotation.extractTypeInfo(clientInterface, "")
}
}
return null
}
private fun GrpcClient.extractTypeInfo(
element: Element,
suffix: String
): AnnotatedTypeInfo = extractTypeInfo(element, suffix, listOf(protoGenerator))
}
// various type aliases and help functions to simplify the generated code
private val methodBindingTypeAlias = TypeAliasSpec.builder(
"MethodBinding<ReqT, RespT>",
Pair::class.asClassName().parameterizedBy(
MethodDescriptor::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
),
ServerCallHandler::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
)
)
)
.addModifiers(KModifier.PRIVATE)
.build()
private val methodListTypeAlias = TypeAliasSpec.builder(
"MethodList",
List::class.asClassName().parameterizedBy(TypeVariableName("MethodBinding<*, *>"))
)
.addModifiers(KModifier.PRIVATE)
.build()
private val methodBindingFun = FunSpec.builder("methodBinding")
.addTypeVariable(TypeVariableName("ReqT"))
.addTypeVariable(TypeVariableName("RespT"))
.addParameter(
"descriptor", MethodDescriptor::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
)
)
.addParameter(
"handler", ServerCallHandler::class.asClassName().parameterizedBy(
TypeVariableName("ReqT"), TypeVariableName("RespT")
)
)
.returns(methodBindingTypeAlias.type)
.addStatement("return %T(descriptor, handler)", Pair::class.asClassName())
.addModifiers(KModifier.PRIVATE)
.build()
| processor/src/main/kotlin/com/google/api/grpc/kapt/generator/ServerGenerator.kt | 3692835364 |
package net.perfectdreams.spicymorenitta.utils
import org.w3c.dom.Image
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
suspend fun Image.awaitLoad(url: String) {
return kotlin.coroutines.suspendCoroutine { cont ->
this.onload = {
cont.resume(Unit)
}
this.onerror = { b: dynamic, s: String, i: Int, i1: Int, any: Any? ->
cont.resumeWithException(Exception())
}
this.src = url
}
} | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/utils/ImageExtensions.kt | 1550602076 |
package us.jimschubert.kopper.typed
import us.jimschubert.kopper.StringOption
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Delegates argument parsing of a string option
*/
class StringArgument(
caller: TypedArgumentParser,
val shortOption: String,
default: String? = null,
longOption: List<String> = listOf(),
description: String? = null,
parameterText: String? = null
): ReadOnlyProperty<TypedArgumentParser, String> {
init {
caller.parser.custom(StringOption(shortOption, longOption, description, default, parameterText))
}
/**
* Returns the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @return the property value.
*/
override fun getValue(thisRef: TypedArgumentParser, property: KProperty<*>): String {
return thisRef.ensureParsed().option(shortOption) ?: ""
}
} | kopper-typed/src/main/kotlin/us/jimschubert/kopper/typed/StringArgument.kt | 1703813005 |
package com.darakeon.dfm.lib.api
import android.content.Context
import android.os.Build
import com.darakeon.dfm.lib.BuildConfig
import com.darakeon.dfm.lib.R
object MainInfo {
fun getSiteUrl(context: Context) : String {
val siteAddress =
context.getString(R.string.site_address)
return when {
siteAddress == "" -> ""
BuildConfig.DEBUG -> "http://$siteAddress/"
else -> "https://$siteAddress/"
}
}
private fun isIP(address: String) =
Regex("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")
.matches(address)
fun getAppVersion(context: Context): String {
return context.packageManager.getPackageInfo(
context.packageName,
0
).versionName
}
}
| android/Lib/src/main/kotlin/com/darakeon/dfm/lib/api/MainInfo.kt | 3666537593 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.maps.placesdemo
import android.app.Activity
import androidx.annotation.StringRes
import kotlinx.coroutines.ExperimentalCoroutinesApi
enum class Demo(
@StringRes val title: Int,
@StringRes val description: Int,
val activity: Class<out Activity>
) {
@ExperimentalCoroutinesApi
DETAILS_FRAGMENT_DEMO(
R.string.details_demo_title,
R.string.details_demo_description,
DetailsActivity::class.java
),
@ExperimentalCoroutinesApi
AUTOCOMPLETE_FRAGMENT_DEMO(
R.string.autocomplete_fragment_demo_title,
R.string.autocomplete_fragment_demo_description,
AutocompleteActivity::class.java
),
@ExperimentalCoroutinesApi
CURRENT_FRAGMENT_DEMO(
R.string.current_demo_title,
R.string.current_demo_description,
CurrentPlaceActivity::class.java
),
} | solution/app/src/main/java/com/google/codelabs/maps/placesdemo/Demo.kt | 1264062135 |
package library.service.api.books
import library.service.api.books.payload.*
import library.service.business.books.BookCollection
import library.service.business.books.domain.composites.Book
import library.service.business.books.domain.types.*
import library.service.logging.LogMethodEntryAndExit
import org.springframework.hateoas.CollectionModel
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn
import org.springframework.http.HttpStatus
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.validation.Valid
@Validated
@RestController
@CrossOrigin
@RequestMapping("/api/books")
@LogMethodEntryAndExit
class BooksController(
private val collection: BookCollection,
private val assembler: BookResourceAssembler
) {
@GetMapping
@ResponseStatus(HttpStatus.OK)
fun getBooks(): CollectionModel<BookResource> {
val allBookRecords = collection.getAllBooks()
val selfLink = linkTo(methodOn(javaClass).getBooks()).withSelfRel()
return assembler.toCollectionModel(allBookRecords)
.apply { add(selfLink) }
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun postBook(@Valid @RequestBody body: CreateBookRequest): BookResource {
val book = Book(
isbn = Isbn13.parse(body.isbn!!),
title = Title(body.title!!),
authors = emptyList(),
numberOfPages = null
)
val bookRecord = collection.addBook(book)
return assembler.toModel(bookRecord)
}
@PutMapping("/{id}/title")
@ResponseStatus(HttpStatus.OK)
fun putBookTitle(@PathVariable id: UUID, @Valid @RequestBody body: UpdateTitleRequest): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeTitle(Title(body.title!!))
}
return assembler.toModel(bookRecord)
}
@PutMapping("/{id}/authors")
@ResponseStatus(HttpStatus.OK)
fun putBookAuthors(@PathVariable id: UUID, @Valid @RequestBody body: UpdateAuthorsRequest): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeAuthors(body.authors!!.map { Author(it) })
}
return assembler.toModel(bookRecord)
}
@DeleteMapping("/{id}/authors")
@ResponseStatus(HttpStatus.OK)
fun deleteBookAuthors(@PathVariable id: UUID): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeAuthors(emptyList())
}
return assembler.toModel(bookRecord)
}
@PutMapping("/{id}/numberOfPages")
@ResponseStatus(HttpStatus.OK)
fun putBookNumberOfPages(@PathVariable id: UUID, @Valid @RequestBody body: UpdateNumberOfPagesRequest): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeNumberOfPages(body.numberOfPages)
}
return assembler.toModel(bookRecord)
}
@DeleteMapping("/{id}/numberOfPages")
@ResponseStatus(HttpStatus.OK)
fun deleteBookNumberOfPages(@PathVariable id: UUID): BookResource {
val bookRecord = collection.updateBook(BookId(id)) {
it.changeNumberOfPages(null)
}
return assembler.toModel(bookRecord)
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun getBook(@PathVariable id: UUID): BookResource {
val bookRecord = collection.getBook(BookId(id))
return assembler.toModel(bookRecord)
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun deleteBook(@PathVariable id: UUID) {
collection.removeBook(BookId(id))
}
@PostMapping("/{id}/borrow")
@ResponseStatus(HttpStatus.OK)
fun postBorrowBook(@PathVariable id: UUID, @Valid @RequestBody body: BorrowBookRequest): BookResource {
val bookRecord = collection.borrowBook(BookId(id), Borrower(body.borrower!!))
return assembler.toModel(bookRecord)
}
@PostMapping("/{id}/return")
@ResponseStatus(HttpStatus.OK)
fun postReturnBook(@PathVariable id: UUID): BookResource {
val bookRecord = collection.returnBook(BookId(id))
return assembler.toModel(bookRecord)
}
} | library-service/src/main/kotlin/library/service/api/books/BooksController.kt | 2752510317 |
/*
* Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>
*
* 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 com.vladsch.smart
import java.util.*
class SmartTableColumnBalancer(charWidthProvider: CharWidthProvider?) {
companion object {
private val IMMUTABLE_ZERO = SmartImmutableData(0)
private val IMMUTABLE_DEFAULT_ALIGNMENT = SmartImmutableData(TextAlignment.DEFAULT)
private val IMMUTABLE_CENTER_ALIGNMENT = SmartImmutableData(TextAlignment.CENTER)
}
protected val myCharWidthProvider = charWidthProvider ?: CharWidthProvider.UNITY_PROVIDER
// inputs
protected val myColumnLengths = HashMap<Int, ArrayList<SmartVersionedDataHolder<Int>>>()
protected val myColumnSpans = ArrayList<TableColumnSpan>()
protected var myMinColumnWidth = 3
// values during balancing computation
protected var myColumnWidths = Array(0, { 0 })
protected var myAdditionalColumnWidths = Array(0, { 0 })
// these are outputs
protected val myAlignmentDataPoints = ArrayList<SmartVersionedDataAlias<TextAlignment>>()
protected val myColumnWidthDataPoints = ArrayList<SmartVersionedDataAlias<Int>>()
protected val myVersionData: SmartVersionedDataAlias<Int> = SmartVersionedDataAlias(IMMUTABLE_ZERO)
protected var myDependencies: List<SmartVersionedDataHolder<Int>> = listOf()
val columnCount: Int get() = myColumnWidthDataPoints.size
val columnWidthDataPoints: List<SmartVersionedDataAlias<Int>> get() = myColumnWidthDataPoints
val columnAlignmentDataPoints: List<SmartVersionedDataAlias<TextAlignment>> get() = myAlignmentDataPoints
var minColumnWidth: Int
get() = myMinColumnWidth
set(value) {
myMinColumnWidth = value.minLimit(0);
}
fun columnWidthDataPoint(index: Int): SmartVersionedDataAlias<Int> {
return myColumnWidthDataPoints[index]
}
fun columnAlignmentDataPoint(index: Int): SmartVersionedDataAlias<TextAlignment> {
return myAlignmentDataPoints[index]
}
fun width(index: Int, textLength: SmartVersionedDataHolder<Int>): SmartVersionedDataHolder<Int> {
return width(index, textLength, 1, 0)
}
fun width(index: Int, textWidth: SmartVersionedDataHolder<Int>, columnSpan: Int, widthOffset: Int): SmartVersionedDataHolder<Int> {
if (columnSpan < 1) throw IllegalArgumentException("columnSpan must be >= 1")
ensureColumnDataPoints(index + columnSpan - 1)
if (columnSpan == 1) {
// regular column
addColumnLength(index, textWidth)
return myColumnWidthDataPoints[index]
} else {
// this one is a span
val colSpan = TableColumnSpan(this, index, columnSpan, textWidth, widthOffset)
myColumnSpans.add(colSpan)
return colSpan.widthDataPoint
}
}
protected fun addColumnLength(index: Int, textWidth: SmartVersionedDataHolder<Int>) {
val list = myColumnLengths[index]
if (list == null) {
myColumnLengths.put(index, arrayListOf(textWidth))
} else {
list.add(textWidth)
}
}
protected fun ensureColumnDataPoints(index: Int) {
while (myAlignmentDataPoints.size < index + 1) {
myAlignmentDataPoints.add(SmartVersionedDataAlias(IMMUTABLE_DEFAULT_ALIGNMENT))
}
while (myColumnWidthDataPoints.size < index + 1) {
myColumnWidthDataPoints.add(SmartVersionedDataAlias(IMMUTABLE_ZERO))
}
}
fun alignmentDataPoint(index: Int): SmartVersionedDataHolder<TextAlignment> {
ensureColumnDataPoints(index)
return myAlignmentDataPoints[index]
}
class SmartVersionedDefaultTextAlignment(val delegate: SmartVersionedDataAlias<TextAlignment>, val isHeader: Boolean) : SmartVersionedDataHolder<TextAlignment> {
override fun get(): TextAlignment {
return if (delegate.get() == TextAlignment.DEFAULT && isHeader) TextAlignment.CENTER else TextAlignment.LEFT
}
override val versionSerial: Int
get() = delegate.versionSerial
override val isStale: Boolean
get() = delegate.isStale
override val isMutable: Boolean
get() = delegate.isMutable
override val dependencies: Iterable<SmartVersion>
get() = delegate.dependencies
override fun nextVersion() {
delegate.nextVersion()
}
override var dataSnapshot: DataSnapshot<TextAlignment>
get() {
return if (isHeader && delegate.dataSnapshot.value == TextAlignment.DEFAULT) DataSnapshot(delegate.dataSnapshot.serial, TextAlignment.CENTER) else delegate.dataSnapshot
}
set(value) {
delegate.dataSnapshot = value
}
}
fun alignmentDataPoint(index: Int, isHeader: Boolean): SmartVersionedDataHolder<TextAlignment> {
ensureColumnDataPoints(index)
return SmartVersionedDefaultTextAlignment(myAlignmentDataPoints[index], isHeader);
}
fun alignment(index: Int, alignment: SmartVersionedDataHolder<TextAlignment>): SmartVersionedDataHolder<TextAlignment> {
ensureColumnDataPoints(index)
if (myAlignmentDataPoints[index].alias === IMMUTABLE_DEFAULT_ALIGNMENT) {
//throw IllegalStateException("Alignment provider for index $index is already defined ${myAlignmentDataPoints[index]}, new one is in error $alignment")
myAlignmentDataPoints[index].alias = alignment
}
return myAlignmentDataPoints[index].alias
}
// here is the meat of the wiring
fun finalizeTable() {
// column width data points depend on all the lengths of columns and all the spans that span those columns
val dependencies = arrayListOf<SmartVersionedDataHolder<Int>>()
for (index in 0..myColumnWidthDataPoints.lastIndex) {
val lengths = myColumnLengths[index]
if (lengths != null) {
for (length in lengths) {
if (length !== IMMUTABLE_ZERO) dependencies.add(length)
}
}
}
// now add any spanning columns
for (columnSpan in myColumnSpans) {
dependencies.add(columnSpan.textLengthDataPoint)
}
myDependencies = dependencies
myColumnWidths = Array(myColumnWidthDataPoints.size, { 0 })
myAdditionalColumnWidths = Array(myColumnWidthDataPoints.size, { 0 })
for (index in 0..myColumnWidthDataPoints.lastIndex) {
myColumnWidthDataPoints[index].alias = SmartDependentData(myVersionData, { columnWidth(index) })
}
for (columnSpan in myColumnSpans) {
columnSpan.widthDataPoint.alias = SmartDependentData(myVersionData, { spanWidth(columnSpan.startIndex, columnSpan.endIndex) - columnSpan.widthOffset })
}
// we now set our version alias to dependent data that will do the column balancing computations
myVersionData.alias = SmartDependentData(dependencies, { balanceColumns(); 0 })
}
private fun additionalColumnWidth(index: Int): Int {
return myAdditionalColumnWidths[index]
}
// called when something has changed in the dependencies, so here we recompute everything
fun balanceColumns() {
// get all the single column text lengths
for (index in 0..myColumnWidthDataPoints.lastIndex) {
var width = myMinColumnWidth
val lengths = myColumnLengths[index]
if (lengths != null) {
for (length in lengths) {
if (width < length.get()) width = length.get()
}
}
myColumnWidths[index] = width
}
// get all the span lengths
for (columnSpan in myColumnSpans) {
columnSpan.textLength = columnSpan.textLengthDataPoint.get()
}
// compute unfixed columns, which are all columns at first
var haveUnfixedColumns = myColumnSpans.size > 0
while (haveUnfixedColumns) {
haveUnfixedColumns = false
for (columnSpan in myColumnSpans) {
columnSpan.distributeLength()
}
var fixedAdditionalWidth = 0
var unfixedColumns = setOf<Int>()
for (columnSpan in myColumnSpans) {
unfixedColumns = unfixedColumns.union(columnSpan.unfixedColumns)
}
// need to reset all unfixed additional columns so we recompute them
for (index in unfixedColumns) {
myAdditionalColumnWidths[index] = 0
}
for (columnSpan in myColumnSpans) {
if (!columnSpan.unfixedColumns.isEmpty()) {
for (index in columnSpan.unfixedColumns) {
val additionalWidth = columnSpan.additionalWidths[index - columnSpan.startIndex]
if (myAdditionalColumnWidths[index] < additionalWidth) {
myAdditionalColumnWidths[index] = additionalWidth
if (fixedAdditionalWidth < additionalWidth) {
fixedAdditionalWidth = additionalWidth
}
}
}
}
}
for (columnSpan in myColumnSpans) {
if (!columnSpan.unfixedColumns.isEmpty()) {
columnSpan.fixLengths(fixedAdditionalWidth)
if (!columnSpan.unfixedColumns.isEmpty()) haveUnfixedColumns = true
}
}
}
// we now have everything computed, can clear the
for (columnSpan in myColumnSpans) {
columnSpan.clearIterationData()
}
}
internal fun spanWidth(startIndex: Int, endIndex: Int): Int {
if (myCharWidthProvider === CharWidthProvider.UNITY_PROVIDER) {
var width = 0
for (index in startIndex..endIndex - 1) {
width += columnWidth(index)
}
return width
}
var preWidth = 0
var spanWidth = 0
for (i in 0..endIndex - 1) {
val rawWidth = myColumnWidths[i] + myAdditionalColumnWidths[i]
if (i < startIndex) preWidth += rawWidth
if (i < endIndex) spanWidth += rawWidth
}
val spaceWidth = myCharWidthProvider.spaceWidth
return ((spanWidth + spaceWidth / 2) / spaceWidth) * spaceWidth - preWidth
}
internal fun columnWidth(index: Int): Int {
// here due to uneven char widths we need to compute the delta of the width by converting previous column widths to spaceWidths, rounding and then back to full width
if (index == 0 || myCharWidthProvider === CharWidthProvider.UNITY_PROVIDER) {
return myColumnWidths[index] + myAdditionalColumnWidths[index]
}
var preWidth = 0
for (i in 0..index - 1) {
preWidth += myColumnWidths[i] + myAdditionalColumnWidths[i]
}
val spaceWidth = myCharWidthProvider.spaceWidth
return (((myColumnWidths[index] + myAdditionalColumnWidths[index] + preWidth) + spaceWidth / 2) / spaceWidth) * spaceWidth - preWidth
}
internal fun columnLength(index: Int): Int = myColumnWidths[index]
class TableColumnSpan(tableColumnBalancer: SmartTableColumnBalancer, index: Int, columnSpan: Int, textLength: SmartVersionedDataHolder<Int>, widthOffset: Int) {
protected val myTableColumnBalancer = tableColumnBalancer
protected val myStartIndex = index
protected val myEndIndex = index + columnSpan
protected val myTextLengthDataPoint = textLength
protected val myWidthOffset: Int = widthOffset
protected val myWidthDataPoint = SmartVersionedDataAlias(IMMUTABLE_ZERO)
protected val myColumns: Set<Int>
// used during balancing
protected var myFixedColumns = setOf<Int>()
protected var myUnfixedColumns = setOf<Int>()
protected val myAddColumnWidth: Array<Int>
protected var myTextLength: Int = 0
init {
val columns = HashSet<Int>()
for (span in startIndex..lastIndex) {
columns.add(span)
}
myColumns = columns
myAddColumnWidth = Array(columnSpan, { 0 })
}
val startIndex: Int get() = myStartIndex
val endIndex: Int get() = myEndIndex
val lastIndex: Int get() = myEndIndex - 1
val widthOffset: Int get() = myWidthOffset
val textLengthDataPoint: SmartVersionedDataHolder<Int> get() = myTextLengthDataPoint
val widthDataPoint: SmartVersionedDataAlias<Int> get() = myWidthDataPoint
val additionalWidths: Array<Int> get() = myAddColumnWidth
var textLength: Int
get() = myTextLength
set(value) {
myTextLength = value
}
val fixedColumns: Set<Int> get() = myFixedColumns
val unfixedColumns: Set<Int> get() = myUnfixedColumns
// distribute length difference to unfixed columns
fun distributeLength() {
val unfixed = HashSet<Int>()
var fixedWidth = 0
for (index in startIndex..lastIndex) {
if (fixedColumns.contains(index)) {
// this one is fixed
fixedWidth += myTableColumnBalancer.columnWidth(index)
} else {
fixedWidth += myTableColumnBalancer.columnLength(index)
unfixed.add(index)
}
}
myUnfixedColumns = unfixed
if (!unfixed.isEmpty()) {
val extraLength = (myTextLength + myWidthOffset - fixedWidth).minLimit(0)
val whole = extraLength / unfixed.size
var remainder = extraLength - whole * unfixed.size
for (index in unfixed.sortedByDescending { myTableColumnBalancer.columnLength(it) }) {
additionalWidths[index - myStartIndex] = whole + if (remainder > 0) 1 else 0
if (remainder > 0) remainder--
}
}
}
fun fixLengths(fixedLength: Int) {
val fixedColumns = HashSet<Int>()
val unfixedColumns = HashSet<Int>()
fixedColumns.addAll(myFixedColumns)
for (index in myUnfixedColumns) {
val additionalColumnWidth = myTableColumnBalancer.additionalColumnWidth(index)
if (additionalColumnWidth == fixedLength) {
// this one is fixed
myAddColumnWidth[index - myStartIndex] = fixedLength
fixedColumns.add(index)
} else {
if (fixedLength < additionalColumnWidth) {
fixedColumns.add(index)
} else {
unfixedColumns.add(index)
}
}
}
myFixedColumns = fixedColumns
myUnfixedColumns = unfixedColumns
}
fun clearIterationData() {
myFixedColumns = setOf()
myUnfixedColumns = setOf()
}
}
}
| src/com/vladsch/smart/SmartTableColumnBalancer.kt | 1739250294 |
package com.github.christophpickl.kpotpourri.http4k.module_tests
import com.github.christophpickl.kpotpourri.http4k.DefiniteRequestBody
import com.github.christophpickl.kpotpourri.http4k.HttpMethod4k
import com.github.christophpickl.kpotpourri.http4k.post
import com.github.christophpickl.kpotpourri.jackson4k.asString
import com.github.christophpickl.kpotpourri.jackson4k.buildJackson4kMapper
import org.testng.annotations.Test
@Test class RequestPayloadTest : ComponentTest() {
companion object {
private val mapper = buildJackson4kMapper()
}
private val anyRequestBody = "anyRequestBody"
fun `When String request body, then string sent and plain text header set`() {
wheneverExecuteHttpMockReturnResponse()
http4kWithMock().post<Unit>(testUrl) {
requestBody(anyRequestBody)
}
verifyHttpMockExecutedWithRequest(
method = HttpMethod4k.POST,
headers = mapOf("Content-Type" to "text/plain"),
requestBody = DefiniteRequestBody.DefiniteStringBody(anyRequestBody)
)
}
fun `When Int request body, then Int sent and plain text header set`() {
wheneverExecuteHttpMockReturnResponse()
http4kWithMock().post<Unit>(testUrl) {
requestBody(42)
}
verifyHttpMockExecutedWithRequest(
method = HttpMethod4k.POST,
headers = mapOf("Content-Type" to "text/plain"),
requestBody = DefiniteRequestBody.DefiniteStringBody("42")
)
}
fun `When Double request body, then Double sent and plain text header set`() {
wheneverExecuteHttpMockReturnResponse()
http4kWithMock().post<Unit>(testUrl) {
requestBody(42.21)
}
verifyHttpMockExecutedWithRequest(
method = HttpMethod4k.POST,
headers = mapOf("Content-Type" to "text/plain"),
requestBody = DefiniteRequestBody.DefiniteStringBody("42.21")
)
}
fun `When Dto request body, then JSON sent and application json header set`() {
wheneverExecuteHttpMockReturnResponse()
http4kWithMock().post<Unit>(testUrl) {
requestBody(Dto.testee)
}
verifyHttpMockExecutedWithRequest(
method = HttpMethod4k.POST,
headers = mapOf("Content-Type" to "application/json"),
requestBody = DefiniteRequestBody.DefiniteStringBody(Dto.testee.toJson())
)
}
fun `When ByteArray request body, then ByteArray sent`() {
val bytes = byteArrayOf(0, 1, 1, 0)
wheneverExecuteHttpMockReturnResponse()
http4kWithMock().post<Unit>(testUrl) {
requestBody(bytes)
}
verifyHttpMockExecutedWithRequest(
method = HttpMethod4k.POST,
headers = mapOf("Content-Type" to "*/*"),
requestBody = DefiniteRequestBody.DefiniteBytesBody(bytes)
)
}
private data class Dto(val name: String, val age: Int) {
companion object {
val testee = Dto("a", 1)
}
fun toJson() = mapper.asString(this)
}
}
| http4k/src/test/kotlin/com/github/christophpickl/kpotpourri/http4k/module_tests/request_payload_test.kt | 3667626377 |
package io.kotest.matchers.date
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import java.time.OffsetDateTime
fun beInTodayODT() = object : Matcher<OffsetDateTime> {
override fun test(value: OffsetDateTime): MatcherResult {
val passed = value.toLocalDate() == OffsetDateTime.now().toLocalDate()
return MatcherResult(
passed,
"$value should be today",
"$value should not be today"
)
}
}
/**
* Asserts that the OffsetDateTime has a date component of today
*
* ```
* OffsetDateTime.now().shouldBeToday() // Assertion passes
* ```
*/
fun OffsetDateTime.shouldBeToday() = this should beInTodayODT()
/**
* Asserts that the OffsetDateTime does not have a date component of today
*
* ```
* OffsetDateTime.of(2009, Month.APRIL, 2,2,2).shouldNotBeToday() // Assertion passes
* ```
*/
fun OffsetDateTime.shouldNotBeToday() = this shouldNot beInTodayODT()
| kotest-assertions/src/jvmMain/kotlin/io/kotest/matchers/date/offsetdatetime.kt | 1720161731 |
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity
import android.app.Activity
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import com.google.android.material.navigation.NavigationView
import fr.cph.chicago.Constants.SELECTED_ID
import fr.cph.chicago.R
import fr.cph.chicago.core.App
import fr.cph.chicago.core.fragment.Fragment
import fr.cph.chicago.core.fragment.buildFragment
import fr.cph.chicago.databinding.ActivityMainBinding
import fr.cph.chicago.redux.store
import fr.cph.chicago.util.RateUtil
import org.apache.commons.lang3.StringUtils
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
companion object {
private val rateUtil: RateUtil = RateUtil
}
private var currentPosition: Int = 0
private lateinit var drawerToggle: ActionBarDrawerToggle
private lateinit var favoriteMenuItem: MenuItem
private lateinit var inputMethodManager: InputMethodManager
lateinit var toolBar: Toolbar
private var title: String? = null
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!this.isFinishing) {
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
this.toolBar = binding.included.toolbar
if (store.state.ctaTrainKey == StringUtils.EMPTY) {
// Start error activity when state is empty (usually when android restart the activity on error)
App.startErrorActivity()
finish()
}
currentPosition = when {
savedInstanceState != null -> savedInstanceState.getInt(SELECTED_ID, R.id.navigation_favorites)
intent.extras != null -> intent.extras!!.getInt(SELECTED_ID, R.id.navigation_favorites)
else -> R.id.navigation_favorites
}
title = when {
savedInstanceState != null -> savedInstanceState.getString(getString(R.string.bundle_title), getString(R.string.favorites))
intent.extras != null -> intent.extras!!.getString(getString(R.string.bundle_title), getString(R.string.favorites))
else -> getString(R.string.favorites)
}
binding.drawer.setNavigationItemSelectedListener(this)
favoriteMenuItem = binding.drawer.menu.getItem(0)
if (currentPosition == R.id.navigation_favorites) {
favoriteMenuItem.isChecked = true
}
this.toolBar.inflateMenu(R.menu.main)
this.toolBar.elevation = 4f
inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
drawerToggle = object : ActionBarDrawerToggle(this, binding.drawerLayout, this.toolBar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
updateFragment(currentPosition)
}
}
binding.drawerLayout.addDrawerListener(drawerToggle)
drawerToggle.syncState()
setBarTitle(title!!)
updateFragment(currentPosition)
}
}
override fun onResume() {
super.onResume()
if (title != null)
setBarTitle(title!!)
}
override fun onBackPressed() {
if (currentPosition == R.id.navigation_favorites) {
finish()
} else {
// Switch to favorites if in another fragment
onNavigationItemSelected(favoriteMenuItem)
loadFragment(currentPosition)
}
}
private fun setBarTitle(title: String) {
this.title = title
this.toolBar.title = title
}
private fun updateFragment(position: Int) {
when (position) {
R.id.navigation_favorites -> loadFragment(R.id.navigation_favorites)
R.id.navigation_train -> loadFragment(R.id.navigation_train)
R.id.navigation_bus -> loadFragment(R.id.navigation_bus)
R.id.navigation_bike -> loadFragment(R.id.navigation_bike)
R.id.navigation_nearby -> loadFragment(R.id.navigation_nearby)
R.id.navigation_cta_map -> loadFragment(R.id.navigation_cta_map)
R.id.navigation_alert_cta -> loadFragment(R.id.navigation_alert_cta)
R.id.navigation_settings -> loadFragment(R.id.navigation_settings)
}
}
private fun loadFragment(navigationId: Int) {
val transaction = supportFragmentManager.beginTransaction()
var fragment = supportFragmentManager.findFragmentByTag(navigationId.toString())
if (fragment == null) {
fragment = buildFragment(navigationId)
transaction.add(fragment, navigationId.toString())
}
transaction.replace(R.id.searchContainer, fragment).commit()
showHideActionBarMenu((fragment as Fragment).hasActionBar())
binding.searchContainer.animate().alpha(1.0f)
}
private fun itemSelected(title: String) {
binding.searchContainer.animate().alpha(0.0f)
setBarTitle(title)
closeDrawerAndUpdateActionBar()
}
private fun closeDrawerAndUpdateActionBar() {
binding.drawerLayout.closeDrawer(GravityCompat.START)
// Force keyboard to hide if present
inputMethodManager.hideSoftInputFromWindow(binding.drawerLayout.windowToken, 0)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
drawerToggle.onConfigurationChanged(newConfig)
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
if (!isFinishing) {
menuItem.isChecked = true
if (currentPosition != menuItem.itemId) {
currentPosition = menuItem.itemId
when (menuItem.itemId) {
R.id.navigation_favorites -> itemSelected(getString(R.string.favorites))
R.id.navigation_train -> itemSelected(getString(R.string.train))
R.id.navigation_bus -> itemSelected(getString(R.string.bus))
R.id.navigation_bike -> itemSelected(getString(R.string.divvy))
R.id.navigation_nearby -> itemSelected(getString(R.string.nearby))
R.id.navigation_cta_map -> itemSelected(getString(R.string.cta_map))
R.id.navigation_alert_cta -> itemSelected(getString(R.string.cta_alert))
R.id.navigation_rate_this_app -> rateUtil.rateThisApp(this)
R.id.navigation_settings -> itemSelected(getString(R.string.settings))
}
} else {
currentPosition = menuItem.itemId
binding.drawerLayout.closeDrawer(GravityCompat.START)
}
}
return true
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
savedInstanceState.putInt(SELECTED_ID, currentPosition)
if (title != null) savedInstanceState.putString(getString(R.string.bundle_title), title)
super.onSaveInstanceState(savedInstanceState)
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
title = savedInstanceState.getString(getString(R.string.bundle_title))
currentPosition = savedInstanceState.getInt(SELECTED_ID)
}
private fun showHideActionBarMenu(show: Boolean) {
this.toolBar.menu.getItem(0).isVisible = show
}
}
| android-app/src/main/kotlin/fr/cph/chicago/core/activity/MainActivity.kt | 2819446509 |
package br.com.edsilfer.android.presence_control.commons.layout
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import br.com.edsilfer.android.presence_control.R
import kotlinx.android.synthetic.main.util_collection_loading.view.*
class EmptyCollection : LinearLayout {
/**
* CONSTRUCTORS
*/
constructor(context: Context) : super(context) {
init(null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init(attrs)
}
/**
* LIFECYCLE
*/
private fun init(attrs: AttributeSet?) {
val rootView = View.inflate(context, R.layout.util_collection_loading, this)
val image = rootView.findViewById<ImageView>(R.id.empty_collection_image)
val label = rootView.findViewById<TextView>(R.id.empty_collection_text)
val disclaimer = getMessage(attrs!!)
if (!disclaimer.isNullOrEmpty()) {
label.text = disclaimer
} else {
label.text = String.format(context.getString(R.string.str_commons_utils_empty_collection), getCollectionName(attrs))
}
image.setImageResource(getIcon(attrs))
}
private fun getIcon(attrs: AttributeSet): Int {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.EmptyCollection,
0, 0)
try {
return a.getResourceId(R.styleable.EmptyCollection_icon, -1)
} finally {
a.recycle()
}
}
private fun getCollectionName(attrs: AttributeSet): String {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.EmptyCollection,
0, 0)
try {
return a.getString(R.styleable.EmptyCollection_name)
} finally {
a.recycle()
}
}
private fun getMessage(attrs: AttributeSet): String {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.EmptyCollection,
0, 0)
try {
return a.getString(R.styleable.EmptyCollection_message)
} catch (e: Exception) {
return ""
} finally {
a.recycle()
}
}
/**
* PUBLIC INTERFACE
*/
fun showFeedback(recyclerView: RecyclerView, collection: Collection<*>?) {
if (collection == null || collection.isEmpty()) {
recyclerView.visibility = RecyclerView.GONE
loading.visibility = LinearLayout.GONE
empty_collection.visibility = LinearLayout.VISIBLE
} else if (!collection.isEmpty()) {
recyclerView.visibility = RecyclerView.VISIBLE
loading.visibility = LinearLayout.GONE
empty_collection.visibility = LinearLayout.GONE
} else {
hideAll()
recyclerView.visibility = RecyclerView.VISIBLE
}
}
fun showLoading() {
loading.visibility = LinearLayout.VISIBLE
empty_collection.visibility = LinearLayout.GONE
}
fun hideAll() {
wrapper.visibility = RelativeLayout.GONE
}
}
| app/src/main/java/br/com/edsilfer/android/presence_control/commons/layout/EmptyCollection.kt | 2115141069 |
package com.github.emulio.ui.screens.util
import com.badlogic.gdx.graphics.Color
import java.math.BigInteger
object ColorCache {
val colorCache = HashMap<String, Color>()
fun getColor(rgba: String?): Color = when {
rgba == null -> defaultColor()
rgba.length == 6 -> cachedColor(rgba.toUpperCase() + "FF")
rgba.length == 8 -> cachedColor(rgba.toUpperCase())
else -> defaultColor()
}
private fun cachedColor(rgba: String): Color {
check(rgba.length == 8)
return colorCache[rgba] ?: storeColor(rgba)
}
private fun storeColor(rgba: String): Color {
val color = createColor(rgba)
colorCache[rgba] = color
return color
}
private fun createColor(rgba: String) = Color(BigInteger(rgba, 16).toInt())
private fun defaultColor() = Color.BLACK
} | core/src/main/com/github/emulio/ui/screens/util/ColorCache.kt | 1630956104 |
@file:Suppress("KDocMissingDocumentation")
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_18_R1
import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy
import net.minecraft.world.entity.EntityInsentient
import org.bukkit.Material
import org.bukkit.craftbukkit.v1_18_R1.CraftServer
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftLivingEntity
import org.bukkit.entity.*
import org.bukkit.inventory.ItemStack
import org.bukkit.loot.LootTable
import java.util.*
/**
* CraftBukkit Wrapper of the pet.
*/
class CraftPet(server: CraftServer, nmsPet: EntityInsentient) : CraftLivingEntity(server, nmsPet), EntityPetProxy, Pig,
Rabbit, Bat {
/**
* Removes this entity.
*/
override fun deleteFromWorld() {
super.remove()
}
override fun isAware(): Boolean {
return false
}
override fun isBreedItem(p0: ItemStack): Boolean {
return false
}
override fun isBreedItem(p0: Material): Boolean {
return false
}
override fun setAware(p0: Boolean) {
}
/**
* Hides the true type of the pet from everyone else.
*/
override fun getType(): EntityType {
return EntityType.PIG
}
override fun getSteerMaterial(): Material {
return Material.AIR
}
/**
* Ignore all other plugins trying to remove this entity. This is the entity of PetBlocks,
* no one else is allowed to modify this!
*/
override fun remove() {
}
/**
* Pet should never be persistent.
*/
override fun isPersistent(): Boolean {
return false
}
/**
* Pet should never be persistent.
*/
override fun setPersistent(b: Boolean) {}
/**
* Custom type.
*/
override fun toString(): String {
return "PetBlocks{Entity}"
}
override fun getLootTable(): LootTable? {
return null
}
override fun setTarget(p0: LivingEntity?) {
}
override fun getTarget(): LivingEntity? {
return null
}
override fun setLootTable(p0: LootTable?) {
}
override fun setSeed(p0: Long) {
}
override fun getSeed(): Long {
return 0L
}
override fun setAdult() {
}
override fun setLoveModeTicks(p0: Int) {
}
override fun setBaby() {
}
override fun setBoostTicks(p0: Int) {
}
override fun setAge(p0: Int) {
}
override fun getLoveModeTicks(): Int {
return 0
}
override fun getAge(): Int {
return 2
}
override fun getCurrentBoostTicks(): Int {
return 0
}
override fun canBreed(): Boolean {
return false
}
override fun setSaddle(p0: Boolean) {
}
override fun getBoostTicks(): Int {
return 0
}
override fun isAdult(): Boolean {
return false
}
override fun hasSaddle(): Boolean {
return false
}
override fun setCurrentBoostTicks(p0: Int) {
}
override fun getAgeLock(): Boolean {
return false
}
override fun getBreedCause(): UUID? {
return UUID.randomUUID()
}
override fun setBreedCause(p0: UUID?) {
}
override fun setAgeLock(p0: Boolean) {
}
override fun isLoveMode(): Boolean {
return false
}
override fun setBreed(p0: Boolean) {
}
override fun setRabbitType(p0: Rabbit.Type) {
}
override fun isAwake(): Boolean {
return true
}
override fun setAwake(p0: Boolean) {
}
override fun getRabbitType(): Rabbit.Type {
return Rabbit.Type.BLACK
}
}
| petblocks-bukkit-plugin/petblocks-bukkit-nms-118R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_18_R1/CraftPet.kt | 1506347991 |
package block.heat
import com.cout970.magneticraft.Magneticraft
import com.cout970.magneticraft.block.PROPERTY_DIRECTION
import com.cout970.magneticraft.misc.block.get
import com.cout970.magneticraft.misc.world.isServer
import com.cout970.magneticraft.tileentity.heat.TileBrickFurnace
import net.minecraft.block.material.Material
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by cout970 on 04/07/2016.
*/
object BlockBrickFurnace : BlockHeatMultistate(Material.ROCK, "brick_furnace") {
override fun createTileEntity(worldIn: World, meta: IBlockState): TileEntity = TileBrickFurnace()
override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState?, playerIn: EntityPlayer, hand: EnumHand?, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean {
if (!playerIn.isSneaking) {
if (worldIn.isServer) {
playerIn.openGui(Magneticraft, -1, worldIn, pos.x, pos.y, pos.z)
}
return true
}
return super.onBlockActivated(worldIn, pos, state, playerIn, hand, heldItem, side, hitX, hitY, hitZ)
}
override fun onBlockPlacedBy(worldIn: World?, pos: BlockPos, state: IBlockState?, placer: EntityLivingBase, stack: ItemStack?) {
super.onBlockPlacedBy(worldIn, pos, state, placer, stack)
worldIn?.setBlockState(pos, defaultState.withProperty(PROPERTY_DIRECTION, placer.horizontalFacing.opposite))
}
override fun getMetaFromState(state: IBlockState): Int = state[PROPERTY_DIRECTION].ordinal
override fun getStateFromMeta(meta: Int): IBlockState = defaultState.withProperty(PROPERTY_DIRECTION, EnumFacing.getHorizontal(meta))
override fun createBlockState(): BlockStateContainer = BlockStateContainer(this, PROPERTY_DIRECTION)
} | ignore/test/block/heat/BlockBrickFurnace.kt | 3570621545 |
package org.mozilla.focus.utils
import android.app.Application
import androidx.test.core.app.ApplicationProvider
import mozilla.components.support.utils.ext.getPackageInfoCompat
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.util.Locale
@RunWith(RobolectricTestRunner::class)
class SupportUtilsTest {
@Test
fun cleanup() {
// Other tests might get confused by our locale fiddling, so lets go back to the default:
Locale.setDefault(Locale.ENGLISH)
}
/*
* Super simple sumo URL test - it exists primarily to verify that we're setting the language
* and page tags correctly. appVersion is null in tests, so we just test that there's a null there,
* which doesn't seem too useful...
*/
@Test
@Throws(Exception::class)
fun getSumoURLForTopic() {
val context = ApplicationProvider.getApplicationContext() as Application
val versionName = context.packageManager.getPackageInfoCompat(context.packageName, 0).versionName
val testTopic = SupportUtils.SumoTopic.TRACKERS
val testTopicStr = testTopic.topicStr
Locale.setDefault(Locale.GERMANY)
assertEquals(
"https://support.mozilla.org/1/mobile/$versionName/Android/de-DE/$testTopicStr",
SupportUtils.getSumoURLForTopic(ApplicationProvider.getApplicationContext(), testTopic),
)
Locale.setDefault(Locale.CANADA_FRENCH)
assertEquals(
"https://support.mozilla.org/1/mobile/$versionName/Android/fr-CA/$testTopicStr",
SupportUtils.getSumoURLForTopic(ApplicationProvider.getApplicationContext(), testTopic),
)
}
/**
* This is a pretty boring tests - it exists primarily to verify that we're actually setting
* a langtag in the manfiesto URL.
*/
@Test
@Throws(Exception::class)
fun getManifestoURL() {
Locale.setDefault(Locale.UK)
assertEquals(
"https://www.mozilla.org/en-GB/about/manifesto/",
SupportUtils.manifestoURL,
)
Locale.setDefault(Locale.KOREA)
assertEquals(
"https://www.mozilla.org/ko-KR/about/manifesto/",
SupportUtils.manifestoURL,
)
}
}
| app/src/test/java/org/mozilla/focus/utils/SupportUtilsTest.kt | 352614337 |
package com.waz.zclient.storage.db.errors
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "Errors")
data class ErrorsEntity(
@PrimaryKey
@ColumnInfo(name = "_id")
val id: String,
@ColumnInfo(name = "err_type", defaultValue = "")
val errorType: String,
@ColumnInfo(name = "users", defaultValue = "")
val users: String,
@ColumnInfo(name = "messages", defaultValue = "")
val messages: String,
@ColumnInfo(name = "conv_id")
val conversationId: String?,
@ColumnInfo(name = "res_code", defaultValue = "0")
val responseCode: Int,
@ColumnInfo(name = "res_msg", defaultValue = "")
val responseMessage: String,
@ColumnInfo(name = "res_label", defaultValue = "")
val responseLabel: String,
@ColumnInfo(name = "time", defaultValue = "0")
val time: Int
)
| storage/src/main/kotlin/com/waz/zclient/storage/db/errors/ErrorsEntity.kt | 846751618 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment.about
import android.content.Context
import android.widget.Toast
import org.mozilla.focus.R
import org.mozilla.focus.ext.components
import org.mozilla.focus.state.AppAction
/**
* Triggers the "secret" debug menu when logoView is tapped 5 times.
*/
class SecretSettingsUnlocker(private val context: Context) {
private var secretSettingsClicks = 0
private var lastDebugMenuToast: Toast? = null
/**
* Reset the [secretSettingsClicks] counter.
*/
fun resetCounter() {
secretSettingsClicks = 0
}
fun increment() {
// Because the user will mostly likely tap the logo in rapid succession,
// we ensure only 1 toast is shown at any given time.
lastDebugMenuToast?.cancel()
secretSettingsClicks += 1
when (secretSettingsClicks) {
in 2 until SECRET_DEBUG_MENU_CLICKS -> {
val clicksLeft = SECRET_DEBUG_MENU_CLICKS - secretSettingsClicks
val toast = Toast.makeText(
context,
context.getString(R.string.about_debug_menu_toast_progress, clicksLeft),
Toast.LENGTH_SHORT,
)
toast.show()
lastDebugMenuToast = toast
}
SECRET_DEBUG_MENU_CLICKS -> {
Toast.makeText(
context,
R.string.about_debug_menu_toast_done,
Toast.LENGTH_LONG,
).show()
context.components.appStore.dispatch(AppAction.SecretSettingsStateChange(true))
}
}
}
companion object {
// Number of clicks on the app logo to enable the "secret" debug menu.
private const val SECRET_DEBUG_MENU_CLICKS = 5
}
}
| app/src/main/java/org/mozilla/focus/fragment/about/SecretSettingsUnlocker.kt | 3049824972 |
package shark
import shark.LeakTrace.Companion.ZERO_WIDTH_SPACE
import shark.LeakTraceObject.LeakingStatus
import shark.LeakTraceObject.LeakingStatus.LEAKING
import shark.LeakTraceObject.LeakingStatus.NOT_LEAKING
import shark.LeakTraceObject.LeakingStatus.UNKNOWN
import shark.internal.lastSegment
import java.io.Serializable
import java.util.Locale
import kotlin.math.ln
import kotlin.math.pow
data class LeakTraceObject(
val type: ObjectType,
/**
* Class name of the object.
* The class name format is the same as what would be returned by [Class.getName].
*/
val className: String,
/**
* Labels that were computed during analysis. A label provides extra information that helps
* understand the state of the leak trace object.
*/
val labels: Set<String>,
val leakingStatus: LeakingStatus,
val leakingStatusReason: String,
/**
* The minimum number of bytes which would be freed if all references to this object were
* released. Not null only if the retained heap size was computed AND [leakingStatus] is
* equal to [LeakingStatus.UNKNOWN] or [LeakingStatus.LEAKING].
*/
val retainedHeapByteSize: Int?,
/**
* The minimum number of objects which would be unreachable if all references to this object were
* released. Not null only if the retained heap size was computed AND [leakingStatus] is
* equal to [LeakingStatus.UNKNOWN] or [LeakingStatus.LEAKING].
*/
val retainedObjectCount: Int?
) : Serializable {
/**
* Returns {@link #className} without the package, ie stripped of any string content before the
* last period (included).
*/
val classSimpleName: String get() = className.lastSegment('.')
val typeName
get() = type.name.toLowerCase(Locale.US)
override fun toString(): String {
val firstLinePrefix = ""
val additionalLinesPrefix = "$ZERO_WIDTH_SPACE "
return toString(firstLinePrefix, additionalLinesPrefix, true)
}
internal fun toString(
firstLinePrefix: String,
additionalLinesPrefix: String,
showLeakingStatus: Boolean,
typeName: String = this.typeName
): String {
val leakStatus = when (leakingStatus) {
UNKNOWN -> "UNKNOWN"
NOT_LEAKING -> "NO ($leakingStatusReason)"
LEAKING -> "YES ($leakingStatusReason)"
}
var result = ""
result += "$firstLinePrefix$className $typeName"
if (showLeakingStatus) {
result += "\n${additionalLinesPrefix}Leaking: $leakStatus"
}
if (retainedHeapByteSize != null) {
val humanReadableRetainedHeapSize =
humanReadableByteCount(retainedHeapByteSize.toLong())
result += "\n${additionalLinesPrefix}Retaining $humanReadableRetainedHeapSize in $retainedObjectCount objects"
}
for (label in labels) {
result += "\n${additionalLinesPrefix}$label"
}
return result
}
enum class ObjectType {
CLASS,
ARRAY,
INSTANCE
}
enum class LeakingStatus {
/** The object was needed and therefore expected to be reachable. */
NOT_LEAKING,
/** The object was no longer needed and therefore expected to be unreachable. */
LEAKING,
/** No decision can be made about the provided object. */
UNKNOWN;
}
companion object {
private const val serialVersionUID = -3616216391305196341L
// https://stackoverflow.com/a/3758880
private fun humanReadableByteCount(bytes: Long): String {
val unit = 1000
if (bytes < unit) return "$bytes B"
val exp = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
val pre = "kMGTPE"[exp - 1]
return String.format("%.1f %sB", bytes / unit.toDouble().pow(exp.toDouble()), pre)
}
}
} | shark/src/main/java/shark/LeakTraceObject.kt | 3135927429 |
package jp.toastkid.search
import android.net.Uri
import androidx.core.net.toUri
/**
* @author toastkidjp
*/
class SearchQueryExtractor {
private val commonQueryParameterNames = setOf("q", "query", "text", "word")
operator fun invoke(url: String?) = invoke(url?.toUri())
operator fun invoke(uri: Uri?): String? {
val host = uri?.host ?: return null
return when {
host.startsWith("www.google.")
or host.startsWith("play.google.")
or host.startsWith("www.bing.")
or host.endsWith("developer.android.com")
or host.endsWith("scholar.google.com")
or host.endsWith("www.aolsearch.com")
or host.endsWith("www.ask.com")
or host.endsWith("twitter.com")
or host.endsWith("stackoverflow.com")
or host.endsWith("github.com")
or host.endsWith("mvnrepository.com")
or host.endsWith("searchcode.com")
or host.equals("www.qwant.com")
or host.equals("www.reddit.com")
or host.equals("www.economist.com")
or host.equals("www.ft.com")
or host.equals("www.startpage.com")
or host.equals("www.imdb.com")
or host.equals("duckduckgo.com")
or host.equals("news.google.com")
or host.endsWith("medium.com")
or host.endsWith("ted.com")
or host.endsWith(".slideshare.net")
or host.endsWith("cse.google.com")
or host.endsWith(".buzzfeed.com")
or host.endsWith("openweathermap.org")
or host.endsWith(".quora.com")
or host.endsWith(".livejournal.com")
or host.endsWith("search.daum.net")
or host.endsWith(".teoma.com")
or host.endsWith("www.info.com")
or host.endsWith("results.looksmart.com")
or host.equals("www.privacywall.org")
or host.equals("alohafind.com")
or host.equals("www.mojeek.com")
or host.equals("www.ecosia.org")
or host.equals("www.findx.com")
or host.equals("www.bbc.co.uk")
or host.equals("hn.algolia.com")
or host.endsWith("search.gmx.com")
or host.equals("search.sify.com")
or host.equals("www.forbes.com")
or host.equals("search.brave.com")
or host.equals("you.com")
or host.equals("seekingalpha.com")
or host.equals("www.givero.com") ->
uri.getQueryParameter("q")
host.startsWith("www.amazon.") ->
uri.getQueryParameter("field-keywords")
host.endsWith(".linkedin.com") ->
uri.getQueryParameter("keywords")
host.contains("yandex.") ->
uri.getQueryParameter("text")
host.endsWith(".youtube.com") ->
uri.getQueryParameter("search_query")
host.startsWith("www.flickr.") ->
uri.getQueryParameter("text")
host.endsWith(".yelp.com") ->
uri.getQueryParameter("find_desc")
host.equals("www.tumblr.com")
or host.equals("ejje.weblio.jp")
or host.equals("web.archive.org")-> uri.lastPathSegment
host.endsWith("archive.org")
or host.endsWith("search.naver.com")
or host.endsWith("www.morningstar.com")
or host.endsWith("info.finance.yahoo.co.jp")
or host.endsWith(".rambler.ru") ->
uri.getQueryParameter("query")
host.endsWith(".wikipedia.org")
or host.endsWith(".wikimedia.org") ->
if (uri.queryParameterNames.contains("search")) {
uri.getQueryParameter("search")
} else {
// "/wiki/"'s length.
Uri.decode(uri.encodedPath?.substring(6))
}
host.endsWith("search.yahoo.com")
or host.endsWith("search.yahoo.co.jp") ->
uri.getQueryParameter("p")
host.endsWith("www.baidu.com") ->
uri.getQueryParameter("wd")
host.endsWith("myindex.jp") ->
uri.getQueryParameter("w")
host == "www.wolframalpha.com" ->
uri.getQueryParameter("i")
host == "search.goo.ne.jp" ->
uri.getQueryParameter("MT")
host == "bgr.com" ->
uri.getQueryParameter("s")?.replace("#$".toRegex(), "")
host == "www.ebay.com" ->
uri.getQueryParameter("_nkw")
host.endsWith("facebook.com")
or host.equals("www.merriam-webster.com")
or host.equals("www.instagram.com")
or host.equals("www.espn.com") ->
Uri.decode(uri.lastPathSegment)
else -> uri.getQueryParameter(
commonQueryParameterNames
.find { uri.queryParameterNames.contains(it) } ?: ""
)
}
}
} | search/src/main/java/jp/toastkid/search/SearchQueryExtractor.kt | 1011150656 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.ui.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.state.model.MediaUiModel
/**
* A simple text only display of [MediaUiModel] showing artist and title in two separated rows.
*/
@ExperimentalHorologistMediaUiApi
@Composable
public fun DefaultMediaDisplay(
media: MediaUiModel?,
modifier: Modifier = Modifier
) {
TextMediaDisplay(
modifier = modifier,
title = media?.title,
artist = media?.artist
)
}
| media-ui/src/main/java/com/google/android/horologist/media/ui/components/DefaultMediaDisplay.kt | 3491390876 |
package eu.kanade.tachiyomi.ui.manga.info
import android.app.Dialog
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import androidx.core.graphics.ColorUtils
import androidx.core.os.bundleOf
import androidx.core.view.WindowCompat
import coil.imageLoader
import coil.request.Disposable
import coil.request.ImageRequest
import dev.chrisbanes.insetter.applyInsetter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.databinding.MangaFullCoverDialogBinding
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.viewer.ReaderPageImageView
import eu.kanade.tachiyomi.util.view.setNavigationBarTransparentCompat
import eu.kanade.tachiyomi.widget.TachiyomiFullscreenDialog
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class MangaFullCoverDialog : DialogController {
private var manga: Manga? = null
private var binding: MangaFullCoverDialogBinding? = null
private var disposable: Disposable? = null
private val mangaController
get() = targetController as MangaController
constructor(targetController: MangaController, manga: Manga) : super(bundleOf("mangaId" to manga.id)) {
this.targetController = targetController
this.manga = manga
}
@Suppress("unused")
constructor(bundle: Bundle) : super(bundle) {
val db = Injekt.get<DatabaseHelper>()
manga = db.getManga(bundle.getLong("mangaId")).executeAsBlocking()
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
binding = MangaFullCoverDialogBinding.inflate(activity!!.layoutInflater)
binding?.toolbar?.apply {
setNavigationOnClickListener { dialog?.dismiss() }
setOnMenuItemClickListener {
when (it.itemId) {
R.id.action_share_cover -> mangaController.shareCover()
R.id.action_save_cover -> mangaController.saveCover()
R.id.action_edit_cover -> mangaController.changeCover()
}
true
}
menu?.findItem(R.id.action_edit_cover)?.isVisible = manga?.favorite ?: false
}
setImage(manga)
binding?.appbar?.applyInsetter {
type(navigationBars = true, statusBars = true) {
padding(left = true, top = true, right = true)
}
}
binding?.container?.onViewClicked = { dialog?.dismiss() }
binding?.container?.applyInsetter {
type(navigationBars = true) {
padding(bottom = true)
}
}
return TachiyomiFullscreenDialog(activity!!, binding!!.root).apply {
val typedValue = TypedValue()
val theme = context.theme
theme.resolveAttribute(android.R.attr.colorBackground, typedValue, true)
window?.setBackgroundDrawable(ColorDrawable(ColorUtils.setAlphaComponent(typedValue.data, 230)))
}
}
override fun onAttach(view: View) {
super.onAttach(view)
dialog?.window?.let { window ->
window.setNavigationBarTransparentCompat(window.context)
WindowCompat.setDecorFitsSystemWindows(window, false)
}
}
override fun onDetach(view: View) {
super.onDetach(view)
disposable?.dispose()
disposable = null
}
fun setImage(manga: Manga?) {
if (manga == null) return
val request = ImageRequest.Builder(applicationContext!!)
.data(manga)
.target {
binding?.container?.setImage(
it,
ReaderPageImageView.Config(
zoomDuration = 500
)
)
}
.build()
disposable = applicationContext?.imageLoader?.enqueue(request)
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/MangaFullCoverDialog.kt | 268855781 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.data
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import java.time.Instant
/**
* Simple In-memory implementation of Data Request Repository for recording network
* data usage.
*/
@ExperimentalHorologistNetworksApi
public class InMemoryDataRequestRepository : DataRequestRepository {
private val from = Instant.now()
private var ble = 0L
private var wifi = 0L
private var cell = 0L
private var unknown = 0L
private val _currentPeriodUsage: MutableStateFlow<DataUsageReport> =
MutableStateFlow(DataUsageReport(dataByType = mapOf(), from = from, to = from))
override fun currentPeriodUsage(): Flow<DataUsageReport> = _currentPeriodUsage
override fun storeRequest(dataRequest: DataRequest) {
when (dataRequest.networkInfo) {
is NetworkInfo.Cellular -> cell += dataRequest.dataBytes
is NetworkInfo.Bluetooth -> ble += dataRequest.dataBytes
is NetworkInfo.Wifi -> wifi += dataRequest.dataBytes
is NetworkInfo.Unknown -> unknown += dataRequest.dataBytes
}
_currentPeriodUsage.value =
DataUsageReport(
dataByType = mapOf(
NetworkType.Cell to cell,
NetworkType.BT to ble,
NetworkType.Wifi to wifi,
NetworkType.Unknown to unknown
),
from = from,
to = Instant.now()
)
}
}
| network-awareness/src/main/java/com/google/android/horologist/networks/data/InMemoryDataRequestRepository.kt | 1177343272 |
package org.seasar.doma.kotlin.jdbc.criteria.statement
import org.seasar.doma.jdbc.Result
import org.seasar.doma.jdbc.Sql
import org.seasar.doma.jdbc.criteria.statement.Statement
class KEntityqlInsertStatement<ENTITY>(
private val statement: Statement<Result<ENTITY>>
) : KStatement<Result<ENTITY>> {
override fun execute(): Result<ENTITY> {
return statement.execute()
}
override fun asSql(): Sql<*> {
return statement.asSql()
}
}
| doma-kotlin/src/main/kotlin/org/seasar/doma/kotlin/jdbc/criteria/statement/KEntityqlInsertStatement.kt | 1766688414 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistComposeToolsApi::class)
package com.google.android.horologist.composables
import androidx.compose.runtime.Composable
import com.google.android.horologist.compose.tools.ExperimentalHorologistComposeToolsApi
import com.google.android.horologist.compose.tools.WearPreviewDevices
import com.google.android.horologist.compose.tools.WearPreviewFontSizes
import java.time.LocalTime
@WearPreviewDevices
@WearPreviewFontSizes
@Composable
@OptIn(ExperimentalHorologistComposablesApi::class)
fun TimePicker12hPreview() {
// Due to a limitation with ScalingLazyColumn,
// previews only work in interactive mode.
TimePickerWith12HourClock(
time = LocalTime.of(10, 10, 0),
onTimeConfirm = {}
)
}
| composables/src/debug/java/com/google/android/horologist/composables/TimePicker12hPreview.kt | 2772361494 |
package org.koin.androidx.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import org.koin.core.Koin
import org.koin.core.context.GlobalContext
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
/**
* Inject lazily a given dependency for [Composable] functions
* @param qualifier
* @param parameters
*
* @return Lazy instance of type T
*
* @author Henrique Horbovyi
*/
@Composable
inline fun <reified T> inject(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): Lazy<T> = remember {
GlobalContext.get().inject(qualifier, parameters)
}
@Composable
inline fun <reified T> get(
qualifier: Qualifier? = null,
noinline parameters: ParametersDefinition? = null
): T = remember {
GlobalContext.get().get(qualifier, parameters)
}
@Composable
fun getKoin(): Koin = remember {
GlobalContext.get()
}
| koin-projects/koin-androidx-compose/src/main/java/org/koin/androidx/compose/ComposeExt.kt | 3143464711 |
package net.yslibrary.monotweety.logout
import dagger.Component
import net.yslibrary.monotweety.UserComponent
import net.yslibrary.monotweety.base.di.ServiceScope
@ServiceScope
@Component(
dependencies = [UserComponent::class]
)
interface LogoutComponent {
fun inject(service: LogoutService)
}
| app/src/main/java/net/yslibrary/monotweety/logout/LogoutComponent.kt | 3833678742 |
package com.hosshan.android.salad.component.scene.splash
import android.content.Context
import android.content.Intent
import com.hosshan.android.salad.component.scene.Presenter
import com.hosshan.android.salad.component.scene.SceneActivityView
/**
* SplashConstants
*/
fun SplashActivity.Companion.createIntent(context: Context): Intent =
Intent(context, SplashActivity::class.java)
internal interface SplashPresenter : Presenter<SplashView> {
}
internal interface SplashView : SceneActivityView {
fun onPostIntent(isLogin: Boolean)
}
| app/src/main/kotlin/com/hosshan/android/salad/component/scene/splash/SplashConstants.kt | 3787124093 |
package org.jetbrains.dokka.base.translators
import org.intellij.markdown.lexer.Compat.codePointToString
import org.intellij.markdown.lexer.Compat.forEachCodePoint
import org.jetbrains.dokka.model.doc.DocTag
import org.jetbrains.dokka.model.doc.DocTag.Companion.contentTypeParam
import org.jetbrains.dokka.model.doc.Text
import org.jsoup.Jsoup
import org.jsoup.internal.StringUtil
import org.jsoup.nodes.Entities
internal fun String.parseHtmlEncodedWithNormalisedSpaces(
renderWhiteCharactersAsSpaces: Boolean
): List<DocTag> {
val accum = StringBuilder()
val tags = mutableListOf<DocTag>()
var lastWasWhite = false
forEachCodePoint { c ->
if (renderWhiteCharactersAsSpaces && StringUtil.isWhitespace(c)) {
if (!lastWasWhite) {
accum.append(' ')
lastWasWhite = true
}
} else if (codePointToString(c).let { it != Entities.escape(it) }) {
accum.toString().takeIf { it.isNotBlank() }?.let { tags.add(Text(it)) }
accum.delete(0, accum.length)
accum.appendCodePoint(c)
tags.add(Text(accum.toString(), params = contentTypeParam("html")))
accum.delete(0, accum.length)
} else if (!StringUtil.isInvisibleChar(c)) {
accum.appendCodePoint(c)
lastWasWhite = false
}
}
accum.toString().takeIf { it.isNotBlank() }?.let { tags.add(Text(it)) }
return tags
}
/**
* Parses string into [Text] doc tags that can have either value of the string or html-encoded value with content-type=html parameter.
* Content type is added when dealing with html entries like ` `
*/
internal fun String.parseWithNormalisedSpaces(
renderWhiteCharactersAsSpaces: Boolean
): List<DocTag> =
//parsing it using jsoup is required to get codePoints, otherwise they are interpreted separately, as chars
//But we dont need to do it for java as it is already parsed with jsoup
Jsoup.parseBodyFragment(this).body().wholeText().parseHtmlEncodedWithNormalisedSpaces(renderWhiteCharactersAsSpaces) | plugins/base/src/main/kotlin/translators/parseWithNormalisedSpaces.kt | 1831802259 |
package me.mrkirby153.KirBot.utils.crypto
import me.mrkirby153.KirBot.Bot
import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.binary.Hex
import org.json.JSONObject
import org.json.JSONTokener
import java.nio.charset.Charset
import java.util.Arrays
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
object AesCrypto {
private val key by lazy {
Base64.decodeBase64(Bot.properties.getProperty("encryption-key") ?: throw Exception("no key provided"))
}
fun encrypt(plaintext: String, serialize: Boolean = true) : String {
val key = SecretKeySpec(this.key, "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key)
val serializedPlaintext = "s:" + plaintext.toByteArray().size + ":\"" + plaintext + "\";"
val toUse = if(serialize) serializedPlaintext else plaintext
val iv = cipher.iv
val encVal = cipher.doFinal(toUse.toByteArray())
val encrypted = Base64.encodeBase64String(encVal)
val macKey = SecretKeySpec(this.key, "HmacSHA256")
val hmacSha256 = Mac.getInstance("HmacSha256")
hmacSha256.init(macKey)
hmacSha256.update(Base64.encodeBase64(iv))
val calcMac = hmacSha256.doFinal(encrypted.toByteArray())
val mac = String(Hex.encodeHex(calcMac))
val json = JSONObject()
json.put("iv", Base64.encodeBase64String(iv))
json.put("value", encrypted)
json.put("mac", mac)
return Base64.encodeBase64String(json.toString().toByteArray())
}
fun decrypt(ivValue: String, encryptedData: String, macValue: String): String {
val key = SecretKeySpec(this.key, "AES")
val iv = Base64.decodeBase64(ivValue.toByteArray())
val decodedValue = Base64.decodeBase64(encryptedData.toByteArray())
val macKey = SecretKeySpec(this.key, "HmacSHA256")
val hmacSha256 = Mac.getInstance("HmacSHA256")
hmacSha256.init(macKey)
hmacSha256.update(ivValue.toByteArray())
val calcMac = hmacSha256.doFinal(encryptedData.toByteArray())
val mac = Hex.decodeHex(macValue.toCharArray())
if (!Arrays.equals(calcMac, mac))
throw IllegalArgumentException("MAC Mismatch")
val c = Cipher.getInstance("AES/CBC/PKCS5Padding") // or PKCS5Padding
c.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
val decValue = c.doFinal(decodedValue)
var firstQuoteIndex = 0
while (decValue[firstQuoteIndex] != '"'.toByte()) firstQuoteIndex++
return String(Arrays.copyOfRange(decValue, firstQuoteIndex + 1, decValue.size - 2))
}
fun decrypt(encData: String): String {
val rawJson = Base64.decodeBase64(encData).toString(Charset.defaultCharset())
val json = JSONObject(JSONTokener(rawJson))
return decrypt(json.getString("iv"), json.getString("value"), json.getString("mac"))
}
} | src/main/kotlin/me/mrkirby153/KirBot/utils/crypto/AesCrypto.kt | 423839733 |
@file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.blockball.core.logic.persistence.entity
import com.github.shynixn.blockball.api.business.annotation.YamlSerialize
import com.github.shynixn.blockball.api.business.enumeration.RewardType
import com.github.shynixn.blockball.api.persistence.entity.CommandMeta
import com.github.shynixn.blockball.api.persistence.entity.RewardMeta
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class RewardEntity : RewardMeta {
/** Money which gets added via Vault when a player does a rewarded action. */
@YamlSerialize(orderNumber = 1, value = "money-reward")
override var moneyReward: MutableMap<RewardType, Int> = HashMap()
/** Commands which get executed when a player does a rewarded action. */
override var commandReward: MutableMap<RewardType, CommandMeta>
get() = internalCommandReward as MutableMap<RewardType, CommandMeta>
set(value) {
internalCommandReward = value as (MutableMap<RewardType, CommandMetaEntity>)
}
@YamlSerialize(orderNumber = 2, value = "command-reward")
private var internalCommandReward: MutableMap<RewardType, CommandMetaEntity> = HashMap()
} | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/RewardEntity.kt | 2130653561 |
/*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.impl.symbol.kotlin
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.*
import org.jetbrains.kotlin.analysis.api.KtStarProjectionTypeArgument
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.psi.KtObjectDeclaration
class KSClassDeclarationImpl private constructor(internal val ktClassOrObjectSymbol: KtClassOrObjectSymbol) :
KSClassDeclaration,
AbstractKSDeclarationImpl(ktClassOrObjectSymbol),
KSExpectActual by KSExpectActualImpl(ktClassOrObjectSymbol) {
companion object : KSObjectCache<KtClassOrObjectSymbol, KSClassDeclarationImpl>() {
fun getCached(ktClassOrObjectSymbol: KtClassOrObjectSymbol) =
cache.getOrPut(ktClassOrObjectSymbol) { KSClassDeclarationImpl(ktClassOrObjectSymbol) }
}
override val qualifiedName: KSName? by lazy {
ktClassOrObjectSymbol.classIdIfNonLocal?.asFqNameString()?.let { KSNameImpl.getCached(it) }
}
override val classKind: ClassKind by lazy {
when (ktClassOrObjectSymbol.classKind) {
KtClassKind.CLASS -> ClassKind.CLASS
KtClassKind.ENUM_CLASS -> ClassKind.ENUM_CLASS
KtClassKind.ANNOTATION_CLASS -> ClassKind.ANNOTATION_CLASS
KtClassKind.INTERFACE -> ClassKind.INTERFACE
KtClassKind.COMPANION_OBJECT, KtClassKind.ANONYMOUS_OBJECT, KtClassKind.OBJECT -> ClassKind.OBJECT
}
}
override val primaryConstructor: KSFunctionDeclaration? by lazy {
if (ktClassOrObjectSymbol.origin == KtSymbolOrigin.JAVA) {
null
} else {
analyze {
ktClassOrObjectSymbol.getMemberScope().getConstructors().singleOrNull { it.isPrimary }?.let {
KSFunctionDeclarationImpl.getCached(it)
}
}
}
}
override val superTypes: Sequence<KSTypeReference> by lazy {
analyze {
val supers = ktClassOrObjectSymbol.superTypes.mapIndexed { index, type ->
KSTypeReferenceImpl.getCached(type, this@KSClassDeclarationImpl, index)
}
// AA is returning additional kotlin.Any for java classes, explicitly extending kotlin.Any will result in
// compile error, therefore filtering by name should work.
// TODO: reconsider how to model super types for interface.
if (supers.size > 1) {
supers.filterNot { it.resolve().declaration.qualifiedName?.asString() == "kotlin.Any" }
} else {
supers
}.asSequence()
}
}
override val isCompanionObject: Boolean by lazy {
(ktClassOrObjectSymbol.psi as? KtObjectDeclaration)?.isCompanion() ?: false
}
override fun getSealedSubclasses(): Sequence<KSClassDeclaration> {
TODO("Not yet implemented")
}
override fun getAllFunctions(): Sequence<KSFunctionDeclaration> {
return ktClassOrObjectSymbol.getAllFunctions()
}
override fun getAllProperties(): Sequence<KSPropertyDeclaration> {
return ktClassOrObjectSymbol.getAllProperties()
}
override fun asType(typeArguments: List<KSTypeArgument>): KSType {
return analyze {
analysisSession.buildClassType(ktClassOrObjectSymbol) {
typeArguments.forEach { argument(it.toKtTypeArgument()) }
}.let { KSTypeImpl.getCached(it) }
}
}
override fun asStarProjectedType(): KSType {
return analyze {
KSTypeImpl.getCached(
analysisSession.buildClassType(ktClassOrObjectSymbol) {
var current: KSNode? = this@KSClassDeclarationImpl
while (current is KSClassDeclarationImpl) {
current.ktClassOrObjectSymbol.typeParameters.forEach {
argument(
KtStarProjectionTypeArgument(
(current as KSClassDeclarationImpl).ktClassOrObjectSymbol.token
)
)
}
current = if (Modifier.INNER in current.modifiers) {
current.parent
} else {
null
}
}
}
)
}
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitClassDeclaration(this, data)
}
override val declarations: Sequence<KSDeclaration> by lazy {
ktClassOrObjectSymbol.declarations()
}
}
internal fun KtClassOrObjectSymbol.toModifiers(): Set<Modifier> {
val result = mutableSetOf<Modifier>()
if (this is KtNamedClassOrObjectSymbol) {
result.add(modality.toModifier())
result.add(visibility.toModifier())
if (isInline) {
result.add(Modifier.INLINE)
}
if (isData) {
result.add(Modifier.DATA)
}
if (isExternal) {
result.add(Modifier.EXTERNAL)
}
}
if (classKind == KtClassKind.ENUM_CLASS) {
result.add(Modifier.ENUM)
}
return result
}
| kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/KSClassDeclarationImpl.kt | 728876422 |
/*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.media.music
import android.content.ContentResolver
import android.os.Build
import android.provider.MediaStore
import android.support.v4.media.MediaMetadataCompat
import androidx.core.net.toUri
/**
* @author toastkidjp
*/
class MusicFileFinder(private val contentResolver: ContentResolver) {
operator fun invoke(): MutableList<MediaMetadataCompat> {
val uri =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
else
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor = contentResolver.query(
uri,
null,
null,
null,
SORT_ORDER
)
val result = mutableListOf<MediaMetadataCompat>()
while (cursor?.moveToNext() == true) {
val meta = MediaMetadataCompat.Builder()
.putString(
MediaMetadataCompat.METADATA_KEY_MEDIA_ID,
cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)).toString()
)
.putString(
MediaMetadataCompat.METADATA_KEY_TITLE,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
)
.putString(
MediaMetadataCompat.METADATA_KEY_ARTIST,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST))
)
.putString(
MediaMetadataCompat.METADATA_KEY_ALBUM,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM))
)
.putString(
MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI,
"content://media/external/audio/albumart".toUri().buildUpon().appendEncodedPath(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)).toString()).build().toString()
)
.putString(
MediaMetadataCompat.METADATA_KEY_MEDIA_URI,
cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
)
.putLong(
MediaMetadataCompat.METADATA_KEY_DURATION,
cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION))
)
.build()
result.add(meta)
}
cursor?.close()
return result
}
companion object {
private const val SORT_ORDER = "${MediaStore.Audio.AudioColumns.ALBUM} ASC"
}
} | music/src/main/java/jp/toastkid/media/music/MusicFileFinder.kt | 2750208869 |
package net.tlalka.fiszki.model.helpers
import android.content.Context
import android.content.SharedPreferences
class StorageHelper(context: Context) {
private val sharedPreferences: SharedPreferences = this.getSharedPreferences(context)
private fun getSharedPreferences(context: Context): SharedPreferences {
return context.getSharedPreferences(this.javaClass.name, Context.MODE_PRIVATE)
}
fun getBoolean(key: Enum<*>, defValue: Boolean): Boolean {
return this.sharedPreferences.getBoolean(key.name, defValue)
}
fun setBoolean(key: Enum<*>, value: Boolean) {
this.sharedPreferences.edit().putBoolean(key.name, value).apply()
}
fun getValue(key: Enum<*>, defValue: Long): Long {
return this.sharedPreferences.getLong(key.name, defValue)
}
fun setValue(key: Enum<*>, value: Long) {
this.sharedPreferences.edit().putLong(key.name, value).apply()
}
fun getString(key: Enum<*>, defValue: String): String {
return this.sharedPreferences.getString(key.name, defValue) ?: ""
}
fun setString(key: Enum<*>, value: String) {
this.sharedPreferences.edit().putString(key.name, value).apply()
}
inline fun <reified E : Enum<E>> getEnum(key: Enum<*>, defValue: Enum<E>): E {
return enumValueOf(this.getString(key, defValue.name))
}
fun <E : Enum<E>> setEnum(key: Enum<*>, value: E) {
this.sharedPreferences.edit().putString(key.name, value.name).apply()
}
}
| app/src/main/kotlin/net/tlalka/fiszki/model/helpers/StorageHelper.kt | 3759341086 |
// https://www.hackerrank.com/challenges/two-strings/problem
fun main() {
val pairs = readLine().orEmpty().trim().toInt()
(0 until pairs).forEach {
val a = readLine().orEmpty().trim().toCharArray().toSet()
val b = readLine().orEmpty().trim().toCharArray().toSet()
println(if (a.intersect(b).isEmpty()) "NO" else "YES")
}
} | hacker-rank/strings/TwoStrings.kt | 3624400891 |
package net.tlalka.fiszki.core.modules
import android.content.Context
import dagger.Module
import dagger.Provides
import net.tlalka.fiszki.core.annotations.SessionScope
import net.tlalka.fiszki.model.dao.ClusterDao
import net.tlalka.fiszki.model.dao.LessonDao
import net.tlalka.fiszki.model.dao.WordDao
import net.tlalka.fiszki.model.db.DbHelper
import net.tlalka.fiszki.model.db.DbManager
import net.tlalka.fiszki.model.helpers.AssetsHelper
import net.tlalka.fiszki.model.helpers.StorageHelper
@Module
class SessionModule(@get:Provides @get:SessionScope val context: Context) {
@Provides
@SessionScope
fun getDbHelper(): DbHelper {
return DbManager.getHelper(context)
}
@Provides
@SessionScope
fun getLessonDao(dbHelper: DbHelper): LessonDao {
return dbHelper.getLessonDao()
}
@Provides
@SessionScope
fun getClusterDao(dbHelper: DbHelper): ClusterDao {
return dbHelper.getClusterDao()
}
@Provides
@SessionScope
fun getWordDao(dbHelper: DbHelper): WordDao {
return dbHelper.getWordDao()
}
@Provides
@SessionScope
fun getStorageHelper(): StorageHelper {
return StorageHelper(context)
}
@Provides
@SessionScope
fun getAssetsHelper(): AssetsHelper {
return AssetsHelper(context)
}
}
| app/src/main/kotlin/net/tlalka/fiszki/core/modules/SessionModule.kt | 1087750790 |
package com.kanchi.periyava.version.dashboard.model
import android.content.Context
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.kanchi.periyava.BR
import com.kanchi.periyava.R
import com.kanchi.periyava.model.OnItemClickListener
import com.kanchi.periyava.model.Volume
/**
* Created by m84098 on 2/15/18.
*/
class VolumeAdapter : RecyclerView.Adapter<VolumeAdapter.ViewHolder> {
lateinit var context: Context
var features = ArrayList<Volume>()
private var selectedPosition = 0
// Define listener member variable
private var listener: OnItemClickListener? = null
// Define the method that allows the parent activity or fragment to define the listener
fun setOnItemClickListener(listener: OnItemClickListener) {
this.listener = listener
}
constructor(context: Context, value: ArrayList<Volume>) : super() {
this.context = context
this.features = value
}
override fun getItemCount(): Int = features.size;
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent?.context)
val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, R.layout.list_item_volume, parent, false)
return ViewHolder(binding)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
if (features[position] != null) {
if(features[position].id != Volume.Type.NONE)
holder!!.bind(features[position]!!)
}
}
inner class ViewHolder(private var binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
/* override fun onClick(v: View?) {
binding.root.setOnClickListener {
if (listener != null) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(itemView, position)
}
} }
}*/
fun bind(obj: Volume) {
binding.root.setOnClickListener {
if (listener != null) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener!!.onItemClick(itemView, position, obj)
}
}
}
binding.setVariable(BR.volume, obj)
binding.executePendingBindings()
}
}
}
| app/src/main/java/com/kanchi/periyava/adapters/VolumeAdapter.kt | 936637013 |
package io.gitlab.arturbosch.detekt.rules.complexity
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Metric
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.ThresholdRule
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
class ComplexInterface(config: Config = Config.empty,
threshold: Int = DEFAULT_LARGE_INTERFACE_COUNT) : ThresholdRule(config, threshold) {
override val issue = Issue(javaClass.simpleName, Severity.Maintainability,
"An interface contains too many functions and properties. " +
"Large classes tend to handle many things at once. " +
"An interface should have one responsibility. " +
"Split up large interfaces into smaller ones that are easier to understand.")
override fun visitClass(klass: KtClass) {
if (klass.isInterface()) {
val body = klass.getBody() ?: return
val size = body.children.count { it is KtNamedFunction || it is KtProperty }
if (size > threshold) {
report(ThresholdedCodeSmell(issue, Entity.from(klass), Metric("SIZE: ", size, threshold)))
}
}
super.visitClass(klass)
}
}
private const val DEFAULT_LARGE_INTERFACE_COUNT = 10
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/ComplexInterface.kt | 2136139852 |
package org.http4k.security.oauth.server
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.present
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Status.Companion.FORBIDDEN
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.body.form
import org.http4k.core.cookie.cookie
import org.http4k.core.cookie.cookies
import org.http4k.core.findSingle
import org.http4k.core.queries
import org.http4k.core.then
import org.http4k.filter.ClientFilters
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasStatus
import org.http4k.security.InsecureCookieBasedOAuthPersistence
import org.http4k.security.Nonce
import org.http4k.security.ResponseType.CodeIdToken
import org.http4k.security.openid.IdToken
import org.junit.jupiter.api.Test
class OpenIdServerTest {
@Test
fun `can follow authorization code id_token flow`() {
val clientOauthPersistence = InsecureCookieBasedOAuthPersistence("oauthTest")
val authenticationServer = customOauthAuthorizationServer()
val tokenConsumer = InMemoryIdTokenConsumer()
val consumerApp = oauthClientApp(
authenticationServer,
CodeIdToken,
tokenConsumer,
listOf("openid", "name", "age"),
clientOauthPersistence
)
val browser = ClientFilters.Cookies().then(authenticationServer + consumerApp)
val browserWithRedirection = ClientFilters.FollowRedirects().then(browser)
val preAuthResponse = browser(Request(GET, "/a-protected-resource"))
val authRequestUri = preAuthResponse.header("location")!!
val suppliedNonce = Uri.of(authRequestUri).queries().findSingle("nonce")?.let { Nonce(it) }
val storedNonce = clientOauthPersistence
.retrieveNonce(preAuthResponse.cookies()
.fold(Request(GET, "/")) { acc, c -> acc.cookie(c) })
assertThat(storedNonce, present())
assertThat(suppliedNonce, present())
assertThat(suppliedNonce, equalTo(storedNonce))
tokenConsumer.expectedNonce = suppliedNonce
val loginPageResponse = browser(Request(GET, authRequestUri))
assertThat(loginPageResponse, hasStatus(OK) and hasBody("Please authenticate"))
val postAuthResponse = browserWithRedirection(Request(POST, authRequestUri).form("some", "credentials"))
assertThat(postAuthResponse, hasStatus(OK) and hasBody("user resource"))
assertThat(
tokenConsumer.consumedFromAuthorizationResponse,
equalTo(IdToken("dummy-id-token-for-unknown-nonce:${suppliedNonce?.value}"))
)
assertThat(tokenConsumer.consumedFromAccessTokenResponse, equalTo(IdToken("dummy-id-token-for-access-token")))
}
@Test
fun `reject oidc flow if nonces do not match`() {
val clientOauthPersistence = InsecureCookieBasedOAuthPersistence("oauthTest")
val authenticationServer = customOauthAuthorizationServer()
val tokenConsumer = InMemoryIdTokenConsumer(expectedNonce = Nonce("some invalid nonce"))
val consumerApp = oauthClientApp(
authenticationServer,
CodeIdToken,
tokenConsumer,
listOf("openid", "name", "age"),
clientOauthPersistence
)
val browser = ClientFilters.Cookies().then(authenticationServer + consumerApp)
val browserWithRedirection = ClientFilters.FollowRedirects().then(browser)
val preAuthResponse = browser(Request(GET, "/a-protected-resource"))
val authRequestUri = preAuthResponse.header("location")!!
val loginPageResponse = browser(Request(GET, authRequestUri))
assertThat(loginPageResponse, hasStatus(OK) and hasBody("Please authenticate"))
val postAuthResponse = browserWithRedirection(Request(POST, authRequestUri).form("some", "credentials"))
assertThat(postAuthResponse, hasStatus(FORBIDDEN))
}
}
| http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/server/OpenIdServerTest.kt | 2375888982 |
import java.util.*
private fun computeScore(input: String): Long? {
val brackets = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
val scores = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
val stack = ArrayDeque<Char>()
for (c in input) {
when (c) {
in brackets.keys -> stack.addFirst(c)
brackets[stack.first] -> stack.removeFirst()
else -> return null
}
}
var score = 0L
while(stack.isNotEmpty()) {
score *= 5
score += scores[brackets[stack.removeFirst()]]!!
}
return score
}
@ExperimentalStdlibApi
fun main() {
val s = Scanner(System.`in`)
val scores = buildList {
while (s.hasNext()) {
add(computeScore(s.next()))
}
}
println(scores.filterNotNull().sorted()[scores.filterNotNull().size/2])
}
| problems/2021adventofcode10b/submissions/accepted/Stefan.kt | 874185581 |
package nl.ecci.hamers.fcm
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import androidx.core.app.NotificationCompat
import android.util.Log
import com.bumptech.glide.Glide
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import nl.ecci.hamers.R
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.models.*
import nl.ecci.hamers.ui.activities.MainActivity
import nl.ecci.hamers.ui.activities.SingleBeerActivity
import nl.ecci.hamers.ui.activities.SingleEventActivity
import nl.ecci.hamers.ui.activities.SingleMeetingActivity
import nl.ecci.hamers.utils.DataUtils
import nl.ecci.hamers.utils.DataUtils.getGravatarURL
class MessagingService : FirebaseMessagingService() {
var intent: Intent? = null
private var pendingIntent : PendingIntent? = null
var gson: Gson = GsonBuilder().setDateFormat(MainActivity.dbDF.toPattern()).create()
/**
* Called when message is received.
*/
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
intent = Intent(this, MainActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
// Check if message contains a notification payload.
if (remoteMessage?.notification != null) {
// TODO
Log.d(TAG, "FCM Notification Body: " + remoteMessage.notification!!.body!!)
}
// Check if message contains a data payload.
if (remoteMessage?.data?.isNotEmpty() as Boolean) {
Log.d(TAG, "FCM data payload: " + remoteMessage.data)
when (remoteMessage.data["type"]) {
"Quote" -> quotePush(remoteMessage.data["object"])
"Event" -> eventPush(remoteMessage.data["object"])
"Beer" -> beerPush(remoteMessage.data["object"])
"Review" -> reviewPush(remoteMessage.data["object"])
"News" -> newsPush(remoteMessage.data["object"])
"Meeting" -> meetingPush(remoteMessage.data["object"])
"Sticker" -> stickerPush(remoteMessage.data["object"])
}
}
}
private fun quotePush(quoteString: String?) {
val quote = gson.fromJson(quoteString, Quote::class.java)
sendNotification(quote.text, applicationContext.getString(R.string.change_quote_new), quote.userID)
}
private fun eventPush(eventString: String?) {
Loader.getData(this, Loader.EVENTURL, -1, null, null)
val event = gson.fromJson(eventString, Event::class.java)
var title = event.title
if (event.location.isNotBlank()) {
title += "(@" + event.location + ")"
}
intent = Intent(this, SingleEventActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Event.EVENT, event.id)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(title, applicationContext.getString(R.string.change_event_new), event.userID)
}
private fun beerPush(beerString: String?) {
Loader.getData(this, Loader.BEERURL, -1, null, null)
val beer = gson.fromJson(beerString, Beer::class.java)
intent = Intent(this, SingleBeerActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Beer.BEER, beer.id)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(beer.name, applicationContext.getString(R.string.change_beer_new), -1)
}
private fun reviewPush(reviewString: String?) {
Loader.getData(this, Loader.REVIEWURL, -1, null, null)
val review = gson.fromJson(reviewString, Review::class.java)
intent = Intent(this, SingleBeerActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Beer.BEER, review.beerID)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(review.description, applicationContext.getString(R.string.change_review_new), review.userID)
}
private fun newsPush(newsString: String?) {
val news = gson.fromJson(newsString, News::class.java)
sendNotification(news.title, applicationContext.getString(R.string.change_news_new), -1)
}
private fun meetingPush(meetingString: String?) {
Loader.getData(this, Loader.MEETINGURL, -1, null, null)
val meeting = gson.fromJson(meetingString, Meeting::class.java)
intent = Intent(this, SingleMeetingActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Meeting.MEETING, meeting.id)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(meeting.subject, applicationContext.getString(R.string.change_meeting_new), meeting.userID)
}
private fun stickerPush(stickerString: String?) {
val sticker = gson.fromJson(stickerString, Sticker::class.java)
sendNotification(applicationContext.getString(R.string.change_sticker_new), sticker.notes, sticker.userID)
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private fun sendNotification(title: String, summary: String, userId: Int) {
val user = DataUtils.getUser(applicationContext, userId)
val icon = Glide.with(this).asBitmap().load(getGravatarURL(user.email)).submit(300, 300).get()
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.launcher_icon)
.setLargeIcon(icon)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
val style = NotificationCompat.BigTextStyle()
style.setBigContentTitle(title)
style.bigText(summary)
style.setSummaryText(summary)
notificationBuilder.setStyle(style)
if (pendingIntent == null) {
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
}
notificationBuilder.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
companion object {
const val TAG = "MessagingService"
}
}
| hamersapp/src/main/java/nl/ecci/hamers/fcm/MessagingService.kt | 2499439901 |
/*
* Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
* Copyright (C) 2017-2020 Pacien TRAN-GIRARD
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.pacien.tincapp.activities.status.networkinfo
import org.pacien.tincapp.R
import org.pacien.tincapp.context.App
import org.pacien.tincapp.data.CidrAddress
/**
* @author pacien
*/
object VpnInterfaceConfigurationFormatter {
private val resources by lazy { App.getResources() }
fun formatList(list: List<Any>?) = when {
list != null && list.isNotEmpty() -> list.joinToString("\n", transform = this::formatListElement)
else -> resources.getString(R.string.status_network_info_value_none)
}
private fun formatListElement(element: Any) = when (element) {
is CidrAddress -> element.toSlashSeparated()
is String -> element
else -> element.toString()
}
}
| app/src/main/java/org/pacien/tincapp/activities/status/networkinfo/VpnInterfaceConfigurationFormatter.kt | 2596737617 |
package mixit.util.web
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.junit5.MockKExtension
import mixit.MixitProperties
import mixit.security.MixitWebFilter
import mixit.security.MixitWebFilter.Companion.AUTHENT_COOKIE
import mixit.security.MixitWebFilter.Companion.BOTS
import mixit.security.model.Credential
import mixit.user.repository.UserRepository
import mixit.util.encodeToBase64
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.http.HttpCookie
import org.springframework.http.HttpHeaders
import org.springframework.http.server.reactive.ServerHttpRequest
import org.springframework.util.LinkedMultiValueMap
import org.springframework.util.MultiValueMap
import org.springframework.web.server.ServerWebExchange
import java.net.InetSocketAddress
import java.net.URI
import java.util.Locale
@ExtendWith(MockKExtension::class)
class MixitWebFilterTest() {
@RelaxedMockK
lateinit var request: ServerHttpRequest
@RelaxedMockK
lateinit var exchange: ServerWebExchange
@RelaxedMockK
lateinit var properties: MixitProperties
@RelaxedMockK
lateinit var userRepository: UserRepository
@InjectMockKs
lateinit var filter: MixitWebFilter
lateinit var headers: HttpHeaders
@BeforeEach
fun init() {
headers = HttpHeaders()
}
private fun mockExchangeRequest() {
every { request.headers } returns headers
every { exchange.request } returns request
}
@Test
fun `should find if user try to call an old URL or not`() {
mockExchangeRequest()
// If no host is defined
assertThat(filter.isACallOnOldUrl(exchange)).isFalse()
headers.setHost(InetSocketAddress("http://mix-it.fr", 8080))
assertThat(filter.isACallOnOldUrl(exchange)).isTrue()
headers.setHost(InetSocketAddress("https://mixitconf.org", 8080))
assertThat(filter.isACallOnOldUrl(exchange)).isFalse()
}
@Test
fun `a foreign user should be redirected on english version when he tries to open homepage`() {
mockExchangeRequest()
// By default the response is false
assertThat(filter.isAHomePageCallFromForeignLanguage(exchange)).isFalse()
// If user come on home page with no language french will be the default
every { request.uri } returns URI("https", "mixitconf.org", "/", "")
assertThat(filter.isAHomePageCallFromForeignLanguage(exchange)).isFalse()
// !if language is not french user has to be redirected
headers.acceptLanguageAsLocales = arrayListOf(Locale.ENGLISH)
assertThat(filter.isAHomePageCallFromForeignLanguage(exchange)).isTrue()
// But if it's a robot we don't want a redirection
headers.set(HttpHeaders.USER_AGENT, "DuckDuckBot")
assertThat(filter.isAHomePageCallFromForeignLanguage(exchange)).isFalse()
}
@Test
fun `should read credential from cookies`() {
val cookies: MultiValueMap<String, HttpCookie> = LinkedMultiValueMap()
every { request.cookies } returns cookies
// When request has no cookie credentials are null
assertThat(filter.readCredentialsFromCookie(request)).isNull()
// When cookie value is null credentials are null
cookies.put(AUTHENT_COOKIE, null)
assertThat(filter.readCredentialsFromCookie(request)).isNull()
// When cookie value is invalid credentials are null
cookies.put(AUTHENT_COOKIE, listOf(HttpCookie(AUTHENT_COOKIE, "invalid")))
assertThat(filter.readCredentialsFromCookie(request)).isNull()
// When cookie value is valid we have a credential
cookies.put(AUTHENT_COOKIE, listOf(HttpCookie(AUTHENT_COOKIE, "email:token".encodeToBase64())))
assertThat(filter.readCredentialsFromCookie(request)).isEqualTo(Credential("email", "token"))
}
@Test
fun `should detect if resource is an authorized static web resource`() {
assertThat(filter.isWebResource("/myfile.css")).isTrue()
assertThat(filter.isWebResource("/myfile.js")).isTrue()
assertThat(filter.isWebResource("/myfile.svg")).isTrue()
assertThat(filter.isWebResource("/myfile.jpg")).isTrue()
assertThat(filter.isWebResource("/myfile.png")).isTrue()
assertThat(filter.isWebResource("/myfile.webp")).isTrue()
assertThat(filter.isWebResource("/myfile.webapp")).isTrue()
assertThat(filter.isWebResource("/myfile.icns")).isTrue()
assertThat(filter.isWebResource("/myfile.ico")).isTrue()
assertThat(filter.isWebResource("/myfile.html")).isTrue()
assertThat(filter.isWebResource("/myfile.xls")).isFalse()
assertThat(filter.isWebResource("/myfile.cgi")).isFalse()
assertThat(filter.isWebResource("/api/users")).isFalse()
assertThat(filter.isWebResource("/talks")).isFalse()
}
@Test
fun `should detect if a robot is the caller`() {
mockExchangeRequest()
assertThat(filter.isSearchEngineCrawler(request)).isFalse()
headers.set(HttpHeaders.USER_AGENT, null)
assertThat(filter.isSearchEngineCrawler(request)).isFalse()
BOTS.forEach {
headers.set(HttpHeaders.USER_AGENT, it)
assertThat(filter.isSearchEngineCrawler(request)).isTrue()
}
headers.set(HttpHeaders.USER_AGENT, "unknown")
assertThat(filter.isSearchEngineCrawler(request)).isFalse()
}
}
| src/test/kotlin/mixit/util/web/MixitWebFilterTest.kt | 3230885194 |
package com.aidanvii.toolbox.delegates.observable.rxjava
import com.aidanvii.toolbox.assignedButNeverAccessed
import com.aidanvii.toolbox.delegates.observable.doOnNext
import com.aidanvii.toolbox.delegates.observable.observable
import com.aidanvii.toolbox.delegates.observable.skip
import com.aidanvii.toolbox.unusedValue
import com.aidanvii.toolbox.unusedVariable
import com.nhaarman.mockito_kotlin.inOrder
import org.amshove.kluent.mock
import org.junit.Test
@Suppress(assignedButNeverAccessed, unusedValue, unusedVariable)
class RxSkipDecoratorTest {
val mockDoOnNext = mock<(propertyEvent: Int) -> Unit>()
@Test
fun `only propagates values downstream after skipCount has been met`() {
val skipCount = 5
val givenValues = intArrayOf(1, 2, 3, 4, 5, 6, 7)
val expectedValues = givenValues.takeLast(givenValues.size - skipCount)
var property by observable(0)
.toRx()
.skip(skipCount)
.doOnNext { mockDoOnNext(it) }
for (givenValue in givenValues) {
property = givenValue
}
inOrder(mockDoOnNext).apply {
for (expectedValue in expectedValues) {
verify(mockDoOnNext).invoke(expectedValue)
}
}
}
} | delegates-observable-rxjava/src/test/java/com/aidanvii/toolbox/delegates/observable/rxjava/RxSkipDecoratorTest.kt | 3232946786 |
package com.infinum.dbinspector.ui.schema.triggers
import com.infinum.dbinspector.domain.shared.models.Statements
import com.infinum.dbinspector.ui.content.trigger.TriggerActivity
import com.infinum.dbinspector.ui.schema.shared.SchemaFragment
import org.koin.androidx.viewmodel.ext.android.viewModel
internal class TriggersFragment : SchemaFragment() {
companion object {
fun newInstance(databasePath: String, databaseName: String): TriggersFragment =
TriggersFragment().apply {
arguments = bundle(databasePath, databaseName)
}
}
override var statement: String = Statements.Schema.triggers()
override val viewModel: TriggersViewModel by viewModel()
override fun childView() = TriggerActivity::class.java
}
| dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/schema/triggers/TriggersFragment.kt | 2818485216 |
package quickbeer.android.domain.style.repository
import javax.inject.Inject
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import quickbeer.android.data.repository.Accept
import quickbeer.android.data.repository.repository.DefaultRepository
import quickbeer.android.data.state.State
import quickbeer.android.domain.style.Style
import quickbeer.android.domain.style.store.StyleStore
import quickbeer.android.domain.stylelist.repository.StyleListRepository
import quickbeer.android.network.result.ApiResult
class StyleRepository @Inject constructor(
store: StyleStore,
styleListRepository: StyleListRepository
) : DefaultRepository<Int, Style>(store, StyleFetcher(styleListRepository)::fetch)
/**
* A fake fetcher using StyleListRepository for doing the fetch. This ensures the fetched style
* list is persisted first. TODO this is a bit dirty, maybe some better approach?
*/
private class StyleFetcher(private val styleListRepository: StyleListRepository) {
suspend fun fetch(key: Int): ApiResult<Style> {
val state = styleListRepository.getStream(Accept())
.filter { it !is State.Loading }
.first()
return when (state) {
is State.Success -> ApiResult.Success(state.value.firstOrNull { it.id == key })
is State.Empty -> ApiResult.Success(null)
is State.Error -> ApiResult.UnknownError(state.cause)
else -> error("Unexpected state $state")
}
}
}
| app/src/main/java/quickbeer/android/domain/style/repository/StyleRepository.kt | 3123674235 |
package com.jtechme.jumpgo.search.suggestions
import com.jtechme.jumpgo.database.HistoryItem
import com.jtechme.jumpgo.utils.FileUtils
import com.jtechme.jumpgo.utils.Utils
import android.app.Application
import android.text.TextUtils
import android.util.Log
import okhttp3.*
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.net.URL
import java.net.URLEncoder
import java.util.*
import java.util.concurrent.TimeUnit
/**
* The base search suggestions API. Provides common
* fetching and caching functionality for each potential
* suggestions provider.
*/
abstract class BaseSuggestionsModel internal constructor(application: Application, private val encoding: String) {
private val httpClient: OkHttpClient
private val cacheControl = CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build()
/**
* Create a URL for the given query in the given language.
* @param query the query that was made.
* *
* @param language the locale of the user.
* *
* @return should return a URL that can be fetched using a GET.
*/
protected abstract fun createQueryUrl(query: String, language: String): String
/**
* Parse the results of an input stream into a list of [HistoryItem].
* @param inputStream the raw input to parse.
* *
* @param results the list to populate.
* *
* @throws Exception throw an exception if anything goes wrong.
*/
@Throws(Exception::class)
protected abstract fun parseResults(inputStream: InputStream, results: MutableList<HistoryItem>)
init {
val suggestionsCache = File(application.cacheDir, "suggestion_responses")
httpClient = OkHttpClient.Builder()
.cache(Cache(suggestionsCache, FileUtils.megabytesToBytes(1)))
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.build()
}
/**
* Retrieves the results for a query.
* @param rawQuery the raw query to retrieve the results for.
* *
* @return a list of history items for the query.
*/
fun fetchResults(rawQuery: String): List<HistoryItem> {
val filter = ArrayList<HistoryItem>(5)
val query: String
try {
query = URLEncoder.encode(rawQuery, encoding)
} catch (e: UnsupportedEncodingException) {
Log.e(TAG, "Unable to encode the URL", e)
return filter
}
val inputStream = downloadSuggestionsForQuery(query, language) ?: return filter
try {
parseResults(inputStream, filter)
} catch (e: Exception) {
Log.e(TAG, "Unable to parse results", e)
} finally {
Utils.close(inputStream)
}
return filter
}
/**
* This method downloads the search suggestions for the specific query.
* NOTE: This is a blocking operation, do not fetchResults on the UI thread.
* @param query the query to get suggestions for
* *
* @return the cache file containing the suggestions
*/
private fun downloadSuggestionsForQuery(query: String, language: String): InputStream? {
val queryUrl = createQueryUrl(query, language)
try {
val url = URL(queryUrl)
// OkHttp automatically gzips requests
val suggestionsRequest = Request.Builder().url(url)
.addHeader("Accept-Charset", encoding)
.cacheControl(cacheControl)
.build()
val suggestionsResponse = httpClient.newCall(suggestionsRequest).execute()
val responseBody = suggestionsResponse.body()
return responseBody?.byteStream()
} catch (exception: IOException) {
Log.e(TAG, "Problem getting search suggestions", exception)
}
return null
}
companion object {
private val TAG = "BaseSuggestionsModel"
internal val MAX_RESULTS = 5
private val INTERVAL_DAY = TimeUnit.DAYS.toSeconds(1)
private val DEFAULT_LANGUAGE = "en"
private val language by lazy {
var lang = Locale.getDefault().language
if (TextUtils.isEmpty(lang)) {
lang = DEFAULT_LANGUAGE
}
lang
}
private val REWRITE_CACHE_CONTROL_INTERCEPTOR = Interceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.header("cache-control", "max-age=$INTERVAL_DAY, max-stale=$INTERVAL_DAY")
.build()
}
}
}
| app/src/main/java/com/jtechme/jumpgo/search/suggestions/BaseSuggestionsModel.kt | 281420791 |
/*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package org.jetbrains.anko
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Handler
import android.os.Looper
import java.lang.ref.WeakReference
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* Execute [f] on the application UI thread.
*/
fun Context.runOnUiThread(f: Context.() -> Unit) {
if (Looper.getMainLooper() === Looper.myLooper()) f() else ContextHelper.handler.post { f() }
}
/**
* Execute [f] on the application UI thread.
*/
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun Fragment.runOnUiThread(crossinline f: () -> Unit) {
activity?.runOnUiThread { f() }
}
class AnkoAsyncContext<T>(val weakRef: WeakReference<T>)
/**
* Execute [f] on the application UI thread.
* If the [doAsync] receiver still exists (was not collected by GC),
* [f] gets it as a parameter ([f] gets null if the receiver does not exist anymore).
*/
fun <T> AnkoAsyncContext<T>.onComplete(f: (T?) -> Unit) {
val ref = weakRef.get()
if (Looper.getMainLooper() === Looper.myLooper()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
}
/**
* Execute [f] on the application UI thread.
* [doAsync] receiver will be passed to [f].
* If the receiver does not exist anymore (it was collected by GC), [f] will not be executed.
*/
fun <T> AnkoAsyncContext<T>.uiThread(f: (T) -> Unit): Boolean {
val ref = weakRef.get() ?: return false
if (Looper.getMainLooper() === Looper.myLooper()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
return true
}
/**
* Execute [f] on the application UI thread if the underlying [Activity] still exists and is not finished.
* The receiver [Activity] will be passed to [f].
* If it is not exist anymore or if it was finished, [f] will not be called.
*/
fun <T: Activity> AnkoAsyncContext<T>.activityUiThread(f: (T) -> Unit): Boolean {
val activity = weakRef.get() ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { f(activity) }
return true
}
fun <T: Activity> AnkoAsyncContext<T>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val activity = weakRef.get() ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { activity.f(activity) }
return true
}
@JvmName("activityContextUiThread")
fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThread(f: (T) -> Unit): Boolean {
val activity = weakRef.get()?.owner ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { f(activity) }
return true
}
@JvmName("activityContextUiThreadWithContext")
fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val activity = weakRef.get()?.owner ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { activity.f(activity) }
return true
}
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThread(f: (T) -> Unit): Boolean {
val fragment = weakRef.get() ?: return false
if (fragment.isDetached) return false
val activity = fragment.activity ?: return false
activity.runOnUiThread { f(fragment) }
return true
}
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val fragment = weakRef.get() ?: return false
if (fragment.isDetached) return false
val activity = fragment.activity ?: return false
activity.runOnUiThread { activity.f(fragment) }
return true
}
private val crashLogger = { throwable : Throwable -> throwable.printStackTrace() }
/**
* Execute [task] asynchronously.
*
* @param exceptionHandler optional exception handler.
* If defined, any exceptions thrown inside [task] will be passed to it. If not, exceptions will be ignored.
* @param task the code to execute asynchronously.
*/
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
return@submit try {
context.task()
} catch (thr: Throwable) {
val result = exceptionHandler?.invoke(thr)
if (result != null) {
result
} else {
Unit
}
}
}
}
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
executorService: ExecutorService,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<Unit> {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
}
}
}
fun <T, R> T.doAsyncResult(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
task: AnkoAsyncContext<T>.() -> R
): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
throw thr
}
}
}
fun <T, R> T.doAsyncResult(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
executorService: ExecutorService,
task: AnkoAsyncContext<T>.() -> R
): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<R> {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
throw thr
}
}
}
internal object BackgroundExecutor {
var executor: ExecutorService =
Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors())
fun <T> submit(task: () -> T): Future<T> = executor.submit(task)
}
private object ContextHelper {
val handler = Handler(Looper.getMainLooper())
}
| anko/library/static/commons/src/main/java/Async.kt | 3425392699 |
package com.moviereel.data.prefs
/**
* @author lusinabrian on 28/03/17
* * This interface will allow interaction with the [android.content.SharedPreferences] API
* * This will handle all data relating to shared preferences such as settings configuration and storing user
* * data. This will be delegated that task by [com.moviereel.data.DataManager]
*/
interface PreferencesHelper {
/**
* checks and sees if this application has been started for the first time
* Returns True if this is the first start, False otherwise
* @return [Boolean]
*/
fun getFirstStart() : Boolean
/**
* Once the application has started for the first time, this will set the value to false
* thus the app will start the splash screen activity when [.getFirstStart] is called
* @param setFirstStart sets the value for the first start
* *
*/
fun setFirstStart(setFirstStart: Boolean) : Unit
}
| app/src/main/kotlin/com/moviereel/data/prefs/PreferencesHelper.kt | 825353807 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.Handle
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.processModel.*
import nl.adaptivity.util.DomUtil
import nl.adaptivity.xmlutil.SimpleNamespaceContext
import nl.adaptivity.xmlutil.XmlException
import nl.adaptivity.xmlutil.XmlUtilInternal
import nl.adaptivity.xmlutil.siblingsToFragment
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
import nl.adaptivity.xmlutil.util.XMLFragmentStreamReader
import org.w3c.dom.NodeList
import java.io.CharArrayReader
import java.sql.SQLException
import javax.xml.xpath.XPathConstants
actual fun IXmlDefineType.applyData(nodeInstanceSource: IProcessInstance, context: ActivityInstanceContext): ProcessData {
// TODO, make this not need engineData
val nodeInstance = nodeInstanceSource.getChildNodeInstance(context.handle)
return applyDataImpl(nodeInstanceSource, refNode?.let { nodeInstance.resolvePredecessor(nodeInstanceSource, it)}, context.processContext.handle)
}
@Throws(SQLException::class)
actual fun IXmlDefineType.applyFromProcessInstance(processInstance: ProcessInstance.Builder): ProcessData {
val predecessor: IProcessNodeInstance? = refNode?.let { refNode -> processInstance
.allChildNodeInstances { it.node.id == refNode }
.lastOrNull()
}
return applyDataImpl(processInstance, predecessor?.build(processInstance), processInstance.handle)
}
@OptIn(XmlUtilInternal::class)
private fun IXmlDefineType.applyDataImpl(nodeInstanceSource: IProcessInstance, predecessor: IProcessNodeInstance?, hProcessInstance: Handle<SecureObject<ProcessInstance>>): ProcessData {
val processData: ProcessData
val predRefName = predecessor?.node?.effectiveRefName(refName)
if (predecessor != null && predRefName != null) {
val origpair = predecessor.getResult(predRefName)
if (origpair == null) {
// TODO on missing data do something else than an empty value
processData = ProcessData.missingData(name)
} else {
val xPath = when (this) {
is XPathHolder -> xPath
else -> null
}
processData = when (xPath) {
null -> ProcessData(name, origpair.content)
else -> ProcessData(
name,
DomUtil.nodeListToFragment(
xPath.evaluate(origpair.contentFragment, XPathConstants.NODESET) as NodeList
)
)
}
}
} else if (predecessor==null && !refName.isNullOrEmpty()) { // Reference to container
return nodeInstanceSource.inputs.single { it.name == refName }.let { ProcessData(name, it.content) }
} else {
processData = ProcessData(name, CompactFragment(""))
}
val content = content
if (content != null && content.isNotEmpty()) {
try {
val transformer = PETransformer.create(SimpleNamespaceContext.from(originalNSContext), processData)
val fragmentReader =
when (this) {
is ICompactFragment -> XMLFragmentStreamReader.from(this)
else -> XMLFragmentStreamReader.from(CharArrayReader(content), originalNSContext)
}
val reader = transformer.createFilter(fragmentReader)
if (reader.hasNext()) reader.next() // Initialise the reader
val transformed = reader.siblingsToFragment()
return ProcessData(name, transformed)
} catch (e: XmlException) {
throw RuntimeException(e)
}
} else {
return processData
}
}
private fun ProcessNode.effectiveRefName(refName: String?): String? = when {
! refName.isNullOrEmpty() -> refName
else -> results.singleOrNull()?.getName()
}
| ProcessEngine/core/src/jvmMain/kotlin/nl/adaptivity/process/engine/processModel/ExecutableDefineType.kt | 500515787 |
package de.westnordost.streetcomplete.quests.barrier_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.AImageListQuestAnswerFragment
import de.westnordost.streetcomplete.quests.barrier_type.StileType.*
import de.westnordost.streetcomplete.view.image_select.DisplayItem
import de.westnordost.streetcomplete.view.image_select.Item
class AddStileTypeForm : AImageListQuestAnswerFragment<StileTypeAnswer, StileTypeAnswer>() {
override val items: List<DisplayItem<StileTypeAnswer>> = listOf(
Item(SQUEEZER, R.drawable.barrier_stile_squeezer, R.string.quest_barrier_type_stile_squeezer),
Item(LADDER, R.drawable.barrier_stile_ladder, R.string.quest_barrier_type_stile_ladder),
Item(STEPOVER_WOODEN, R.drawable.barrier_stile_stepover_wooden, R.string.quest_barrier_type_stepover_wooden),
Item(STEPOVER_STONE, R.drawable.barrier_stile_stepover_stone, R.string.quest_barrier_type_stepover_stone),
Item(ConvertedStile.KISSING_GATE, R.drawable.barrier_kissing_gate, R.string.quest_barrier_type_kissing_gate_conversion),
Item(ConvertedStile.PASSAGE, R.drawable.barrier_passage, R.string.quest_barrier_type_passage_conversion),
Item(ConvertedStile.GATE, R.drawable.barrier_gate_pedestrian, R.string.quest_barrier_type_gate_conversion),
)
override val itemsPerRow = 2
override fun onClickOk(selectedItems: List<StileTypeAnswer>) {
applyAnswer(selectedItems.single())
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/barrier_type/AddStileTypeForm.kt | 3610253046 |
package org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards
import android.annotation.TargetApi
import android.os.Build
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.style.URLSpan
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.LeaderboardItemRow
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.Type.PRODUCTS
/**
* The API response from the V4 Leaderboards endpoint returns the Top Performers Products list as an array of arrays,
* each inner array represents a Top Performer Product itself, so in the end it's an array of Top Performers items.
*
* Each Top Performer item is an array containing three objects with the following properties: display and value.
*
* Single Top Performer item response example:
[
{
"display": "<a href='https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin&path=\/analytics\/products&filter=single_product&products=14'>Beanie<\/a>",
"value": "Beanie"
},
{
"display": "2.000",
"value": 2000
},
{
"display": "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">R$<\/span>36.000,00<\/span>",
"value": 36000
}
]
This class represents one Single Top Performer item response as a Product type one
*/
@Suppress("MaxLineLength")
class LeaderboardProductItem(
private val itemRows: Array<LeaderboardItemRow>? = null
) {
val quantity
get() = itemRows
?.second()
?.value
val total
get() = itemRows
?.third()
?.value
/**
* This property will operate and transform a HTML tag in order to retrieve the currency symbol out of it.
*
* Example:
* HTML tag -> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">R$<\/span>36.000,00<\/span>
*
* split from ">" delimiter
* Output: string list containing
* <span class=\"woocommerce-Price-amount amount\"
* <span class=\"woocommerce-Price-currencySymbol\"
* R$<\/span
* 36.000,00<\/span
*
* first who contains "&#"
* Output: R$<\/span>
*
* split from ";" delimiter
* Output: string list containing
* R
* $
* <\/span>
*
* filter what contains "&#"
* Output: string list containing
* R
* $
*
* reduce string list
* Output: R$
*
* fromHtmlWithSafeApiCall
* Output: R$
*/
@Suppress("MaxLineLength") val currency by lazy {
priceAmountHtmlTag
?.split(">")
?.firstOrNull { it.contains("&#") }
?.split(";")
?.filter { it.contains("&#") }
?.reduce { total, new -> "$total$new" }
?.run { fromHtmlWithSafeApiCall(this) }
?: plainTextCurrency
}
/**
* This property will serve as a fallback for cases where the currency is represented in plain text instead of
* HTML currency code.
*
* It will extract the raw content between tags and leave only the currency information
*
* Example:
*
* HTML tag -> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">DKK<\/span>36.000,00<\/span>
*
* parse HTML tag to string
* Output: DKK36.000,00
*
* regex filter with replace
* Output: DKK
*/
@Suppress("MaxLineLength") private val plainTextCurrency by lazy {
fromHtmlWithSafeApiCall(priceAmountHtmlTag)
.toString()
.replace(Regex("[0-9.,]"), "")
}
/**
* This property will operate and transform a URL string in order to retrieve the product id parameter out of it.
*
* Example:
* URL string -> https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin&path=\/analytics\/products&filter=single_product&products=14
*
* split from "&" delimiter
* Output: string list containing
* https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin
* filter=single_product
* products=14
*
* first who contains "products="
* Output: products=14
*
* split from "=" delimiter
* Output: string list containing
* products
* 14
*
* extract last string from the list
* Output: 14 as String
*
* try to convert to long
* Output: 14 as Long
*/
@Suppress("MaxLineLength") val productId by lazy {
link
?.split("&")
?.firstOrNull { it.contains("${PRODUCTS.value}=", true) }
?.split("=")
?.last()
?.toLongOrNull()
}
/**
* This property will operate and transform a HTML tag in order to retrieve the inner URL out of the <a href/> tag
* using the [SpannableStringBuilder] implementation in order to parse it
*/
private val link by lazy {
fromHtmlWithSafeApiCall(itemHtmlTag)
.run { this as? SpannableStringBuilder }
?.spansAsList()
?.firstOrNull()
?.url
}
private val itemHtmlTag by lazy {
itemRows
?.first()
?.display
}
private val priceAmountHtmlTag by lazy {
itemRows
?.third()
?.display
}
private fun SpannableStringBuilder.spansAsList() =
getSpans(0, length, URLSpan::class.java)
.toList()
@TargetApi(Build.VERSION_CODES.N)
private fun fromHtmlWithSafeApiCall(source: String?) = source
?.takeIf { Build.VERSION.SDK_INT >= Build.VERSION_CODES.N }?.let {
Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)
} ?: Html.fromHtml(source)
/**
* Returns the second object of the Top Performer Item Array if exists
*/
private fun Array<LeaderboardItemRow>.second() =
takeIf { isNotEmpty() && size > 1 }
?.let { this[1] }
/**
* Returns the third object of the Top Performer Item Array if exists
*/
private fun Array<LeaderboardItemRow>.third() =
takeIf { isNotEmpty() && size > 2 }
?.let { this[2] }
}
| plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/leaderboards/LeaderboardProductItem.kt | 863882471 |
package org.wordpress.android.fluxc.example.ui.products
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.fragment_woo_product_filters.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCTS
import org.wordpress.android.fluxc.example.R.layout
import org.wordpress.android.fluxc.example.prependToLog
import org.wordpress.android.fluxc.example.ui.ListSelectorDialog
import org.wordpress.android.fluxc.example.ui.ListSelectorDialog.Companion.ARG_LIST_SELECTED_ITEM
import org.wordpress.android.fluxc.example.ui.ListSelectorDialog.Companion.LIST_SELECTOR_REQUEST_CODE
import org.wordpress.android.fluxc.generated.WCProductActionBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStatus
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStockStatus
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductType
import org.wordpress.android.fluxc.store.WCProductStore
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductsPayload
import org.wordpress.android.fluxc.store.WCProductStore.OnProductChanged
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.CATEGORY
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.STATUS
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.STOCK_STATUS
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.TYPE
import org.wordpress.android.fluxc.store.WooCommerceStore
import java.io.Serializable
import javax.inject.Inject
class WooProductFiltersFragment : Fragment() {
@Inject internal lateinit var dispatcher: Dispatcher
@Inject internal lateinit var wooCommerceStore: WooCommerceStore
@Inject internal lateinit var wcProductStore: WCProductStore
private var selectedSiteId: Int = -1
private var filterOptions: MutableMap<ProductFilterOption, String>? = null
companion object {
const val ARG_SELECTED_SITE_ID = "ARG_SELECTED_SITE_ID"
const val ARG_SELECTED_FILTER_OPTIONS = "ARG_SELECTED_FILTER_OPTIONS"
const val LIST_RESULT_CODE_STOCK_STATUS = 101
const val LIST_RESULT_CODE_PRODUCT_TYPE = 102
const val LIST_RESULT_CODE_PRODUCT_STATUS = 103
@JvmStatic
fun newInstance(selectedSitePosition: Int): WooProductFiltersFragment {
return WooProductFiltersFragment().apply {
this.selectedSiteId = selectedSitePosition
}
}
}
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onStart() {
super.onStart()
dispatcher.register(this)
}
override fun onStop() {
super.onStop()
dispatcher.unregister(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(layout.fragment_woo_product_filters, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
savedInstanceState?.let { bundle -> selectedSiteId = bundle.getInt(ARG_SELECTED_SITE_ID) }
filterOptions = savedInstanceState?.getSerializable(ARG_SELECTED_FILTER_OPTIONS)
as? MutableMap<ProductFilterOption, String> ?: mutableMapOf()
filter_stock_status.setOnClickListener {
showListSelectorDialog(
CoreProductStockStatus.values().map { it.value }.toList(),
LIST_RESULT_CODE_STOCK_STATUS, filterOptions?.get(STOCK_STATUS)
)
}
filter_by_status.setOnClickListener {
showListSelectorDialog(
CoreProductStatus.values().map { it.value }.toList(),
LIST_RESULT_CODE_PRODUCT_STATUS, filterOptions?.get(STATUS)
)
}
filter_by_type.setOnClickListener {
showListSelectorDialog(
CoreProductType.values().map { it.value }.toList(),
LIST_RESULT_CODE_PRODUCT_TYPE, filterOptions?.get(TYPE)
)
}
filter_by_category.setOnClickListener {
getWCSite()?.let { site ->
val randomCategory = wcProductStore.getProductCategoriesForSite(site).random()
filterOptions?.clear()
filterOptions?.put(CATEGORY, randomCategory.remoteCategoryId.toString())
prependToLog("Selected category: ${randomCategory.name} id: ${randomCategory.remoteCategoryId}")
}
}
filter_products.setOnClickListener {
getWCSite()?.let { site ->
val payload = FetchProductsPayload(site, filterOptions = filterOptions)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductsAction(payload))
} ?: prependToLog("No valid siteId defined...doing nothing")
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(ARG_SELECTED_SITE_ID, selectedSiteId)
outState.putSerializable(ARG_SELECTED_FILTER_OPTIONS, filterOptions as? Serializable)
}
private fun getWCSite() = wooCommerceStore.getWooCommerceSites().getOrNull(selectedSiteId)
private fun showListSelectorDialog(listItems: List<String>, resultCode: Int, selectedItem: String? = null) {
fragmentManager?.let { fm ->
val dialog = ListSelectorDialog.newInstance(
this, listItems, resultCode, selectedItem
)
dialog.show(fm, "ListSelectorDialog")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == LIST_SELECTOR_REQUEST_CODE) {
val selectedItem = data?.getStringExtra(ARG_LIST_SELECTED_ITEM)
when (resultCode) {
LIST_RESULT_CODE_PRODUCT_TYPE -> {
selectedItem?.let { filterOptions?.put(TYPE, it) }
}
LIST_RESULT_CODE_STOCK_STATUS -> {
selectedItem?.let { filterOptions?.put(STOCK_STATUS, it) }
}
LIST_RESULT_CODE_PRODUCT_STATUS -> {
selectedItem?.let { filterOptions?.put(STATUS, it) }
}
}
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductChanged(event: OnProductChanged) {
if (event.isError) {
prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type)
return
}
if (event.causeOfChange == FETCH_PRODUCTS) {
prependToLog("Fetched ${event.rowsAffected} products")
filterOptions?.let {
if (it.containsKey(CATEGORY)) {
prependToLog("From category ID " + it[CATEGORY])
}
}
}
}
}
| example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooProductFiltersFragment.kt | 4253428383 |
package com.naosim.rtm.infra.datasource
import com.naosim.rtm.domain.model.RtmParamValueObject
import com.naosim.rtm.domain.model.auth.Token
import com.naosim.rtm.domain.model.timeline.TimelineId
import com.naosim.rtm.domain.repository.RtmAuthRepository
import com.naosim.rtm.domain.repository.RtmRepository
import com.naosim.rtm.domain.repository.RtmTaskRepository
import com.naosim.rtm.infra.datasource.common.RtmMethod
import com.naosim.rtm.infra.datasource.common.RtmParam
import com.naosim.rtm.infra.datasource.common.RtmRequestUtil
import java.util.*
class RtmRepositoryNet(val rtmApiConfig: RtmApiConfig, val rtmAuthRepository: RtmAuthRepository, val rtmTaskRepository: RtmTaskRepository): RtmRepository, RtmAuthRepository by rtmAuthRepository, RtmTaskRepository by rtmTaskRepository {
private val rtmRequestUtil = RtmRequestUtil(rtmApiConfig)
override fun createTimeline(token: Token): TimelineId {
val rtmParams = HashMap<RtmParam, RtmParamValueObject>()
rtmParams.put(RtmParam.method, RtmMethod.timelines_create)
rtmParams.put(RtmParam.auth_token, token)
val response = rtmRequestUtil.requestXML(rtmParams).body
if(response.isFailed) {
throw RuntimeException(response.failedResponse!!.code + " " + response.failedResponse!!.msg)
}
return TimelineId(response.getFirstElementValueByTagName("timeline"))
}
}
class RtmRepositoryNetFactory {
fun create(rtmApiConfig: RtmApiConfig): RtmRepositoryNet {
return RtmRepositoryNet(
rtmApiConfig,
RtmAuthRepositoryNet(rtmApiConfig),
RtmTaskRepositoryNet(rtmApiConfig)
)
}
}
| src/main/java/com/naosim/rtm/infra/datasource/RtmRepositoryNet.kt | 3117057841 |
package com.sxtanna.database.task.builder.base
import com.sxtanna.database.struct.obj.Target
import com.sxtanna.database.struct.obj.Target.Position
import com.sxtanna.database.struct.obj.Target.Position.*
import com.sxtanna.database.type.base.SqlObject
abstract class TargetedStatement<T : SqlObject, W : TargetedStatement<T, W>> : BuilderStatement() {
val where = mutableListOf<Target>()
@JvmOverloads
fun like(column : String, value : Any, option : Position, not : Boolean = false) = impl().apply { where.add(Target.like(column, value, option, not)) }
@JvmOverloads
fun startsWith(column : String, value : Any, not : Boolean = false) = like(column, value, START, not)
@JvmSynthetic
@JvmName("inStartsWith")
infix fun String.startsWith(value : Any) = startsWith(this, value, false)
@JvmSynthetic
infix fun String.startsNotWith(value : Any) = startsWith(this, value, true)
@JvmOverloads
fun contains(column : String, value : Any, not : Boolean = false) = like(column, value, CONTAINS, not)
@JvmSynthetic
@JvmName("inContains")
infix fun String.contains(value : Any) = contains(this, value, false)
@JvmSynthetic
infix fun String.containsNot(value : Any) = contains(this, value, true)
@JvmOverloads
fun endsWith(column : String, value : Any, not : Boolean = false) = like(column, value, END, not)
@JvmSynthetic
@JvmName("inEndsWith")
infix fun String.endsWith(value : Any) = endsWith(this, value, false)
@JvmSynthetic
infix fun String.endsNotWith(value : Any) = endsWith(this, value, true)
@JvmOverloads
fun equals(column : String, value : Any, not : Boolean = false) = impl().apply { where.add(Target.equals(column, value, not)) }
@JvmSynthetic
@JvmName("inEquals")
infix fun String.equals(value : Any) = equals(this, value, false)
@JvmSynthetic
infix fun String.equalsNot(value : Any) = equals(this, value, true)
@JvmOverloads
fun between(column : String, first : Any, second : Any, not : Boolean = false) = impl().apply { where.add(Target.between(column, first, second, not)) }
@JvmSynthetic
infix fun String.between(data : Pair<Any, Any>) = between(this, data.first, data.second, false)
@JvmSynthetic
infix fun String.notBetween(data : Pair<Any, Any>) = between(this, data.first, data.second, true)
fun lesser(column : String, value : Any, orEqual : Boolean) = impl().apply { where.add(Target.lesser(column, value, orEqual)) }
@JvmSynthetic
infix fun String.lesser(value : Any) = lesser(this, value, false)
@JvmSynthetic
infix fun String.lesserOrEqual(value : Any) = lesser(this, value, true)
fun greater(column : String, value : Any, orEqual : Boolean) = impl().apply { where.add(Target.greater(column, value, orEqual)) }
@JvmSynthetic
infix fun String.greater(value : Any) = greater(this, value, false)
@JvmSynthetic
infix fun String.greaterOrEqual(value : Any) = greater(this, value, true)
abstract protected fun impl() : W
} | src/main/kotlin/com/sxtanna/database/task/builder/base/TargetedStatement.kt | 1731422335 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.util.text
import org.apache.commons.lang3.StringUtils
/**
* Normalizes the spaces of this [String].
*/
inline fun String.normalizeSpaces(): String = StringUtils.normalizeSpace(this)
/**
* Normalizes the spaces of this [CharSequence].
*/
inline fun CharSequence.normalizeSpaces(): CharSequence = StringUtils.normalizeSpace(toString())
| src/main/kotlin/org/lanternpowered/api/util/text/CharSequence.kt | 2736031817 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.type.play
import org.lanternpowered.api.entity.player.chat.ChatVisibility
import org.lanternpowered.server.network.packet.Packet
import org.spongepowered.api.data.type.HandPreference
import java.util.Locale
data class ClientSettingsPacket(
val locale: Locale,
val viewDistance: Int,
val chatVisibility: ChatVisibility,
val dominantHand: HandPreference,
val enableColors: Boolean,
val skinPartsBitPattern: Int
) : Packet
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/type/play/ClientSettingsPacket.kt | 1737288141 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("FunctionName", "NOTHING_TO_INLINE")
package org.lanternpowered.api.item.enchantment
import java.util.function.Supplier
typealias Enchantment = org.spongepowered.api.item.enchantment.Enchantment
/**
* Constructs a new [Enchantment] with the given [EnchantmentType] and level. If no
* level is specified, then will the minimum one be used instead.
*
* @param type The enchantment type
* @param level The level of the enchantment
* @return The constructed enchantment
*/
inline fun enchantmentOf(type: Supplier<out EnchantmentType>, level: Int = type.get().minimumLevel): Enchantment = Enchantment.of(type, level)
/**
* Constructs a new [Enchantment] with the given [EnchantmentType] and level. If no
* level is specified, then will the minimum one be used instead.
*
* @param type The enchantment type
* @param level The level of the enchantment
* @return The constructed enchantment
*/
inline fun enchantmentOf(type: EnchantmentType, level: Int = type.minimumLevel): Enchantment = Enchantment.of(type, level)
| src/main/kotlin/org/lanternpowered/api/item/enchantment/Enchantment.kt | 44141265 |
package bg.o.sim.colourizmus.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import androidx.annotation.ColorInt
import java.io.Serializable
const val TABLE: String = "colour"
const val COLUMN_PK: String = "value"
const val COLUMN_NAME: String = "name"
const val COLUMN_IS_FAVOURITE: String = "is_favourite"
/**
* The [CustomColour] represents a single, named, colour that
* can be marked as favourite and is persisted in on-disk database.
*/
@Entity(tableName = TABLE, indices = [(Index(value = [COLUMN_NAME], unique = true))])
class CustomColour(@ColorInt value: Int, name: String) : Serializable {
@PrimaryKey(autoGenerate = false)
@ColumnInfo(name = COLUMN_PK)
@ColorInt val value: Int = value
@ColumnInfo(name = COLUMN_NAME)
var name: String = name
@ColumnInfo(name = COLUMN_IS_FAVOURITE)
var isFavourite: Boolean = false
// TODO: 16/02/18 - include name in hash? Yes? No?
override fun hashCode(): Int = value
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (this.javaClass != other?.javaClass) return false
other as CustomColour
if (value != other.value) return false
if (name != other.name) return false
return true
}
}
| app/src/main/java/bg/o/sim/colourizmus/model/CustomColour.kt | 1395833135 |
package me.echeung.moemoekyun.util.system
import android.content.Context
import android.os.Build
import me.echeung.moemoekyun.BuildConfig
import me.echeung.moemoekyun.util.ext.connectivityManager
import me.echeung.moemoekyun.viewmodel.RadioViewModel
import org.koin.core.component.KoinComponent
import org.koin.core.component.get
object NetworkUtil : KoinComponent {
val userAgent: String
get() = String.format(
"%s/%s (%s; %s; Android %s)",
BuildConfig.APPLICATION_ID,
BuildConfig.VERSION_NAME,
Build.DEVICE,
Build.BRAND,
Build.VERSION.SDK_INT,
)
fun isNetworkAvailable(context: Context?): Boolean {
context ?: return false
val isAvailable = context.connectivityManager.activeNetworkInfo?.isConnected ?: false
val radioViewModel: RadioViewModel = get()
radioViewModel.isConnected = isAvailable
return isAvailable
}
}
| app/src/main/kotlin/me/echeung/moemoekyun/util/system/NetworkUtil.kt | 536269554 |
package ch.difty.scipamato.core.web.paper.common
import ch.difty.scipamato.common.AjaxRequestTargetSpy
import ch.difty.scipamato.core.entity.search.SearchCondition
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkboxx.CheckBoxX
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeNull
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.model.Model
import org.junit.jupiter.api.Test
@Suppress("SpellCheckingInspection")
internal class SearchablePaperPanelTest : PaperPanelTest<SearchCondition, SearchablePaperPanel>() {
override fun makePanel(): SearchablePaperPanel = newPanel()
private fun newPanel(attachments: Boolean? = null, attachmentName: String? = null): SearchablePaperPanel {
val sc = SearchCondition().apply {
id = "1"
number = "100"
authors = "a"
firstAuthor = "fa"
isFirstAuthorOverridden = false
title = "t"
location = "l"
publicationYear = "2017"
pmId = "pmid"
doi = "doi"
createdDisplayValue = "cdv"
modifiedDisplayValue = "lmdv"
goals = "g"
population = "p"
methods = "m"
populationPlace = "ppl"
populationParticipants = "ppa"
populationDuration = "pd"
exposurePollutant = "ep"
exposureAssessment = "ea"
methodStudyDesign = "msd"
methodOutcome = "mo"
methodStatistics = "ms"
methodConfounders = "mc"
result = "r"
intern = "i"
resultMeasuredOutcome = "rmo"
resultExposureRange = "rer"
resultEffectEstimate = "ree"
conclusion = "cc"
comment = "c"
addCode(newC(1, "F"))
mainCodeOfCodeclass1 = "mcocc1"
addCode(newC(2, "A"))
addCode(newC(3, "A"))
addCode(newC(4, "A"))
addCode(newC(5, "A"))
addCode(newC(6, "A"))
addCode(newC(7, "A"))
addCode(newC(8, "A"))
codesExcluded = "1B 2C"
originalAbstract = "oa"
hasAttachments = attachments
attachmentNameMask = attachmentName
}
return object : SearchablePaperPanel("panel", Model.of(sc)) {
override fun onFormSubmit() {
// no-op
}
override fun restartSearchInPaperSearchPage() {
// no-op
}
override fun doOnSubmit() {
// no-op
}
}
}
override fun assertSpecificComponents() {
var b = "panel"
tester.assertComponent(b, SearchablePaperPanel::class.java)
assertCommonComponents(b)
b += ":form"
assertTextFieldWithLabel("$b:id", "1", "ID")
assertTextFieldWithLabel("$b:number", "100", "SciPaMaTo-Core-No.")
assertTextFieldWithLabel("$b:publicationYear", "2017", "Pub. Year")
assertTextFieldWithLabel("$b:pmId", "pmid", "PMID")
tester.assertLabel("$b:submit:label", "Search")
assertTextFieldWithLabel("$b:createdDisplayValue", "cdv", "Created")
assertTextFieldWithLabel("$b:modifiedDisplayValue", "lmdv", "Last Modified")
tester.assertComponent("$b:submit", BootstrapButton::class.java)
verifyCodeAndCodeClassCalls(1)
tester.clickLink("panel:form:tabs:tabs-container:tabs:5:link")
val bb = "$b:tabs:panel"
val bbb = "$bb:tab6Form"
assertTextFieldWithLabel("$bbb:attachmentNameMask", null, "Attachment Name Mask")
assertComponentWithLabel("$bbb:hasAttachments", CheckBoxX::class.java, null, "W/ or w/o Attachments")
tester.assertComponent(bbb, Form::class.java)
}
@Test
fun specificFields_areEnabled() {
tester.startComponentInPage(makePanel())
tester.isEnabled("panel:form:id")
tester.isEnabled("panel:form:number")
tester.isEnabled("panel:form:firstAuthorOverridden")
tester.isEnabled("panel:form:createdDisplayValue")
tester.isEnabled("panel:form:modifiedDisplayValue")
}
@Test
fun summary_doesNotExist() {
tester.startComponentInPage(makePanel())
tester.assertContainsNot("panel:form:summary")
}
@Test
fun summaryShort_doesNotExist() {
tester.startComponentInPage(makePanel())
tester.assertContainsNot("panel:form:summaryShort")
}
@Test
fun navigationButtons_andPubmedRetrieval_andBackButton_areInvisible() {
tester.startComponentInPage(makePanel())
tester.assertInvisible("panel:form:previous")
tester.assertInvisible("panel:form:next")
tester.assertInvisible("panel:form:pubmedRetrieval")
tester.assertInvisible("panel:form:back")
}
@Test
fun assertSubmit() {
tester.startComponentInPage(makePanel())
applyTestHackWithNestedMultiPartForms()
tester.submitForm("panel:form")
}
@Test
fun gettingCallingPage_isNull() {
val panel = tester.startComponentInPage(makePanel())
panel.callingPage.shouldBeNull()
}
@Test
fun isNotAssociatedWithNewsletter() {
makePanel().isAssociatedWithNewsletter.shouldBeFalse()
}
@Test
fun isNotAssociatedWithWipNewsletter() {
makePanel().isAssociatedWithWipNewsletter.shouldBeFalse()
}
@Test
fun isNotNewsletterInStatusWip() {
makePanel().isaNewsletterInStatusWip().shouldBeFalse()
}
@Test
fun modifyNewsletterAssociation_isNoOp() {
val targetDummy = AjaxRequestTargetSpy()
makePanel().modifyNewsletterAssociation(targetDummy)
targetDummy.components.isEmpty()
targetDummy.javaScripts.isEmpty()
}
@Test
fun withExcludedCodeFilter() {
tester.startComponentInPage(newPanel())
val bbb = prepareCodePanel()
assertTextFieldWithLabel("$bbb:codesExcluded", "1B 2C", "Excluded Codes")
verifyCodeAndCodeClassCalls(1)
}
@Test
fun withAttachmentFilter_havingAttachments() {
tester.startComponentInPage(newPanel(attachments = true))
val bbb = prepareAttachmentPanel()
assertTextFieldWithLabel("$bbb:attachmentNameMask", null, "Attachment Name Mask")
assertComponentWithLabel("$bbb:hasAttachments", CheckBoxX::class.java, true, "W/ or w/o Attachments")
}
@Test
fun withAttachmentFilter_notHavingAttachments() {
tester.startComponentInPage(newPanel(attachments = false))
val bbb = prepareAttachmentPanel()
assertTextFieldWithLabel("$bbb:attachmentNameMask", null, "Attachment Name Mask")
assertComponentWithLabel("$bbb:hasAttachments", CheckBoxX::class.java, false, "W/ or w/o Attachments")
}
@Test
fun withAttachmentFilter_havingAttachmentFilterWithAttachmentName() {
tester.startComponentInPage(newPanel(attachmentName = "foo"))
val bbb = prepareAttachmentPanel()
assertTextFieldWithLabel("$bbb:attachmentNameMask", "foo", "Attachment Name Mask")
assertComponentWithLabel("$bbb:hasAttachments", CheckBoxX::class.java, null, "W/ or w/o Attachments")
}
private fun prepareCodePanel() = prepareTabPanel(tabIndex = 2)
private fun prepareAttachmentPanel() = prepareTabPanel(tabIndex = 5)
private fun prepareTabPanel(tabIndex: Int): String {
val b = "panel:form:tabs"
tester.clickLink("$b:tabs-container:tabs:$tabIndex:link")
return "$b:panel:tab${tabIndex + 1}Form"
}
}
| core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/paper/common/SearchablePaperPanelTest.kt | 3831158679 |
package nl.hannahsten.texifyidea.psi
import com.intellij.openapi.paths.WebReference
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import junit.framework.TestCase
import nl.hannahsten.texifyidea.file.BibtexFileType
import nl.hannahsten.texifyidea.util.firstChildOfType
import org.intellij.lang.annotations.Language
import org.junit.Test
class BibtexEntryImplUtilTest : BasePlatformTestCase() {
private val url = "https://github.com/hannah-sten/TeXiFy-IDEA"
@Language("Bibtex")
private val entryText =
"""@article{texify,
author = {Hannah-Sten},
title = {TeXiFy IDEA},
journal = {GitHub},
year = {2020},
url = {$url},
biburl = {$url}
}"""
private val entryElement by lazy {
PsiDocumentManager.getInstance(myFixture.project)
.getPsiFile(myFixture.editor.document)!!
.firstChildOfType(BibtexEntry::class)!!
}
override fun setUp() {
super.setUp()
myFixture.configureByText(BibtexFileType, entryText)
}
@Test
fun testEntryGetReferences() {
listOf(WebReference(entryElement, url)).map { it.url }.forEach {
UsefulTestCase.assertContainsElements(entryElement.references.map { reference -> (reference as WebReference).url }, it)
}
}
@Test
fun testGetTagContent() {
TestCase.assertEquals("TeXiFy IDEA", entryElement.getTagContent("title"))
}
} | test/nl/hannahsten/texifyidea/psi/BibtexEntryImplUtilTest.kt | 3477864024 |
/*
* Copyright (C) 2016 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.ui.search
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import butterknife.BindView
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.fragment.ToolbarGridFragment
import net.simonvt.cathode.common.widget.ErrorView
import net.simonvt.cathode.common.widget.SearchView
import net.simonvt.cathode.search.SearchHandler.SearchResult
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.sync.scheduler.SearchTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.NavigationListener
import javax.inject.Inject
class SearchFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory,
private val searchScheduler: SearchTaskScheduler
) : ToolbarGridFragment<ViewHolder>(), SearchAdapter.OnResultClickListener {
@BindView(R.id.errorView)
@JvmField
var errorView: ErrorView? = null
private lateinit var viewModel: SearchViewModel
private var searchView: SearchView? = null
private var requestFocus: Boolean = false
private var sortBy: SortBy? = null
private val adapter = SearchAdapter(this)
private var displayErrorView: Boolean = false
private var resetScrollPosition: Boolean = false
private lateinit var navigationListener: NavigationListener
enum class SortBy(val key: String) {
TITLE("title"), RATING("rating"), RELEVANCE("relevance");
override fun toString(): String {
return key
}
companion object {
fun fromValue(value: String): SortBy? {
return values().firstOrNull { it.key == value }
}
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
sortBy = SortBy.fromValue(
Settings.get(requireContext()).getString(Settings.Sort.SEARCH, SortBy.TITLE.key)!!
)
setAdapter(adapter)
setEmptyText(R.string.search_empty)
if (inState == null) {
requestFocus = true
}
viewModel = ViewModelProviders.of(this, viewModelFactory).get(SearchViewModel::class.java)
viewModel.recents.observe(
this,
Observer { recentQueries -> adapter.setRecentQueries(recentQueries) })
viewModel.liveResults.observe(this, resultsObserver)
}
private val resultsObserver = Observer<SearchResult> { (success, results) ->
adapter.setSearching(false)
displayErrorView = !success
updateErrorView()
if (success) {
adapter.setResults(results)
resetScrollPosition = true
updateScrollPosition()
if (view != null) {
updateScrollPosition()
}
} else {
adapter.setResults(null)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
inState: Bundle?
): View? {
return inflater.inflate(R.layout.search_fragment, container, false)
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
searchView = LayoutInflater.from(toolbar!!.context)
.inflate(R.layout.search_view, toolbar, false) as SearchView
toolbar!!.addView(searchView)
searchView!!.setListener(object : SearchView.SearchViewListener {
override fun onTextChanged(newText: String) {
queryChanged(newText)
}
override fun onSubmit(query: String) {
query(query)
searchView!!.clearFocus()
}
})
updateErrorView()
if (requestFocus) {
requestFocus = false
searchView!!.onActionViewExpanded()
}
}
override fun onDestroyView() {
searchView = null
super.onDestroyView()
}
override fun onViewStateRestored(inState: Bundle?) {
super.onViewStateRestored(inState)
updateScrollPosition()
}
private fun updateScrollPosition() {
if (view != null && resetScrollPosition) {
resetScrollPosition = false
recyclerView.scrollToPosition(0)
}
}
private fun updateErrorView() {
if (displayErrorView) {
errorView!!.show()
} else {
errorView!!.hide()
}
}
private fun queryChanged(query: String) {
viewModel.search(query)
}
private fun query(query: String) {
if (!query.isBlank()) {
adapter.setSearching(true)
searchScheduler.insertRecentQuery(query)
}
viewModel.search(query)
}
override fun onShowClicked(showId: Long, title: String?, overview: String?) {
navigationListener.onDisplayShow(showId, title, overview, LibraryType.WATCHED)
if (title != null) {
searchScheduler.insertRecentQuery(title)
}
}
override fun onMovieClicked(movieId: Long, title: String?, overview: String?) {
navigationListener.onDisplayMovie(movieId, title, overview)
if (title != null) {
searchScheduler.insertRecentQuery(title)
}
}
override fun onQueryClicked(query: String) {
searchView?.clearFocus()
searchView?.query = query
adapter.setSearching(true)
query(query)
}
companion object {
const val TAG = "net.simonvt.cathode.ui.search.SearchFragment"
}
}
| cathode/src/main/java/net/simonvt/cathode/ui/search/SearchFragment.kt | 2943619269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.