repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/foundation/NSLog.kt
1
329
package com.yy.codex.foundation import android.util.Log import com.yy.codex.uikit.UIView /** * Created by cuiminghui on 2017/1/12. */ object NSLog { fun log(`object`: Any?) { println("NSLog: " + `object`!!.toString()) } fun warn(`object`: Any?) { Log.w("NSLog", `object`!!.toString()) } }
gpl-3.0
actions-on-google/actions-on-google-java
src/test/kotlin/com/google/actions/api/test/MockRequestBuilderTest.kt
1
1710
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.actions.api.test import junit.framework.TestCase.* import org.testng.annotations.Test class MockRequestBuilderTest { @Test fun testBasicAogRequest() { val aogRequest = MockRequestBuilder .welcome("welcome", false) .build() assertEquals("welcome", aogRequest.intent) assertNotNull(aogRequest.appRequest?.conversation) } @Test fun testBasicDialogflowRequest() { val dialogflowRequest = MockRequestBuilder .welcome("welcome") .build() assertEquals("welcome", dialogflowRequest.intent) assertNotNull(dialogflowRequest.webhookRequest?.originalDetectIntentRequest?.payload) } @Test fun testConfirmationResponse() { var request = MockRequestBuilder .userConfirmation() .build() assertTrue(request.getUserConfirmation()) request = MockRequestBuilder .userConfirmation(false) .build() assertFalse(request.getUserConfirmation()) } }
apache-2.0
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/test/java/com/garpr/android/data/models/EndpointTest.kt
1
2273
package com.garpr.android.data.models import com.garpr.android.test.BaseTest import org.junit.Assert.assertEquals import org.junit.Test class EndpointTest : BaseTest() { @Test fun testGetBasePath() { assertEquals("https://www.garpr.com", Endpoint.GAR_PR.basePath) assertEquals("https://www.notgarpr.com", Endpoint.NOT_GAR_PR.basePath) } @Test fun testGetPlayerWebPath() { assertEquals("https://www.garpr.com/#/norcal/players/588852e7d2994e3bbfa52d6e", Endpoint.GAR_PR.getPlayerWebPath("norcal", "588852e7d2994e3bbfa52d6e")) assertEquals("https://www.notgarpr.com/#/newjersey/players/545c854e8ab65f127805bd6f", Endpoint.NOT_GAR_PR.getPlayerWebPath("newjersey", "545c854e8ab65f127805bd6f")) } @Test fun testGetRankingsWebPath() { assertEquals("https://www.garpr.com/#/norcal/rankings", Endpoint.GAR_PR.getRankingsWebPath("norcal")) assertEquals("https://www.notgarpr.com/#/newjersey/rankings", Endpoint.NOT_GAR_PR.getRankingsWebPath("newjersey")) } @Test fun testGetTournamentWebPath() { assertEquals("https://www.garpr.com/#/norcal/tournaments/58d8c3e8d2994e057e91f7fd", Endpoint.GAR_PR.getTournamentWebPath("norcal", "58d8c3e8d2994e057e91f7fd")) assertEquals("https://www.notgarpr.com/#/newjersey/tournaments/58bdc6e31d41c867e937fc15", Endpoint.NOT_GAR_PR.getTournamentWebPath("newjersey", "58bdc6e31d41c867e937fc15")) } @Test fun testGetTournamentsWebPath() { assertEquals("https://www.garpr.com/#/googlemtv/tournaments", Endpoint.GAR_PR.getTournamentsWebPath("googlemtv")) assertEquals("https://www.notgarpr.com/#/nyc/tournaments", Endpoint.NOT_GAR_PR.getTournamentsWebPath("nyc")) } @Test fun testGetWebPath() { assertEquals("https://www.garpr.com/#/", Endpoint.GAR_PR.getWebPath()) assertEquals("https://www.notgarpr.com/#/", Endpoint.NOT_GAR_PR.getWebPath()) assertEquals("https://www.garpr.com/#/norcal", Endpoint.GAR_PR.getWebPath("norcal")) assertEquals("https://www.notgarpr.com/#/chicago", Endpoint.NOT_GAR_PR.getWebPath("chicago")) } }
unlicense
uber/RIBs
android/config/spotless/copyright.kt
2
606
/* * Copyright (C) $YEAR. Uber Technologies * * 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. */
apache-2.0
Sjtek/sjtekcontrol-core
data/src/main/kotlin/nl/sjtek/control/data/parsers/ResponseHolder.kt
1
888
package nl.sjtek.control.data.parsers import nl.sjtek.control.data.response.* import java.io.Serializable @Suppress("MemberVisibilityCanPrivate") data class ResponseHolder(val map: Map<String, Response> = mapOf(), @Transient val exception: Exception? = null) : Serializable { val audio: Audio = map["audio"] as Audio val base: Base = map["base"] as Base val coffee: Coffee = map["coffee"] as Coffee val lights: Lights = map["lights"] as Lights val music: Music = map["music"] as Music val nightMode: NightMode = map["nightmode"] as NightMode val temperature: Temperature = map["temperature"] as Temperature val tv: TV = map["tv"] as TV @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") internal fun test() { audio!! base!! coffee!! lights!! music!! nightMode!! temperature!! tv!! } }
gpl-3.0
Waverunner/HarvesterDroid
api/src/main/kotlin/com/lewisjmorgan/harvesterdroid/api/repository/GalaxyResourceRepository.kt
1
418
package com.lewisjmorgan.harvesterdroid.api.repository import com.lewisjmorgan.harvesterdroid.api.GalaxyResource import io.reactivex.Flowable import io.reactivex.Single interface GalaxyResourceRepository { fun get(resource: String): Single<GalaxyResource> fun add(resource: GalaxyResource) fun exists(resource: GalaxyResource): Boolean fun remove(resource: String) fun getAll(): Flowable<GalaxyResource> }
gpl-3.0
tutao/tutanota
app-android/app/src/test/java/de/tutao/tutanota/TestUtils.kt
1
277
package de.tutao.tutanota import org.mockito.AdditionalMatchers.aryEq /** * Wrapper around `AdditionalMatchers::aryEq` * aryEq returns null, which causes an error when used on a non-null parameter */ fun arrayEq(array: ByteArray): ByteArray { aryEq(array) return array }
gpl-3.0
squins/ooverkommelig
main/src/commonMain/kotlin/org/ooverkommelig/Constant.kt
1
740
package org.ooverkommelig import org.ooverkommelig.definition.DefinitionDelegate import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty class Constant<out TObject>(private val value: TObject) : DefinitionDelegate<Definition<TObject>>() { operator fun provideDelegate(owner: SubGraphDefinition, property: KProperty<*>): ReadOnlyProperty<SubGraphDefinition, Definition<TObject>> { owner.addDefinitionProperty(property, true) return this } override fun createDefinition(owner: SubGraphDefinition, name: String): Definition<TObject> = ConstantDefinition(value) operator fun getValue(any: Any, property: KProperty<*>): Definition<TObject> { return ConstantDefinition(value) } }
mit
googlecreativelab/digital-wellbeing-experiments-toolkit
notifications/notifications-listener/app/src/main/java/com/digitalwellbeingexperiments/toolkit/notificationlistener/PackageManagerExtensions.kt
1
870
// 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 // // 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.digitalwellbeingexperiments.toolkit.notificationlistener import android.content.pm.PackageManager fun PackageManager.getApplicationLabel(packageName: String): String { val info = getApplicationInfo(packageName, 0) return getApplicationLabel(info).toString() }
apache-2.0
danfma/kodando
kodando-react-dom/src/main/kotlin/kodando/react/dom/HtmlTextAreaElementProps.kt
1
169
package kodando.react.dom import org.w3c.dom.HTMLTextAreaElement external interface HtmlTextAreaElementProps : HtmlElementProps<HTMLTextAreaElement>, InputControlProps
mit
msebire/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GenericAccessorResolveResult.kt
1
1009
// 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.plugins.groovy.lang.resolve import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiSubstitutor import com.intellij.psi.ResolveState import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.buildTopLevelSession import org.jetbrains.plugins.groovy.util.recursionPreventingLazy class GenericAccessorResolveResult( element: PsiMethod, place: PsiElement, state: ResolveState, arguments: Arguments? ) : AccessorResolveResult(element, place, state, arguments) { override fun getSubstitutor(): PsiSubstitutor = inferredSubstitutor ?: run { log.warn("Recursion prevented") PsiSubstitutor.EMPTY } private val inferredSubstitutor by recursionPreventingLazy { buildTopLevelSession(place).inferSubst(this) } }
apache-2.0
danfma/kodando
kodando-mithril/src/main/kotlin/kodando/mithril/elements/HtmlAnchorElementProps.kt
1
162
package kodando.mithril.elements external interface HtmlAnchorElementProps : HtmlElementProps { var href: String? var hrefLang: String? var rel: String? }
mit
square/duktape-android
zipline/src/engineMain/kotlin/app/cash/zipline/internal/CoroutineEventLoop.kt
1
2150
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.internal import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart.UNDISPATCHED import kotlinx.coroutines.Job import kotlinx.coroutines.Runnable import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * We implement scheduled work with raw calls to [CoroutineDispatcher.dispatch] because it prevents * recursion. Otherwise, it's easy to unintentionally have `setTimeout(0, ...)` calls that execute * immediately, eventually exhausting stack space and crashing the process. */ internal class CoroutineEventLoop( private val dispatcher: CoroutineDispatcher, private val scope: CoroutineScope, private val jsPlatform: JsPlatform, ) : EventLoop { private val jobs = mutableMapOf<Int, DelayedJob>() override fun setTimeout(timeoutId: Int, delayMillis: Int) { val job = DelayedJob(timeoutId, delayMillis) jobs[timeoutId] = job dispatcher.dispatch(scope.coroutineContext, job) } override fun clearTimeout(timeoutId: Int) { jobs.remove(timeoutId)?.cancel() } private inner class DelayedJob( val timeoutId: Int, val delayMillis: Int ) : Runnable { var canceled = false var job: Job? = null override fun run() { if (canceled) return this.job = scope.launch(start = UNDISPATCHED) { delay(delayMillis.toLong()) jsPlatform.runJob(timeoutId) jobs.remove(timeoutId) } } fun cancel() { canceled = true job?.cancel() } } }
apache-2.0
vhromada/Catalog-Swing
src/main/kotlin/cz/vhromada/catalog/gui/program/ProgramDataPanel.kt
1
4750
package cz.vhromada.catalog.gui.program import cz.vhromada.catalog.entity.Program import cz.vhromada.catalog.gui.common.AbstractDataPanel import cz.vhromada.catalog.gui.common.WebPageButtonType import javax.swing.GroupLayout import javax.swing.JButton import javax.swing.JLabel /** * A class represents panel with program's data. * * @author Vladimir Hromada */ class ProgramDataPanel(program: Program) : AbstractDataPanel<Program>() { /** * Label for name */ private val nameLabel = JLabel("Name") /** * Label with name */ private val nameData = JLabel() /** * Label for additional data */ private val dataLabel = JLabel("Additional data") /** * Label with additional data */ private val dataData = JLabel() /** * Label for count of media */ private val mediaCountLabel = JLabel("Count of media") /** * Label with count of media */ private val mediaCountData = JLabel() /** * Label for note */ private val noteLabel = JLabel("Note") /** * Label with note */ private val noteData = JLabel() /** * Button for showing program's czech Wikipedia page */ private val wikiCzButton = JButton("Czech Wikipedia") /** * Button for showing program's english Wikipedia page */ private val wikiEnButton = JButton("English Wikipedia") /** * URL to czech Wikipedia page about program */ private var wikiCz: String? = null /** * URL to english Wikipedia page about program */ private var wikiEn: String? = null init { updateData(program) initData(nameLabel, nameData) initData(dataLabel, dataData) initData(mediaCountLabel, mediaCountData) initData(noteLabel, noteData) initButton(wikiCzButton, WebPageButtonType.WIKI_CZ) initButton(wikiEnButton, WebPageButtonType.WIKI_EN) createLayout() } @Suppress("DuplicatedCode") override fun updateComponentData(data: Program) { nameData.text = data.name dataData.text = getAdditionalData(data) mediaCountData.text = data.mediaCount?.toString() noteData.text = data.note wikiCz = data.wikiCz wikiEn = data.wikiEn wikiCzButton.isEnabled = !wikiCz.isNullOrBlank() wikiEnButton.isEnabled = !wikiEn.isNullOrBlank() } override fun getCzWikiUrl(): String { return wikiCz!! } override fun getEnWikiUrl(): String { return wikiEn!! } override fun getCsfdUrl(): String { error { "Getting URL to ČSFD page is not allowed for programs." } } override fun getImdbUrl(): Int { error { "Getting URL to IMDB page is not allowed for programs." } } override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group { return group .addGroup(createHorizontalDataComponents(layout, nameLabel, nameData)) .addGroup(createHorizontalDataComponents(layout, dataLabel, dataData)) .addGroup(createHorizontalDataComponents(layout, mediaCountLabel, mediaCountData)) .addGroup(createHorizontalDataComponents(layout, noteLabel, noteData)) .addGroup(createHorizontalButtons(layout, wikiCzButton, wikiEnButton)) } override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group { return group .addGroup(createVerticalComponents(layout, nameLabel, nameData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, dataLabel, dataData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, mediaCountLabel, mediaCountData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, noteLabel, noteData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalButtons(layout, wikiCzButton, wikiEnButton)) } /** * Returns additional data. * * @param program program * @return additional data */ private fun getAdditionalData(program: Program): String { val result = StringBuilder() if (program.crack!!) { result.append("Crack") } addAdditionalDataToResult(result, program.serialKey!!, "serial key") if (!program.otherData.isNullOrBlank()) { if (result.isNotEmpty()) { result.append(", ") } result.append(program.otherData) } return result.toString() } }
mit
RFonzi/RxAware
rxaware-lib/src/main/java/io/github/rfonzi/rxaware/bus/RxBus.kt
1
573
package io.github.rfonzi.rxaware.bus import com.jakewharton.rxrelay2.BehaviorRelay import io.github.rfonzi.rxaware.bus.events.FlushEvent import io.reactivex.Observable /** * Created by ryan on 8/24/17. */ object RxBus { private val subject: BehaviorRelay<Any> = BehaviorRelay.create() fun post(event: Any) = subject.accept(event) fun <T> toObservable(eventType: Class<T>): Observable<T> = subject.ofType(eventType) fun clear() = post(FlushEvent()) } //val questionBankRelayModule = Kodein.Module { // bind<RxBus>() with singleton { RxBus() } //}
mit
damien5314/HoldTheNarwhal
app/src/main/java/com/ddiehl/android/htn/listings/BaseListingsFragment.kt
1
5827
package com.ddiehl.android.htn.listings import android.os.Bundle import android.view.* import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.ddiehl.android.htn.R import com.ddiehl.android.htn.listings.report.ReportViewRouter import com.ddiehl.android.htn.routing.AppRouter import com.ddiehl.android.htn.view.BaseFragment import com.google.android.material.snackbar.Snackbar import javax.inject.Inject abstract class BaseListingsFragment : BaseFragment(), ListingsView, SwipeRefreshLayout.OnRefreshListener { @Inject internal lateinit var appRouter: AppRouter @Inject internal lateinit var reportViewRouter: ReportViewRouter lateinit var recyclerView: RecyclerView protected lateinit var swipeRefreshLayout: SwipeRefreshLayout protected lateinit var listingsPresenter: BaseListingsPresenter protected abstract val listingsAdapter: ListingsAdapter protected lateinit var callbacks: ListingsView.Callbacks private val onScrollListener: RecyclerView.OnScrollListener get() = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { with(recyclerView.layoutManager as LinearLayoutManager) { handleScroll(childCount, itemCount, findFirstVisibleItemPosition()) } } private fun handleScroll(visible: Int, total: Int, firstVisible: Int) { if (firstVisible == 0) { callbacks.onFirstItemShown() } else if (visible + firstVisible >= total) { callbacks.onLastItemShown() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true setHasOptionsMenu(true) listenForReportViewResults() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): View { return super.onCreateView(inflater, container, state).also { recyclerView = it.findViewById(R.id.recycler_view); instantiateListView() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout) swipeRefreshLayout.setOnRefreshListener(this) } private fun instantiateListView() { with(recyclerView) { layoutManager = LinearLayoutManager(activity) clearOnScrollListeners() addOnScrollListener(onScrollListener) adapter = listingsAdapter } } override fun onStart() { super.onStart() // FIXME Do we need to check nextRequested here? if (!listingsPresenter.hasData()) { listingsPresenter.refreshData() } } override fun onDestroy() { recyclerView.adapter = null // To disable the memory dereferencing functionality just comment these lines listingsPresenter.clearData() super.onDestroy() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_refresh -> { listingsPresenter.refreshData() return true } R.id.action_settings -> { appRouter.showSettings() return true } } return false } protected fun hideTimespanOptionIfUnsupported(menu: Menu, sort: String) { menu.findItem(R.id.action_change_sort).isVisible = true when (sort) { "controversial", "top" -> menu.findItem(R.id.action_change_timespan).isVisible = true "hot", "new", "rising" -> menu.findItem(R.id.action_change_timespan).isVisible = false else -> menu.findItem(R.id.action_change_timespan).isVisible = false } } override fun onContextItemSelected(item: MenuItem): Boolean { return listingsPresenter.onContextItemSelected(item) } override fun notifyDataSetChanged() = listingsAdapter.notifyDataSetChanged() override fun notifyItemChanged(position: Int) = listingsAdapter.notifyItemChanged(position) override fun notifyItemInserted(position: Int) = listingsAdapter.notifyItemInserted(position) override fun notifyItemRemoved(position: Int) = listingsAdapter.notifyItemRemoved(position) override fun notifyItemRangeChanged(position: Int, count: Int) = listingsAdapter.notifyItemRangeChanged(position, count) override fun notifyItemRangeInserted(position: Int, count: Int) = listingsAdapter.notifyItemRangeInserted(position, count) override fun notifyItemRangeRemoved(position: Int, count: Int) = listingsAdapter.notifyItemRangeRemoved(position, count) override fun onRefresh() { swipeRefreshLayout.isRefreshing = false listingsPresenter.refreshData() } private fun listenForReportViewResults() { reportViewRouter.observeReportResults() .subscribe { result -> when (result) { ReportViewRouter.ReportResult.SUCCESS -> showReportSuccessToast() ReportViewRouter.ReportResult.CANCELED -> showReportErrorToast() null -> { } } } } private fun showReportSuccessToast() { Snackbar.make(chromeView, R.string.report_successful, Snackbar.LENGTH_LONG).show() } private fun showReportErrorToast() { Snackbar.make(chromeView, R.string.report_error, Snackbar.LENGTH_LONG).show() } }
apache-2.0
tfelix/worldgen
src/test/kotlin/de/tfelix/bestia/worldgen/SimpleMapGeneratorTest.kt
1
265
package de.tfelix.bestia.worldgen class SimpleMapGeneratorTest { /** * Test is currently disabled until the problem with non termination is solved. */ // @Test fun `general test`() { val generator = SimpleMapGenerator() generator.start() } }
mit
Aidanvii7/Toolbox
redux/src/test/java/com/aidanvii/toolbox/redux/ExampleState.kt
1
249
package com.aidanvii.toolbox.redux data class ExampleState( val fooBar1: Boolean, val fooBar2: Boolean ) { companion object { val DEFAULT = ExampleState( fooBar1 = false, fooBar2 = false ) } }
apache-2.0
tipsy/javalin
javalin/src/main/java/io/javalin/core/util/FileUtil.kt
1
828
/* * Javalin - https://javalin.io * Copyright 2017 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin.core.util import java.io.File import java.io.InputStream import java.nio.file.Files import java.nio.file.StandardCopyOption object FileUtil { @JvmStatic fun streamToFile(inputStream: InputStream, path: String) { val newFile = File(path) newFile.parentFile.mkdirs() // create parent dirs if necessary newFile.createNewFile() // create file if necessary Files.copy(inputStream, newFile.toPath(), StandardCopyOption.REPLACE_EXISTING) } @JvmStatic fun readResource(path: String) = FileUtil::class.java.getResource(path).readText() @JvmStatic fun readFile(path: String) = File(path).readText() }
apache-2.0
envoyproxy/envoy
mobile/library/kotlin/io/envoyproxy/envoymobile/Headers.kt
2
1167
package io.envoyproxy.envoymobile /** * Base class that is used to represent header/trailer data structures. * To instantiate new instances, see `{Request|Response}HeadersBuilder`. */ open class Headers { internal val container: HeadersContainer /** * Internal constructor used by builders. * * @param container: The headers container to set. */ internal constructor(container: HeadersContainer) { this.container = container } /** * Get the value for the provided header name. It's discouraged * to use this dictionary for equality key-based lookups as this * may lead to issues with headers that do not follow expected * casing i.e., "Content-Length" instead of "content-length". * * @param name: Header name for which to get the current value. * * @return The current headers specified for the provided name. */ fun value(name: String): List<String>? { return container.value(name) } /** * Accessor for all underlying headers as a map. * * @return The underlying headers. */ fun caseSensitiveHeaders(): Map<String, List<String>> { return container.caseSensitiveHeaders() } }
apache-2.0
toxxmeister/BLEacon
library/src/main/java/de/troido/bleacon/ble/HandledBleActor.kt
1
624
package de.troido.bleacon.ble import android.os.Handler import de.troido.ekstend.android.threads.postDelayed /** * [BleActor] with [BleActor.start]`(Long)` and [BleActor.pause] implemented through a [Handler]. * * It's advised to implement [BleActor.start] and [BleActor.stop] through this [handler] too. */ abstract class HandledBleActor(protected val handler: Handler = Handler()) : BleActor { override fun start(millis: Long) { start() handler.postDelayed(millis, this::stop) } override fun pause(millis: Long) { stop() handler.postDelayed(millis, this::start) } }
apache-2.0
perseacado/feedback-ui
feedback-ui-web/src/main/java/com/github/perseacado/feedbackui/web/FeedbackEndpointController.kt
1
905
package com.github.perseacado.feedbackui.web import com.github.perseacado.feedbackui.core.FeedbackMessage import com.github.perseacado.feedbackui.core.FeedbackService import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import javax.validation.Valid /** * @author Marco Eigletsberger, 24.06.16. */ @RestController @RequestMapping("**/__feedback/message") open class FeedbackEndpointController @Autowired constructor( val feedbackService: FeedbackService) { @RequestMapping(method = arrayOf(RequestMethod.POST)) fun postFeedback(@Valid @RequestBody feedbackDto: FeedbackMessage) = feedbackService.processFeedback(feedbackDto) }
mit
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/Menu.kt
1
662
package com.boardgamegeek.extensions import android.view.Menu import android.widget.TextView import androidx.annotation.IdRes fun Menu.setActionBarCount(@IdRes id: Int, count: Int, text: String? = null) { setActionBarText(id, if (count <= 0) "" else "%,d".format(count), if (count <= 0) "" else text) } private fun Menu.setActionBarText(@IdRes id: Int, text1: String, text2: String?) { val actionView = findItem(id).actionView ?: return actionView.findViewById<TextView>(android.R.id.text1)?.text = text1 if (!text2.isNullOrBlank()) { actionView.findViewById<TextView>(android.R.id.text2)?.text = text2 } }
gpl-3.0
ratabb/Hishoot2i
imageloader/src/main/java/imageloader/coil/fetch/Checker.kt
1
99
package imageloader.coil.fetch enum class Checker(val dp: Float) { SCREEN(18F), BACKGROUND(24F) }
apache-2.0
ratabb/Hishoot2i
app/src/main/java/org/illegaller/ratabb/hishoot2i/data/pref/ScreenToolPref.kt
1
185
package org.illegaller.ratabb.hishoot2i.data.pref import kotlinx.coroutines.flow.Flow interface ScreenToolPref { var doubleScreenEnable: Boolean val mainFlow: List<Flow<*>> }
apache-2.0
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/timings/DummyTimingsFactory.kt
1
1201
/* * 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.timings import co.aikar.timings.Timing import co.aikar.timings.TimingsFactory import org.lanternpowered.api.audience.Audience import org.lanternpowered.api.plugin.PluginContainer object DummyTimingsFactory : TimingsFactory { override fun of(plugin: PluginContainer, name: String, groupHandler: Timing?): Timing = DummyTiming override fun isTimingsEnabled(): Boolean = false override fun setTimingsEnabled(enabled: Boolean) {} override fun isVerboseTimingsEnabled(): Boolean = false override fun setVerboseTimingsEnabled(enabled: Boolean) {} override fun getHistoryInterval(): Int = 0 override fun setHistoryInterval(interval: Int) {} override fun getHistoryLength(): Int = 0 override fun setHistoryLength(length: Int) {} override fun reset() {} override fun generateReport(channel: Audience) {} }
mit
rusinikita/movies-shmoovies
app/src/main/kotlin/com/nikita/movies_shmoovies/common/utils/ActivityExtentions.kt
1
281
package com.nikita.movies_shmoovies.common.utils import android.app.Activity import android.view.View inline fun <reified T : View> Activity.findView(id: Int): T = findViewById(id) as T inline fun <reified T : View> Activity.findViewOptional(id: Int): T? = findViewById(id) as? T
apache-2.0
FHannes/intellij-community
uast/uast-common/src/org/jetbrains/uast/values/UConstant.kt
8
15405
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.values import com.intellij.psi.PsiEnumConstant import com.intellij.psi.PsiType import org.jetbrains.uast.* interface UConstant : UValue { val value: Any? val source: UExpression? // Used for string concatenation fun asString(): String // Used for logging / debugging purposes override fun toString(): String } abstract class UAbstractConstant : UValueBase(), UConstant { override fun valueEquals(other: UValue) = when (other) { this -> UBooleanConstant.True is UConstant -> UBooleanConstant.False else -> super.valueEquals(other) } override fun equals(other: Any?) = other is UAbstractConstant && value == other.value override fun hashCode() = value?.hashCode() ?: 0 override fun toString() = "$value" override fun asString() = toString() } enum class UNumericType(val prefix: String = "") { BYTE("(byte)"), SHORT("(short)"), INT(), LONG("(long)"), FLOAT("(float)"), DOUBLE(); fun merge(other: UNumericType): UNumericType { if (this == DOUBLE || other == DOUBLE) return DOUBLE if (this == FLOAT || other == FLOAT) return FLOAT if (this == LONG || other == LONG) return LONG return INT } } abstract class UNumericConstant(val type: UNumericType, override val source: ULiteralExpression?) : UAbstractConstant() { override abstract val value: Number override fun toString() = "${type.prefix}$value" override fun asString() = "$value" } private fun PsiType.toNumeric(): UNumericType = when (this) { PsiType.LONG -> UNumericType.LONG PsiType.INT -> UNumericType.INT PsiType.SHORT -> UNumericType.SHORT PsiType.BYTE -> UNumericType.BYTE PsiType.DOUBLE -> UNumericType.DOUBLE PsiType.FLOAT -> UNumericType.FLOAT else -> throw AssertionError("Conversion is impossible for type $canonicalText") } private fun Int.asType(type: UNumericType): Int = when (type) { UNumericType.BYTE -> toByte().toInt() UNumericType.SHORT -> toShort().toInt() else -> this } class UIntConstant( rawValue: Int, type: UNumericType = UNumericType.INT, override val source: ULiteralExpression? = null ) : UNumericConstant(type, source) { init { when (type) { UNumericType.INT, UNumericType.SHORT, UNumericType.BYTE -> {} else -> throw AssertionError("Incorrect UIntConstant type: $type") } } override val value: Int = rawValue.asType(type) constructor(value: Int, type: PsiType): this(value, type.toNumeric()) override fun plus(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value + other.value, type.merge(other.type)) is ULongConstant -> other + this is UFloatConstant -> other + this else -> super.plus(other) } override fun times(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value * other.value, type.merge(other.type)) is ULongConstant -> other * this is UFloatConstant -> other * this else -> super.times(other) } override fun div(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value / other.value, type.merge(other.type)) is ULongConstant -> ULongConstant(value / other.value) is UFloatConstant -> UFloatConstant.create(value / other.value, type.merge(other.type)) else -> super.div(other) } override fun mod(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value % other.value, type.merge(other.type)) is ULongConstant -> ULongConstant(value % other.value) is UFloatConstant -> UFloatConstant.create(value % other.value, type.merge(other.type)) else -> super.mod(other) } override fun unaryMinus() = UIntConstant(-value, type) override fun greater(other: UValue) = when (other) { is UIntConstant -> UBooleanConstant.valueOf(value > other.value) is ULongConstant -> UBooleanConstant.valueOf(value > other.value) is UFloatConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun inc() = UIntConstant(value + 1, type) override fun dec() = UIntConstant(value - 1, type) override fun bitwiseAnd(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value and other.value, type.merge(other.type)) else -> super.bitwiseAnd(other) } override fun bitwiseOr(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value or other.value, type.merge(other.type)) else -> super.bitwiseOr(other) } override fun bitwiseXor(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value xor other.value, type.merge(other.type)) else -> super.bitwiseXor(other) } override fun shl(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value shl other.value, type.merge(other.type)) else -> super.shl(other) } override fun shr(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value shr other.value, type.merge(other.type)) else -> super.shr(other) } override fun ushr(other: UValue) = when (other) { is UIntConstant -> UIntConstant(value ushr other.value, type.merge(other.type)) else -> super.ushr(other) } } class ULongConstant(override val value: Long, source: ULiteralExpression? = null) : UNumericConstant(UNumericType.LONG, source) { override fun plus(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value + other.value) is UIntConstant -> ULongConstant(value + other.value) is UFloatConstant -> other + this else -> super.plus(other) } override fun times(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value * other.value) is UIntConstant -> ULongConstant(value * other.value) is UFloatConstant -> other * this else -> super.times(other) } override fun div(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value / other.value) is UIntConstant -> ULongConstant(value / other.value) is UFloatConstant -> UFloatConstant.create(value / other.value, type.merge(other.type)) else -> super.div(other) } override fun mod(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value % other.value) is UIntConstant -> ULongConstant(value % other.value) is UFloatConstant -> UFloatConstant.create(value % other.value, type.merge(other.type)) else -> super.mod(other) } override fun unaryMinus() = ULongConstant(-value) override fun greater(other: UValue) = when (other) { is ULongConstant -> UBooleanConstant.valueOf(value > other.value) is UIntConstant -> UBooleanConstant.valueOf(value > other.value) is UFloatConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun inc() = ULongConstant(value + 1) override fun dec() = ULongConstant(value - 1) override fun bitwiseAnd(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value and other.value) else -> super.bitwiseAnd(other) } override fun bitwiseOr(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value or other.value) else -> super.bitwiseOr(other) } override fun bitwiseXor(other: UValue) = when (other) { is ULongConstant -> ULongConstant(value xor other.value) else -> super.bitwiseXor(other) } override fun shl(other: UValue) = when (other) { is UIntConstant -> ULongConstant(value shl other.value) else -> super.shl(other) } override fun shr(other: UValue) = when (other) { is UIntConstant -> ULongConstant(value shr other.value) else -> super.shr(other) } override fun ushr(other: UValue) = when (other) { is UIntConstant -> ULongConstant(value ushr other.value) else -> super.ushr(other) } } open class UFloatConstant protected constructor( override val value: Double, type: UNumericType = UNumericType.DOUBLE, source: ULiteralExpression? = null ) : UNumericConstant(type, source) { override fun plus(other: UValue) = when (other) { is ULongConstant -> create(value + other.value, type.merge(other.type)) is UIntConstant -> create(value + other.value, type.merge(other.type)) is UFloatConstant -> create(value + other.value, type.merge(other.type)) else -> super.plus(other) } override fun times(other: UValue) = when (other) { is ULongConstant -> create(value * other.value, type.merge(other.type)) is UIntConstant -> create(value * other.value, type.merge(other.type)) is UFloatConstant -> create(value * other.value, type.merge(other.type)) else -> super.times(other) } override fun div(other: UValue) = when (other) { is ULongConstant -> create(value / other.value, type.merge(other.type)) is UIntConstant -> create(value / other.value, type.merge(other.type)) is UFloatConstant -> create(value / other.value, type.merge(other.type)) else -> super.div(other) } override fun mod(other: UValue) = when (other) { is ULongConstant -> create(value % other.value, type.merge(other.type)) is UIntConstant -> create(value % other.value, type.merge(other.type)) is UFloatConstant -> create(value % other.value, type.merge(other.type)) else -> super.mod(other) } override fun greater(other: UValue) = when (other) { is ULongConstant -> UBooleanConstant.valueOf(value > other.value) is UIntConstant -> UBooleanConstant.valueOf(value > other.value) is UFloatConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun unaryMinus() = create(-value, type) override fun inc() = create(value + 1, type) override fun dec() = create(value - 1, type) companion object { fun create(value: Double, type: UNumericType = UNumericType.DOUBLE, source: ULiteralExpression? = null) = when (type) { UNumericType.DOUBLE, UNumericType.FLOAT -> { if (value.isNaN()) UNaNConstant.valueOf(type) else UFloatConstant(value, type, source) } else -> throw AssertionError("Incorrect UFloatConstant type: $type") } fun create(value: Double, type: PsiType) = create(value, type.toNumeric()) } } sealed class UNaNConstant(type: UNumericType = UNumericType.DOUBLE) : UFloatConstant(kotlin.Double.NaN, type) { object Float : UNaNConstant(UNumericType.FLOAT) object Double : UNaNConstant(UNumericType.DOUBLE) override fun greater(other: UValue) = UBooleanConstant.False override fun less(other: UValue) = UBooleanConstant.False override fun greaterOrEquals(other: UValue) = UBooleanConstant.False override fun lessOrEquals(other: UValue) = UBooleanConstant.False override fun valueEquals(other: UValue) = UBooleanConstant.False companion object { fun valueOf(type: UNumericType) = when (type) { UNumericType.DOUBLE -> Double UNumericType.FLOAT -> Float else -> throw AssertionError("NaN exists only for Float / Double, but not for $type") } } } class UCharConstant(override val value: Char, override val source: ULiteralExpression? = null) : UAbstractConstant() { override fun plus(other: UValue) = when (other) { is UIntConstant -> UCharConstant(value + other.value) is UCharConstant -> UCharConstant(value + other.value.toInt()) else -> super.plus(other) } override fun minus(other: UValue) = when (other) { is UIntConstant -> UCharConstant(value - other.value) is UCharConstant -> UIntConstant(value - other.value) else -> super.plus(other) } override fun greater(other: UValue) = when (other) { is UCharConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun inc() = this + UIntConstant(1) override fun dec() = this - UIntConstant(1) override fun toString() = "\'$value\'" override fun asString() = "$value" } sealed class UBooleanConstant(override val value: Boolean) : UAbstractConstant() { override val source = null object True : UBooleanConstant(true) { override fun not() = False override fun and(other: UValue) = other as? UBooleanConstant ?: super.and(other) override fun or(other: UValue) = True } object False : UBooleanConstant(false) { override fun not() = True override fun and(other: UValue) = False override fun or(other: UValue) = other as? UBooleanConstant ?: super.or(other) } companion object { fun valueOf(value: Boolean) = if (value) True else False } } class UStringConstant(override val value: String, override val source: ULiteralExpression? = null) : UAbstractConstant() { override fun plus(other: UValue) = when (other) { is UConstant -> UStringConstant(value + other.asString()) else -> super.plus(other) } override fun greater(other: UValue) = when (other) { is UStringConstant -> UBooleanConstant.valueOf(value > other.value) else -> super.greater(other) } override fun asString() = value override fun toString() = "\"$value\"" } class UEnumEntryValueConstant(override val value: PsiEnumConstant, override val source: USimpleNameReferenceExpression? = null) : UAbstractConstant() { override fun equals(other: Any?) = other is UEnumEntryValueConstant && value.nameIdentifier.text == other.value.nameIdentifier.text && value.containingClass?.qualifiedName == other.value.containingClass?.qualifiedName override fun hashCode(): Int { var result = 19 result = result * 13 + value.nameIdentifier.text.hashCode() result = result * 13 + (value.containingClass?.qualifiedName?.hashCode() ?: 0) return result } override fun toString() = value.name?.let { "$it (enum entry)" }?: "<unnamed enum entry>" override fun asString() = value.name ?: "" } class UClassConstant(override val value: PsiType, override val source: UClassLiteralExpression? = null) : UAbstractConstant() { override fun toString() = value.name } object UNullConstant : UAbstractConstant() { override val value = null override val source = null }
apache-2.0
lettuce-io/lettuce-core
src/main/kotlin/io/lettuce/core/api/coroutines/RedisHLLCoroutinesCommands.kt
1
2029
/* * Copyright 2020-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi /** * Coroutine executed commands for HyperLogLog (PF* commands). * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 * @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesApi */ @ExperimentalLettuceCoroutinesApi interface RedisHLLCoroutinesCommands<K : Any, V : Any> { /** * Adds the specified elements to the specified HyperLogLog. * * @param key the key. * @param values the values. * @return Long integer-reply specifically: * * 1 if at least 1 HyperLogLog internal register was altered. 0 otherwise. */ suspend fun pfadd(key: K, vararg values: V): Long? /** * Merge N different HyperLogLogs into a single one. * * @param destkey the destination key. * @param sourcekeys the source key. * @return String simple-string-reply The command just returns `OK`. */ suspend fun pfmerge(destkey: K, vararg sourcekeys: K): String? /** * Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s). * * @param keys the keys. * @return Long integer-reply specifically: * * The approximated number of unique elements observed via `PFADD`. */ suspend fun pfcount(vararg keys: K): Long? }
apache-2.0
SuperAwesomeLTD/sa-mobile-sdk-android
app/src/androidTest/java/tv/superawesome/demoapp/util/WaitUtils.kt
1
4493
package tv.superawesome.demoapp.util import android.graphics.Color import android.view.View import android.view.ViewTreeObserver import androidx.test.espresso.* import androidx.test.espresso.Espresso.onView import androidx.test.espresso.matcher.ViewMatchers.isRoot import androidx.test.espresso.util.HumanReadables import androidx.test.espresso.util.TreeIterables import org.hamcrest.CoreMatchers import org.hamcrest.Matcher import org.hamcrest.StringDescription import java.lang.Thread.sleep import java.util.concurrent.TimeoutException private class ViewPropertyChangeCallback( private val matcher: Matcher<View>, private val view: View, ) : IdlingResource, ViewTreeObserver.OnDrawListener { private lateinit var callback: IdlingResource.ResourceCallback private var matched = false override fun getName() = "ViewPropertyChangeCallback" override fun isIdleNow() = matched override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) { this.callback = callback } override fun onDraw() { matched = matcher.matches(view) callback.onTransitionToIdle() } } fun waitUntil(matcher: Matcher<View>): ViewAction = object : ViewAction { override fun getConstraints(): Matcher<View> = CoreMatchers.any(View::class.java) override fun getDescription(): String = StringDescription().let { matcher.describeTo(it) "wait until: $it" } override fun perform(uiController: UiController, view: View) { if (!matcher.matches(view)) { ViewPropertyChangeCallback(matcher, view).run { try { IdlingRegistry.getInstance().register(this) view.viewTreeObserver.addOnDrawListener(this) uiController.loopMainThreadUntilIdle() } finally { view.viewTreeObserver.removeOnDrawListener(this) IdlingRegistry.getInstance().unregister(this) } } } } } fun waitForViewMatcherOneTime(viewMatcher: Matcher<View>): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> = isRoot() override fun getDescription(): String { val matcherDescription = StringDescription() viewMatcher.describeTo(matcherDescription) return "wait for a specific $matcherDescription." } override fun perform(uiController: UiController, rootView: View) { for (child in TreeIterables.breadthFirstViewTraversal(rootView)) { if (viewMatcher.matches(child)) { return } } throw PerformException.Builder() .withCause(TimeoutException()) .withActionDescription(this.description) .withViewDescription(HumanReadables.describe(rootView)) .build() } } } open class ViewTester { fun waitForView( viewMatcher: Matcher<View>, waitMillis: Int = 15000, waitMillisPerTry: Long = 100 ): ViewInteraction { val maxTries = waitMillis / waitMillisPerTry.toInt() var tries = 0 for (i in 0..maxTries) try { tries++ onView(isRoot()).perform(waitForViewMatcherOneTime(viewMatcher)) return onView(viewMatcher) } catch (e: Exception) { if (tries == maxTries) { throw e } sleep(waitMillisPerTry) } throw Exception("Could not find view for $viewMatcher") } fun waitForColorInCenter( color: Color, waitMillis: Int = 15000, waitMillisPerTry: Long = 500 ) { val maxTries = waitMillis / waitMillisPerTry.toInt() var tries = 0 var lastColor:Color? = null for (i in 0..maxTries) try { tries++ lastColor = ScreenshotUtil.captureColorInCenter() if (TestColors.checkApproximatelyEqual(color, lastColor)) { return } sleep(waitMillisPerTry) } catch (e: Exception) { if (tries == maxTries) { throw e } sleep(waitMillisPerTry) } throw Exception("Could not find color $color but last color was $lastColor") } }
lgpl-3.0
misaochan/apps-android-commons
app/src/main/java/fr/free/nrw/commons/nearby/fragments/PlaceAdapter.kt
8
996
package fr.free.nrw.commons.nearby.fragments import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao import fr.free.nrw.commons.nearby.Place import fr.free.nrw.commons.nearby.placeAdapterDelegate import fr.free.nrw.commons.upload.categories.BaseDelegateAdapter class PlaceAdapter( bookmarkLocationsDao: BookmarkLocationsDao, onPlaceClicked: ((Place) -> Unit)? = null, onBookmarkClicked: (Place, Boolean) -> Unit, commonPlaceClickActions: CommonPlaceClickActions ) : BaseDelegateAdapter<Place>( placeAdapterDelegate( bookmarkLocationsDao, onPlaceClicked, commonPlaceClickActions.onCameraClicked(), commonPlaceClickActions.onGalleryClicked(), onBookmarkClicked, commonPlaceClickActions.onOverflowClicked(), commonPlaceClickActions.onDirectionsClicked() ), areItemsTheSame = {oldItem, newItem -> oldItem.wikiDataEntityId == newItem.wikiDataEntityId } )
apache-2.0
gumil/basamto
app/src/main/kotlin/io/github/gumil/basamto/reddit/subreddit/SubredditKey.kt
1
1615
/* * The MIT License (MIT) * * Copyright 2017 Miguel Panelo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.gumil.basamto.reddit.subreddit import android.annotation.SuppressLint import io.github.gumil.basamto.common.BaseFragment import io.github.gumil.basamto.navigation.BaseKey import kotlinx.android.parcel.Parcelize @SuppressLint("ParcelCreator") @Parcelize internal data class SubredditKey( val submissions: List<SubmissionItem> = emptyList() ) : BaseKey() { override fun createFragment(): BaseFragment = SubredditFragment.newInstance(this) }
mit
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/data/dao/DatabaseMigrationHelper.kt
1
3103
package jp.kentan.studentportalplus.data.dao import android.database.sqlite.SQLiteDatabase import androidx.core.database.getStringOrNull import jp.kentan.studentportalplus.data.component.ClassWeek import jp.kentan.studentportalplus.util.Murmur3 import org.jetbrains.anko.db.dropTable import org.jetbrains.anko.db.insert import org.jetbrains.anko.db.select import org.jetbrains.anko.db.transaction import kotlin.math.max class DatabaseMigrationHelper { companion object { fun upgradeVersion3From2(db: SQLiteDatabase, createTablesIfNotExist: (SQLiteDatabase) -> Unit) { db.transaction { db.execSQL("ALTER TABLE my_class RENAME TO tmp_my_class") db.dropTable("news", true) db.dropTable("lecture_info", true) db.dropTable("lecture_cancel", true) db.dropTable("my_class", true) db.execSQL("DELETE FROM sqlite_sequence") createTablesIfNotExist(db) db.select("tmp_my_class").exec { while (moveToNext()) { val week: ClassWeek = getLong(1).let { return@let ClassWeek.valueOf(it.toInt() + 1) } val period = getLong(2).let { if (it > 0) it else 0 } val scheduleCode = getLong(8).let { code -> if (code < 0L) "" else code.toString() } val credit = max(getLong(7), 0) val category = getStringOrNull(6) ?: "" val subject = getString(3) val isUser = getLong(10) == 1L val instructor = getStringOrNull(4)?.let { return@let if (isUser) it else it.replace(' ', ' ') } ?: "" val location = getStringOrNull(5)?.let { val trim = it.trim() return@let if (trim.isBlank()) null else trim } val hash = Murmur3.hash64("$week$period$scheduleCode$credit$category$subject$instructor$isUser") db.insert("my_class", "_id" to null, "hash" to hash, "week" to week.code, "period" to period, "schedule_code" to scheduleCode, "credit" to credit, "category" to category, "subject" to subject, "instructor" to instructor, "user" to isUser.toLong(), "color" to getLong(9), "location" to location) } } db.dropTable("tmp_my_class") } } private fun Boolean.toLong() = if (this) 1L else 0L } }
gpl-3.0
nhaarman/mockito-kotlin
mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/Stubber.kt
1
2108
/* * The MIT License * * Copyright (c) 2018 Niek Haarman * Copyright (c) 2007 Mockito contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nhaarman.mockitokotlin2 import org.mockito.Mockito import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Stubber import kotlin.reflect.KClass fun <T> doAnswer(answer: (InvocationOnMock) -> T?): Stubber { return Mockito.doAnswer { answer(it) }!! } fun doCallRealMethod(): Stubber { return Mockito.doCallRealMethod()!! } fun doNothing(): Stubber { return Mockito.doNothing()!! } fun doReturn(value: Any?): Stubber { return Mockito.doReturn(value)!! } fun doReturn(toBeReturned: Any?, vararg toBeReturnedNext: Any?): Stubber { return Mockito.doReturn( toBeReturned, *toBeReturnedNext )!! } fun doThrow(toBeThrown: KClass<out Throwable>): Stubber { return Mockito.doThrow(toBeThrown.java)!! } fun doThrow(vararg toBeThrown: Throwable): Stubber { return Mockito.doThrow(*toBeThrown)!! } fun <T> Stubber.whenever(mock: T) = `when`(mock)
mit
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/bqg5200.kt
1
2584
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern /** * Created by AoEiuV020 on 2018.06.06-18:51:02. */ class Bqg5200 : DslJsoupNovelContext() {init { // 已经废了,域名都丢了, hide = true site { name = "笔趣阁5200" baseUrl = "https://www.biquge5200.com" logo = "https://www.biquge5200.com/skin/images/logo.png" } search { get { // https://www.bqg5200.com/modules/article/search.php?searchtype=articlename&searchkey=%B6%BC%CA%D0&page=1 charset = "GBK" url = "/modules/article/search.php" data { "searchtype" to "articlename" "searchkey" to it // 加上&page=1可以避开搜索时间间隔的限制, // 也可以通过不加载cookies避开搜索时间间隔的限制, "page" to "1" } } document { single("^/book/") { name("#bookinfo > div.bookright > div.booktitle > h1") author("#author", block = pickString("作\\s*者:(\\S+)")) } items("#conn > table > tbody > tr:not(:nth-child(1))") { name("> td:nth-child(1) > a") author("> td:nth-child(3)") } } } // https://www.bqg5200.com/book/2889/ bookIdRegex = "/(book|xiaoshuo/\\d+)/(\\d+)" bookIdIndex = 1 detailPageTemplate = "/book/%s/" detail { document { novel { name("#bookinfo > div.bookright > div.booktitle > h1") author("#author", block = pickString("作\\s*者:(\\S+)")) } image("#bookimg > img") update("#bookinfo > div.bookright > div.new > span.new_t", format = "最后更新:yyyy-MM-dd") introduction("#bookintro > p", block = ownLinesString()) } } // https://www.bqg5200.com/xiaoshuo/2/2889/ chapterDivision = 1000 chaptersPageTemplate = "/xiaoshuo/%d/%s/" chapters { document { items("#readerlist > ul > li > a") lastUpdate("#smallcons > span:nth-child(4)", format = "yyyy-MM-dd HH:mm") } } // https://www.bqg5200.com/xiaoshuo/3/3590/11768349.html bookIdWithChapterIdRegex = firstThreeIntPattern contentPageTemplate = "/xiaoshuo/%s.html" content { document { items("#content", block = ownLinesSplitWhitespace()) } } } }
gpl-3.0
Light-Team/ModPE-IDE-Source
editorkit/src/main/kotlin/com/brackeys/ui/editorkit/internal/ScrollableEditText.kt
1
4628
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.editorkit.internal import android.annotation.SuppressLint import android.content.Context import android.text.InputType import android.util.AttributeSet import android.view.MotionEvent import android.view.VelocityTracker import android.view.ViewConfiguration import android.view.inputmethod.EditorInfo import android.widget.Scroller import com.brackeys.ui.editorkit.R import kotlin.math.abs abstract class ScrollableEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.autoCompleteTextViewStyle ) : ConfigurableEditText(context, attrs, defStyleAttr) { private val textScroller = Scroller(context) private val scrollListeners = mutableListOf<OnScrollChangedListener>() private val maximumVelocity = ViewConfiguration.get(context).scaledMaximumFlingVelocity * 100f private var velocityTracker: VelocityTracker? = null override fun configure() { imeOptions = if (editorConfig.softKeyboard) { EditorInfo.IME_ACTION_UNSPECIFIED } else { EditorInfo.IME_FLAG_NO_EXTRACT_UI } inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS textSize = editorConfig.fontSize typeface = editorConfig.fontType setHorizontallyScrolling(!editorConfig.wordWrap) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) for (listener in scrollListeners) { listener.onScrollChanged(scrollX, scrollY, scrollX, scrollY) } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { abortFling() velocityTracker?.clear() if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain() } } MotionEvent.ACTION_UP -> { velocityTracker?.computeCurrentVelocity(1000, maximumVelocity) val velocityX = if (!editorConfig.wordWrap) { velocityTracker?.xVelocity?.toInt() ?: 0 } else 0 val velocityY = velocityTracker?.yVelocity?.toInt() ?: 0 if (abs(velocityY) < 0 || abs(velocityX) < 0) { velocityTracker?.recycle() velocityTracker = null } if (layout != null) { textScroller.fling( scrollX, scrollY, -velocityX, -velocityY, 0, layout.width - width + paddingStart + paddingEnd, 0, layout.height - height + paddingTop + paddingBottom ) } } MotionEvent.ACTION_MOVE -> { velocityTracker?.addMovement(event) } } return super.onTouchEvent(event) } override fun onScrollChanged(horiz: Int, vert: Int, oldHoriz: Int, oldVert: Int) { super.onScrollChanged(horiz, vert, oldHoriz, oldVert) for (listener in scrollListeners) { listener.onScrollChanged(horiz, vert, oldHoriz, oldVert) } } override fun computeScroll() { if (!isInEditMode) { if (textScroller.computeScrollOffset()) { scrollTo(textScroller.currX, textScroller.currY) postInvalidate() } } } fun addOnScrollChangedListener(listener: OnScrollChangedListener) { scrollListeners.add(listener) } fun abortFling() { if (!textScroller.isFinished) { textScroller.abortAnimation() } } interface OnScrollChangedListener { fun onScrollChanged(x: Int, y: Int, oldX: Int, oldY: Int) } }
apache-2.0
robertwb/incubator-beam
learning/katas/kotlin/Core Transforms/Combine/CombineFn/test/org/apache/beam/learning/katas/coretransforms/combine/combinefn/TaskTest.kt
9
1550
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.learning.katas.coretransforms.combine.combinefn import org.apache.beam.learning.katas.coretransforms.combine.combinefn.Task.applyTransform import org.apache.beam.sdk.testing.PAssert import org.apache.beam.sdk.testing.TestPipeline import org.apache.beam.sdk.transforms.Create import org.junit.Rule import org.junit.Test class TaskTest { @get:Rule @Transient val testPipeline: TestPipeline = TestPipeline.create() @Test fun core_transforms_combine_combinefn() { val values = Create.of(10, 20, 50, 70, 90) val numbers = testPipeline.apply(values) val results = applyTransform(numbers) PAssert.that(results).containsInAnyOrder(48.0) testPipeline.run().waitUntilFinish() } }
apache-2.0
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/settings/SettingsFragment.kt
1
2741
/* 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/. */ @file:Suppress("ForbiddenComment") package org.mozilla.focus.settings import android.content.SharedPreferences import android.os.Bundle import org.mozilla.focus.R import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.AppConstants class SettingsFragment : BaseSettingsFragment(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreatePreferences(bundle: Bundle?, s: String?) { addPreferencesFromResource(R.xml.settings) if (!AppConstants.isGeckoBuild && !AppConstants.isDevBuild) { preferenceScreen.removePreference(findPreference(getString(R.string.pref_key_advanced_screen))) } } override fun onResume() { super.onResume() preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) // Update title and icons when returning to fragments. val updater = activity as BaseSettingsFragment.ActionBarUpdater? updater!!.updateTitle(R.string.menu_settings) updater.updateIcon(R.drawable.ic_back) } override fun onPause() { preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onPause() } override fun onPreferenceTreeClick(preference: androidx.preference.Preference): Boolean { val resources = resources when { preference.key == resources.getString(R.string .pref_key_general_screen) -> navigateToFragment(GeneralSettingsFragment()) preference.key == resources.getString(R.string .pref_key_privacy_security_screen) -> navigateToFragment(PrivacySecuritySettingsFragment()) preference.key == resources.getString(R.string .pref_key_search_screen) -> navigateToFragment(SearchSettingsFragment()) preference.key == resources.getString(R.string .pref_key_advanced_screen) -> navigateToFragment(AdvancedSettingsFragment()) preference.key == resources.getString(R.string .pref_key_mozilla_screen) -> navigateToFragment(MozillaSettingsFragment()) } return super.onPreferenceTreeClick(preference) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { TelemetryWrapper.settingsEvent(key, sharedPreferences.all[key].toString()) } companion object { fun newInstance(): SettingsFragment { return SettingsFragment() } } }
mpl-2.0
ExMCL/ExMCL
ExMCL API/src/main/kotlin/com/n9mtq4/exmcl/api/hooks/events/PreDefinedSwingHookEvent.kt
1
1703
/* * MIT License * * Copyright (c) 2016 Will (n9Mtq4) Bresnahan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.n9mtq4.exmcl.api.hooks.events import com.n9mtq4.logwindow.BaseConsole import com.n9mtq4.logwindow.events.DefaultGenericEvent /** * Created by will on 2/16/16 at 5:57 PM. * * @author Will "n9Mtq4" Bresnahan */ @Suppress("unused", "UNUSED_PARAMETER") class PreDefinedSwingHookEvent(val component: Any, val type: PreDefinedSwingComponent, initiatingBaseConsole: BaseConsole) : DefaultGenericEvent(initiatingBaseConsole) { override fun toString() = "${this.javaClass.name} carrying type: ${type.name} with value ${component.toString()}" }
mit
arturbosch/detekt
detekt-rules-naming/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NonBooleanPropertyPrefixedWithIs.kt
1
3106
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution import io.gitlab.arturbosch.detekt.rules.fqNameOrNull import io.gitlab.arturbosch.detekt.rules.identifierName import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.typeBinding.createTypeBindingForReturnType /** * Reports when property with 'is' prefix doesn't have a boolean type. * Please check the [chapter 8.3.2 at Java Language Specification](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.2) * * <noncompliant> * val isEnabled: Int = 500 * </noncompliant> * * <compliant> * val isEnabled: Boolean = false * </compliant> */ @RequiresTypeResolution class NonBooleanPropertyPrefixedWithIs(config: Config = Config.empty) : Rule(config) { private val kotlinBooleanTypeName = "kotlin.Boolean" private val javaBooleanTypeName = "java.lang.Boolean" override val issue = Issue( javaClass.simpleName, Severity.Warning, "Only boolean property names can start with 'is' prefix.", debt = Debt.FIVE_MINS ) override fun visitParameter(parameter: KtParameter) { super.visitParameter(parameter) if (parameter.hasValOrVar()) { validateDeclaration(parameter) } } override fun visitProperty(property: KtProperty) { super.visitProperty(property) validateDeclaration(property) } private fun validateDeclaration(declaration: KtCallableDeclaration) { if (bindingContext == BindingContext.EMPTY) { return } val name = declaration.identifierName() if (name.startsWith("is") && name.length > 2 && !name[2].isLowerCase()) { val typeName = getTypeName(declaration) if (typeName != null && typeName != kotlinBooleanTypeName && typeName != javaBooleanTypeName) { report( reportCodeSmell(declaration, name, typeName) ) } } } private fun reportCodeSmell( declaration: KtCallableDeclaration, name: String, typeName: String ): CodeSmell { return CodeSmell( issue, Entity.from(declaration), message = "Non-boolean properties shouldn't start with 'is' prefix. Actual type of $name: $typeName" ) } private fun getTypeName(parameter: KtCallableDeclaration): String? { return parameter.createTypeBindingForReturnType(bindingContext) ?.type ?.fqNameOrNull() ?.asString() } }
apache-2.0
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/AccountGroupSelection.kt
1
572
package net.nemerosa.ontrack.model.security; import net.nemerosa.ontrack.model.support.Selectable /** * Defines the selection of an [AccountGroup]. */ class AccountGroupSelection( private val id: Int, private val name: String, private val isSelected: Boolean ) : Selectable { constructor(group: AccountGroup, isSelected: Boolean) : this( group.id(), group.name, isSelected ) override fun getId(): String = id.toString() override fun isSelected(): Boolean = isSelected override fun getName(): String = name }
mit
lambdasoup/watchlater
tea/src/main/java/com/lambdasoup/tea/Util.kt
1
1011
/* * Copyright (c) 2015 - 2021 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.tea internal fun prettyName(o: Any?): String { return o.toString().split('$').last().split('@').first() } operator fun <Model, Msg> Model.times(cmd: Cmd<Msg>) = Pair(this, cmd)
gpl-3.0
DemonWav/IntelliJBukkitSupport
src/test/kotlin/nbt/NbtParseTest.kt
1
4165
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt import com.demonwav.mcdev.framework.findLibraryPath import com.demonwav.mcdev.nbt.tags.NbtTypeId import com.demonwav.mcdev.nbt.tags.RootCompound import com.demonwav.mcdev.nbt.tags.TagByte import com.demonwav.mcdev.nbt.tags.TagByteArray import com.demonwav.mcdev.nbt.tags.TagCompound import com.demonwav.mcdev.nbt.tags.TagDouble import com.demonwav.mcdev.nbt.tags.TagFloat import com.demonwav.mcdev.nbt.tags.TagInt import com.demonwav.mcdev.nbt.tags.TagIntArray import com.demonwav.mcdev.nbt.tags.TagList import com.demonwav.mcdev.nbt.tags.TagLong import com.demonwav.mcdev.nbt.tags.TagLongArray import com.demonwav.mcdev.nbt.tags.TagShort import com.demonwav.mcdev.nbt.tags.TagString import com.intellij.util.io.inputStream import java.nio.file.Path import java.nio.file.Paths import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test @DisplayName("NBT Parse Tests") class NbtParseTest { private lateinit var nbtFile: Path @BeforeEach fun setup() { nbtFile = Paths.get(findLibraryPath("all-types-nbt")) } @Test @DisplayName("NBT Parse Test") fun parseTest() { val (compound, compressed) = Nbt.buildTagTree(nbtFile.inputStream(), 1000L) Assertions.assertTrue(compressed) Assertions.assertEquals(expected, compound) } @Test @DisplayName("NBT Parse Timeout Test") fun slowParseTest() { Assertions.assertThrows(MalformedNbtFileException::class.java) { Nbt.buildTagTree(nbtFile.inputStream(), -1L) } } private val expected: RootCompound = RootCompound( "root", mapOf( "byte" to TagByte(1), "short" to TagShort(127), "int" to TagInt(127), "long" to TagLong(127), "float" to TagFloat(127F), "double" to TagDouble(127.0), "byteArray" to TagByteArray(byteArrayOf(1)), "intArray" to TagIntArray(intArrayOf(127)), "longArray" to TagLongArray(longArrayOf(127)), "byteList" to TagList(NbtTypeId.BYTE, listOf(TagByte(1))), "shortList" to TagList(NbtTypeId.SHORT, listOf(TagShort(127))), "intList" to TagList(NbtTypeId.INT, listOf(TagInt(127))), "longList" to TagList(NbtTypeId.LONG, listOf(TagLong(127))), "floatList" to TagList(NbtTypeId.FLOAT, listOf(TagFloat(127F))), "doubleList" to TagList(NbtTypeId.DOUBLE, listOf(TagDouble(127.0))), "string" to TagString("this is a string"), "compound1" to TagCompound( mapOf( "compound2" to TagCompound( mapOf( "compound3" to TagCompound( mapOf( "list" to TagList( NbtTypeId.COMPOUND, listOf( TagCompound( mapOf( "key" to TagString("value") ) ), TagCompound( mapOf( "key" to TagString("value") ) ) ) ) ) ) ) ) ) ) ) ) }
mit
drakeet/MultiType
library/src/main/kotlin/com/drakeet/multitype/Types.kt
1
1866
/* * Copyright (c) 2016-present. Drakeet Xu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.drakeet.multitype /** * An ordered collection to hold the types, delegates and linkers. * * @author Drakeet Xu */ interface Types { /** * Returns the size of the [Types]. */ val size: Int fun <T> register(type: Type<T>) /** * Unregister all types indexed by the specified class. * * @param clazz the main class of a [Type] * @return true if any types are unregistered from this [Types] */ fun unregister(clazz: Class<*>): Boolean /** * Gets the type at the specified index. * * @param index the type index * @return the [Type] at the specified index * @throws IndexOutOfBoundsException if the index is out of range */ fun <T> getType(index: Int): Type<T> /** * For getting index of the type class. If the subclass is already registered, * the registered mapping is used. If the subclass is not registered, then look * for its parent class if is registered, if the parent class is registered, * the subclass is regarded as the parent class. * * @param clazz the type class. * @return The index of the first occurrence of the specified class in this [Types], * or -1 if this [Types] does not contain the class. */ fun firstIndexOf(clazz: Class<*>): Int }
apache-2.0
mockk/mockk
modules/mockk/src/jvmTest/kotlin/io/mockk/junit5/MockKExtensionAfterAllTestTest.kt
1
2198
package io.mockk.junit5 import io.mockk.isMockKMock import io.mockk.junit5.MockKExtension.Companion.KEEP_MOCKS_PROPERTY import io.mockk.mockkObject import io.mockk.unmockkObject import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.AfterAllCallback import org.junit.jupiter.api.extension.BeforeAllCallback import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.ExtensionContext import kotlin.test.assertFalse import kotlin.test.assertTrue abstract class MockKExtensionAfterAllTestTest { @Test open fun prepareAfterAllUnmockTest() { mockkObject(TestMock) assertTrue(isMockKMock(TestMock, objectMock = true)) } @ExtendWith(CheckIsNotMock::class, MockKExtension::class) class AfterAllClearMocks : MockKExtensionAfterAllTestTest() @MockKExtension.KeepMocks @ExtendWith(CheckIsStillMock::class, MockKExtension::class) class AnnotatedClassAfterAllKeepMocks : MockKExtensionAfterAllTestTest() @ExtendWith(CheckIsStillMock::class, MockKExtension::class) class AnnotatedMethodAfterAllKeepMocks : MockKExtensionAfterAllTestTest() { @MockKExtension.KeepMocks override fun prepareAfterAllUnmockTest() = super.prepareAfterAllUnmockTest() } @ExtendWith(CheckIsStillMock::class, PropertyExtension::class, MockKExtension::class) class PropertyAfterAllKeepMocks : MockKExtensionAfterAllTestTest() object TestMock class CheckIsNotMock : AfterAllCallback { override fun afterAll(context: ExtensionContext) { assertFalse(isMockKMock(TestMock, objectMock = true)) } } class CheckIsStillMock : AfterAllCallback { override fun afterAll(context: ExtensionContext) { assertTrue(isMockKMock(TestMock, objectMock = true)) unmockkObject(TestMock) } } class PropertyExtension : BeforeAllCallback, AfterAllCallback { override fun beforeAll(context: ExtensionContext?) { System.setProperty(KEEP_MOCKS_PROPERTY, "true") } override fun afterAll(context: ExtensionContext) { System.clearProperty(KEEP_MOCKS_PROPERTY) } } }
apache-2.0
hewking/HUILibrary
app/src/main/java/com/hewking/demo/TinderStackLayoutFragment.kt
1
2620
package com.hewking.demo import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.Toast import com.hewking.custom.R import com.hewking.custom.tinderstack.TinderStackLayout import com.hewking.custom.util.dp2px import com.hewking.custom.util.load import kotlinx.android.synthetic.main.fragment_tinder.* /** * 类的描述: * 创建人员:hewking * 创建时间:2018/12/9 * 修改人员:hewking * 修改时间:2018/12/9 * 修改备注: * Version: 1.0.0 */ class TinderStackLayoutFragment : androidx.fragment.app.Fragment(){ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_tinder,container,false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) tinderStack.adapter = TinderCardAdapter().apply { } tinderStack.setChooseListener { if (it == 1) { Toast.makeText(activity,"right swipe select",Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity,"left swipe select",Toast.LENGTH_SHORT).show() } } } inner class TinderCardAdapter : TinderStackLayout.BaseCardAdapter{ val datas = mutableListOf<String>("https://tuimeizi.cn/random?w=665&h=656" ,"https://tuimeizi.cn/random?w=665&h=656" ,"https://tuimeizi.cn/random?w=667&h=656" ,"https://tuimeizi.cn/random?w=665&h=656" ,"https://tuimeizi.cn/random?w=668&h=656" ,"https://tuimeizi.cn/random?w=665&h=656" ,"https://tuimeizi.cn/random?w=665&h=659" ,"https://tuimeizi.cn/random?w=665&h=653" ,"https://tuimeizi.cn/random?w=665&h=656" ,"https://tuimeizi.cn/random?w=665&h=653") private var index = 0 override fun getItemCount(): Int { return datas.size } override fun getView(): View? { if (index > datas.size - 1) { return null } val img = ImageView(activity) img.scaleType = ImageView.ScaleType.CENTER_CROP img.layoutParams = ViewGroup.LayoutParams(dp2px(350f),dp2px(350f)) img.load(datas[index]) index ++ return img } } }
mit
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/at/psi/mixins/AtEntryMixin.kt
1
1364
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at.psi.mixins import com.demonwav.mcdev.platform.mcp.at.AtElementFactory import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtAsterisk import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtClassName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFieldName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFunction import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtKeyword import com.demonwav.mcdev.platform.mcp.at.psi.AtElement interface AtEntryMixin : AtElement { val asterisk: AtAsterisk? val className: AtClassName val fieldName: AtFieldName? val function: AtFunction? val keyword: AtKeyword fun setEntry(entry: String) fun setKeyword(keyword: AtElementFactory.Keyword) fun setClassName(className: String) fun setFieldName(fieldName: String) fun setFunction(function: String) fun setAsterisk() fun replaceMember(element: AtElement) { // One of these must be true when { fieldName != null -> fieldName!!.replace(element) function != null -> function!!.replace(element) asterisk != null -> asterisk!!.replace(element) else -> addAfter(className, element) } } }
mit
ohmae/mmupnp
mmupnp/src/test/java/net/mm2d/upnp/internal/util/IoUtilsTest.kt
1
3664
/* * Copyright (c) 2016 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.util import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.Closeable import java.io.IOException import java.net.DatagramSocket import java.net.ServerSocket import java.net.Socket import java.nio.channels.Selector @Suppress("NonAsciiCharacters", "TestFunctionName") @RunWith(JUnit4::class) class IoUtilsTest { @Test fun `closeQuietly Closeable closeがコールされる`() { val closeable = mockk<Closeable>(relaxed = true) closeable.closeQuietly() verify(exactly = 1) { closeable.close() } } @Test fun `closeQuietly Closeable nullを渡してもExceptionが発生しない`() { val closeable: Closeable? = null closeable.closeQuietly() } @Test fun `closeQuietly Closeable closeでIOExceptionが発生しても外に伝搬しない`() { val closeable = mockk<Closeable>(relaxed = true) every { closeable.close() }.throws(IOException()) closeable.closeQuietly() } @Test fun `closeQuietly Socket closeがコールされる`() { val socket = mockk<Socket>(relaxed = true) socket.closeQuietly() verify(exactly = 1) { socket.close() } } @Test fun `closeQuietly Socket nullを渡してもExceptionが発生しない`() { val socket: Socket? = null socket.closeQuietly() } @Test fun `closeQuietly Socket closeでIOExceptionが発生しても外に伝搬しない`() { val socket = mockk<Socket>(relaxed = true) every { socket.close() }.throws(IOException()) socket.closeQuietly() } @Test fun `closeQuietly DatagramSocket closeがコールされる`() { val datagramSocket = mockk<DatagramSocket>(relaxed = true) datagramSocket.closeQuietly() verify(exactly = 1) { datagramSocket.close() } } @Test fun `closeQuietly DatagramSocket nullを渡してもExceptionが発生しない`() { val datagramSocket: DatagramSocket? = null datagramSocket.closeQuietly() } @Test fun `closeQuietly ServerSocket closeがコールされる`() { val serverSocket = mockk<ServerSocket>(relaxed = true) serverSocket.closeQuietly() verify(exactly = 1) { serverSocket.close() } } @Test fun `closeQuietly ServerSocket nullを渡してもExceptionが発生しない`() { val serverSocket: ServerSocket? = null serverSocket.closeQuietly() } @Test fun `closeQuietly ServerSocket closeでIOExceptionが発生しても外に伝搬しない`() { val serverSocket = mockk<ServerSocket>(relaxed = true) every { serverSocket.close() }.throws(IOException()) serverSocket.closeQuietly() } @Test fun `closeQuietly Selector closeがコールされる`() { val selector = mockk<Selector>(relaxed = true) selector.closeQuietly() verify(exactly = 1) { selector.close() } } @Test fun `closeQuietly Selector nullを渡してもExceptionが発生しない`() { val selector: Selector? = null selector.closeQuietly() } @Test fun `closeQuietly Selector closeでIOExceptionが発生しても外に伝搬しない`() { val selector = mockk<Selector>(relaxed = true) every { selector.close() }.throws(IOException()) selector.closeQuietly() } }
mit
dewarder/Android-Kotlin-Commons
akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/TestActivity.kt
1
2213
package com.dewarder.akommons.binding import android.app.Dialog import android.app.Fragment import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.FrameLayout import com.dewarder.akommons.binding.common.R import android.support.v4.app.Fragment as SupportFragment open class TestActivity : AppCompatActivity() { private lateinit var view: View private lateinit var fragment: Fragment private lateinit var supportFragment: SupportFragment private lateinit var dialog: Dialog private lateinit var contextProvider: ContextProvider override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val container = FrameLayout(this).apply { id = R.id.action_container } setContentView(container) initView()?.let { view = it container.addView(view) } initFragment()?.let { fragment = it fragmentManager.beginTransaction() .replace(R.id.action_container, fragment) .commit() } initSupportFragment()?.let { supportFragment = it supportFragmentManager.beginTransaction() .replace(R.id.action_container, supportFragment) .commit() } initDialog()?.let { dialog = it dialog.show() } initContextProvider()?.let { contextProvider = it } } protected open fun initView(): View? = null protected open fun initFragment(): Fragment? = null protected open fun initSupportFragment(): SupportFragment? = null protected open fun initDialog(): Dialog? = null protected open fun initContextProvider(): ContextProvider? = null fun <T> getView(): T { return view as T } fun <T> getFragment(): T { return fragment as T } fun <T> getSupportFragment(): T { return supportFragment as T } fun <T> getDialog(): T { return dialog as T } fun <T> getContextProvider(): T { return contextProvider as T } }
apache-2.0
androhi/AndroidDrawableViewer
src/main/kotlin/com/androhi/androiddrawableviewer/form/ImageListCellRenderer.kt
1
1151
package com.androhi.androiddrawableviewer.form import com.intellij.ui.JBColor import java.awt.Component import javax.swing.* class ImageListCellRenderer : ListCellRenderer<Any> { override fun getListCellRendererComponent(list: JList<out Any>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component = when (value) { is JPanel -> { setLabelColor(value, isSelected) val normalColor = if (index % 2 == 0) JBColor.border() else JBColor.background() val selectedColor = UIManager.getColor("List.selectionBackground") value.apply { background = if (isSelected) selectedColor else normalColor } } else -> { JLabel("") } } private fun setLabelColor(panel: JPanel, isSelected: Boolean) = panel.components.forEach { it.foreground = if (isSelected) { UIManager.getColor("List.selectionForeground") } else { JBColor.foreground() } } }
apache-2.0
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/grouping/KatydidDt.kt
1
1406
// // (C) Copyright 2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.elements.grouping import i.katydid.vdom.builders.miscellaneous.KatydidDescriptionListContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidFlowContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for a <dt> element. */ internal class KatydidDt<Msg>( descriptionListContent: KatydidDescriptionListContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit ) : KatydidHtmlElementImpl<Msg>(selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { init { descriptionListContent.flowContent(this).defineContent() this.freeze() } //// override val nodeName = "DT" } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
apixandru/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/inlays/IntentionTest.kt
6
2945
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.codeInsight.daemon.inlays import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.assertj.core.api.Assertions.assertThat class BlackListMethodIntentionTest : LightCodeInsightFixtureTestCase() { private var isParamHintsEnabledBefore = false private val default = ParameterNameHintsSettings() override fun setUp() { super.setUp() val settings = EditorSettingsExternalizable.getInstance() isParamHintsEnabledBefore = settings.isShowParameterNameHints settings.isShowParameterNameHints = true } override fun tearDown() { EditorSettingsExternalizable.getInstance().isShowParameterNameHints = isParamHintsEnabledBefore ParameterNameHintsSettings.Companion.getInstance().loadState(default.state) super.tearDown() } fun `test add to blacklist by alt enter`() { myFixture.configureByText("a.java", """ class Test { void test() { check(<caret>100); } void check(int isShow) {} } """) assertHintExistsAndDisappearsAfterIntention() } fun `test add elements which has inlays`() { myFixture.configureByText("a.java", """ class ParamHintsTest { public static void main(String[] args) { Mvl( <caret>Math.abs(1) * 100, 32, 32 ); } public static double Mvl(double first, double x, double c) { return Double.NaN; } } """) assertHintExistsAndDisappearsAfterIntention() } private fun assertHintExistsAndDisappearsAfterIntention() { myFixture.doHighlighting() val caretOffset = editor.caretModel.offset val before = editor.inlayModel.getInlineElementsInRange(caretOffset, caretOffset) assertThat(before).isNotEmpty val intention = myFixture.getAvailableIntention("Do not show hints for current method") myFixture.launchAction(intention!!) myFixture.doHighlighting() val after = editor.inlayModel.getInlineElementsInRange(caretOffset, caretOffset) assertThat(after).hasSize(1) val text = ParameterHintsPresentationManager.getInstance().getHintText(after[0]) assertThat(text).isNull() } }
apache-2.0
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/grouping/KatydidMain.kt
1
1456
// // (C) Copyright 2017-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.elements.grouping import i.katydid.vdom.builders.KatydidFlowContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidFlowContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for a <main> element. */ internal class KatydidMain<Msg>( flowContent: KatydidFlowContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit ) : KatydidHtmlElementImpl<Msg>(selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { init { flowContent.contentRestrictions.confirmMainAllowed() flowContent.withMainNotAllowed(this).defineContent() this.freeze() } //// override val nodeName = "MAIN" } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
apixandru/intellij-community
plugins/settings-repository/src/ProjectId.kt
18
1266
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "IcsProjectId", storages = arrayOf(Storage(StoragePathMacros.WORKSPACE_FILE))) class ProjectId : PersistentStateComponent<ProjectId> { var uid: String? = null var path: String? = null override fun getState(): ProjectId? { return this } override fun loadState(state: ProjectId?) { XmlSerializerUtil.copyBean(state!!, this) } }
apache-2.0
pokk/KotlinKnifer
kotlinknifer/src/main/java/com/devrapid/kotlinknifer/ViewStub.kt
1
1080
package com.devrapid.kotlinknifer import android.app.Activity import android.view.View import android.view.ViewStub import androidx.annotation.IdRes import androidx.fragment.app.Fragment fun Activity.obtainViewStub(@IdRes stub: Int, @IdRes realView: Int) = (findViewById(stub) as? View) ?: findViewById(realView) fun Fragment.obtainViewStub(@IdRes stub: Int, @IdRes realView: Int) = (requireNotNull(view).findViewById(stub) as? View) ?: requireNotNull(view).findViewById(realView) fun Activity.showViewStub(@IdRes stub: Int, @IdRes realView: Int, options: (View.() -> Unit)? = null) { (findViewById<ViewStub>(stub)?.inflate() ?: findViewById(realView)).apply { visible() bringToFront() options?.let(this::apply) } } fun Fragment.showViewStub(@IdRes stub: Int, @IdRes realView: Int, options: (View.() -> Unit)? = null) { (requireNotNull(view).findViewById<ViewStub>(stub) ?.inflate() ?: requireNotNull(view).findViewById(realView)).apply { visible() bringToFront() options?.let(this::apply) } }
apache-2.0
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/target/RemoteViewsDisplayTargetTest.kt
1
2768
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.target import android.widget.RemoteViews import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.target.RemoteViewsDisplayTarget import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.util.getDrawableCompat import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class RemoteViewsDisplayTargetTest { @Test fun test() { val context = getTestContext() val remoteViews = RemoteViews(context.packageName, android.R.layout.activity_list_item) var callbackCount = 0 RemoteViewsDisplayTarget(remoteViews, android.R.id.icon) { callbackCount++ }.apply { Assert.assertEquals(0, callbackCount) onStart(context.getDrawableCompat(android.R.drawable.bottom_bar)) Assert.assertEquals(1, callbackCount) onStart(null) Assert.assertEquals(2, callbackCount) onError(context.getDrawableCompat(android.R.drawable.bottom_bar)) Assert.assertEquals(3, callbackCount) onError(null) Assert.assertEquals(4, callbackCount) onSuccess(context.getDrawableCompat(android.R.drawable.bottom_bar)) Assert.assertEquals(5, callbackCount) } callbackCount = 0 RemoteViewsDisplayTarget(remoteViews, android.R.id.icon, ignoreNullDrawable = true) { callbackCount++ }.apply { Assert.assertEquals(0, callbackCount) onStart(context.getDrawableCompat(android.R.drawable.bottom_bar)) Assert.assertEquals(1, callbackCount) onStart(null) Assert.assertEquals(1, callbackCount) onError(context.getDrawableCompat(android.R.drawable.bottom_bar)) Assert.assertEquals(2, callbackCount) onError(null) Assert.assertEquals(2, callbackCount) onSuccess(context.getDrawableCompat(android.R.drawable.bottom_bar)) Assert.assertEquals(3, callbackCount) } } }
apache-2.0
Ribesg/anko
dsl/src/org/jetbrains/android/anko/config/AnkoFile.kt
1
2211
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.config import org.jetbrains.android.anko.config.TargetArtifactType.COMMON import org.jetbrains.android.anko.config.TargetArtifactType.SQLITE import org.jetbrains.android.anko.config.TargetArtifactType.PLATFORM import org.jetbrains.android.anko.config.TargetArtifactType.SUPPORT_V4 import org.jetbrains.android.anko.config.TargetArtifactType.TOOLKIT import org.jetbrains.android.anko.utils.toCamelCase enum class TargetArtifactType { COMMON, // Common stuff (does not contain platform-dependent functions) SQLITE, // SqLite Database helpers PLATFORM, // Artifacts for the specific Android SDK version (eg. 15, 19, 21 etc.) SUPPORT_V4, // Artifact for Android support-v4 library (contains some helpers for support.v4 Fragments) TOOLKIT; // Helpers for any other Android libraries } enum class AnkoFile( type: Set<TargetArtifactType>, val shouldBeWritten: (AnkoConfiguration) -> Boolean = { true } ) : ConfigurationOption { LAYOUTS(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)), LISTENERS(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)), PROPERTIES(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)), SERVICES(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)), SQL_PARSER_HELPERS(setOf(SQLITE)), VIEWS(setOf(PLATFORM, SUPPORT_V4, TOOLKIT), { it[VIEWS] || it[ConfigurationTune.HELPER_CONSTRUCTORS] }); val types: Set<TargetArtifactType> = type.toSet() val filename: String by lazy { val name = name val extension = if (name.endsWith("_JAVA")) ".java" else ".kt" name.substringBeforeLast("_JAVA").toCamelCase() + extension } }
apache-2.0
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/ComponentRegistryTest.kt
1
27573
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.ComponentRegistry import com.github.panpf.sketch.decode.internal.DefaultBitmapDecoder import com.github.panpf.sketch.decode.internal.DefaultDrawableDecoder import com.github.panpf.sketch.decode.internal.EngineBitmapDecodeInterceptor import com.github.panpf.sketch.decode.internal.EngineDrawableDecodeInterceptor import com.github.panpf.sketch.decode.internal.XmlDrawableBitmapDecoder import com.github.panpf.sketch.fetch.AssetUriFetcher import com.github.panpf.sketch.fetch.Base64UriFetcher import com.github.panpf.sketch.fetch.HttpUriFetcher import com.github.panpf.sketch.fetch.ResourceUriFetcher import com.github.panpf.sketch.isNotEmpty import com.github.panpf.sketch.merged import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.internal.EngineRequestInterceptor import com.github.panpf.sketch.test.utils.Test2BitmapDecodeInterceptor import com.github.panpf.sketch.test.utils.Test2DrawableDecodeInterceptor import com.github.panpf.sketch.test.utils.TestAssets import com.github.panpf.sketch.test.utils.TestBitmapDecodeInterceptor import com.github.panpf.sketch.test.utils.TestBitmapDecoder import com.github.panpf.sketch.test.utils.TestDrawableDecodeInterceptor import com.github.panpf.sketch.test.utils.TestDrawableDecoder import com.github.panpf.sketch.test.utils.TestFetcher import com.github.panpf.sketch.test.utils.TestRequestInterceptor import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.test.utils.newSketch import com.github.panpf.sketch.test.utils.toRequestContext import com.github.panpf.sketch.transform.internal.BitmapTransformationDecodeInterceptor import com.github.panpf.tools4j.test.ktx.assertNoThrow import com.github.panpf.tools4j.test.ktx.assertThrow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ComponentRegistryTest { @Test fun testNewBuilder() { ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) addBitmapDecoder(XmlDrawableBitmapDecoder.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) }.build().apply { Assert.assertEquals( listOf(HttpUriFetcher.Factory()), fetcherFactoryList ) Assert.assertEquals( listOf(XmlDrawableBitmapDecoder.Factory()), bitmapDecoderFactoryList ) Assert.assertEquals( listOf(DefaultDrawableDecoder.Factory()), drawableDecoderFactoryList ) Assert.assertTrue(requestInterceptorList.isEmpty()) Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty()) Assert.assertTrue(drawableDecodeInterceptorList.isEmpty()) }.newBuilder().build().apply { Assert.assertEquals( listOf(HttpUriFetcher.Factory()), fetcherFactoryList ) Assert.assertEquals( listOf(XmlDrawableBitmapDecoder.Factory()), bitmapDecoderFactoryList ) Assert.assertEquals( listOf(DefaultDrawableDecoder.Factory()), drawableDecoderFactoryList ) Assert.assertTrue(requestInterceptorList.isEmpty()) Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty()) Assert.assertTrue(drawableDecodeInterceptorList.isEmpty()) }.newBuilder { addRequestInterceptor(EngineRequestInterceptor()) addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor()) addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor()) }.build().apply { Assert.assertEquals( listOf(HttpUriFetcher.Factory()), fetcherFactoryList ) Assert.assertEquals( listOf(XmlDrawableBitmapDecoder.Factory()), bitmapDecoderFactoryList ) Assert.assertEquals( listOf(DefaultDrawableDecoder.Factory()), drawableDecoderFactoryList ) Assert.assertEquals(listOf(EngineRequestInterceptor()), requestInterceptorList) Assert.assertEquals( listOf(EngineBitmapDecodeInterceptor()), bitmapDecodeInterceptorList ) Assert.assertEquals( listOf(EngineDrawableDecodeInterceptor()), drawableDecodeInterceptorList ) } } @Test fun testNewRegistry() { ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) addBitmapDecoder(XmlDrawableBitmapDecoder.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) }.build().apply { Assert.assertEquals( listOf(HttpUriFetcher.Factory()), fetcherFactoryList ) Assert.assertEquals( listOf(XmlDrawableBitmapDecoder.Factory()), bitmapDecoderFactoryList ) Assert.assertEquals( listOf(DefaultDrawableDecoder.Factory()), drawableDecoderFactoryList ) Assert.assertTrue(requestInterceptorList.isEmpty()) Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty()) Assert.assertTrue(drawableDecodeInterceptorList.isEmpty()) }.newRegistry().apply { Assert.assertEquals( listOf(HttpUriFetcher.Factory()), fetcherFactoryList ) Assert.assertEquals( listOf(XmlDrawableBitmapDecoder.Factory()), bitmapDecoderFactoryList ) Assert.assertEquals( listOf(DefaultDrawableDecoder.Factory()), drawableDecoderFactoryList ) Assert.assertTrue(requestInterceptorList.isEmpty()) Assert.assertTrue(bitmapDecodeInterceptorList.isEmpty()) Assert.assertTrue(drawableDecodeInterceptorList.isEmpty()) }.newRegistry { addRequestInterceptor(EngineRequestInterceptor()) addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor()) addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor()) }.apply { Assert.assertEquals( listOf(HttpUriFetcher.Factory()), fetcherFactoryList ) Assert.assertEquals( listOf(XmlDrawableBitmapDecoder.Factory()), bitmapDecoderFactoryList ) Assert.assertEquals( listOf(DefaultDrawableDecoder.Factory()), drawableDecoderFactoryList ) Assert.assertEquals(listOf(EngineRequestInterceptor()), requestInterceptorList) Assert.assertEquals( listOf(EngineBitmapDecodeInterceptor()), bitmapDecodeInterceptorList ) Assert.assertEquals( listOf(EngineDrawableDecodeInterceptor()), drawableDecodeInterceptorList ) } } @Test fun testIsEmpty() { ComponentRegistry.Builder().build().apply { Assert.assertTrue(isEmpty()) Assert.assertFalse(isNotEmpty()) } ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } ComponentRegistry.Builder().apply { addBitmapDecoder(DefaultBitmapDecoder.Factory()) }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } ComponentRegistry.Builder().apply { addDrawableDecoder(DefaultDrawableDecoder.Factory()) }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } ComponentRegistry.Builder().apply { addRequestInterceptor(EngineRequestInterceptor()) }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } ComponentRegistry.Builder().apply { addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor()) }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } ComponentRegistry.Builder().apply { addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor()) }.build().apply { Assert.assertFalse(isEmpty()) Assert.assertTrue(isNotEmpty()) } } @Test fun testNewFetcher() { val context = getTestContext() val sketch = newSketch() ComponentRegistry.Builder().build().apply { assertThrow(IllegalStateException::class) { runBlocking(Dispatchers.Main) { newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) } } } ComponentRegistry.Builder().build().apply { assertThrow(IllegalArgumentException::class) { newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) } assertThrow(IllegalArgumentException::class) { newFetcher(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg")) } Assert.assertNull( newFetcherOrNull(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) ) Assert.assertNull( newFetcherOrNull(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg")) ) } ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) }.build().apply { assertNoThrow { newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) } assertThrow(IllegalArgumentException::class) { newFetcher(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg")) } Assert.assertNotNull( newFetcherOrNull(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) ) Assert.assertNull( newFetcherOrNull(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg")) ) } ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) addFetcher(HttpUriFetcher.Factory()) }.build().apply { assertNoThrow { newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) } assertNoThrow { newFetcher(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg")) } Assert.assertNotNull( newFetcherOrNull(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) ) Assert.assertNotNull( newFetcherOrNull(sketch, DisplayRequest(context, "http://sample.com/sample.jpeg")) ) } } @Test fun testBitmapDecoder() { val context = getTestContext() val sketch = newSketch() val request = DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI) val requestContext = request.toRequestContext() ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) }.build().apply { val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) val fetchResult = runBlocking { fetcher.fetch() } assertThrow(IllegalStateException::class) { runBlocking(Dispatchers.Main) { newBitmapDecoder(sketch, requestContext, fetchResult) } } } ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) }.build().apply { val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) val fetchResult = runBlocking { fetcher.fetch() } assertThrow(IllegalArgumentException::class) { newBitmapDecoder(sketch, requestContext, fetchResult) } Assert.assertNull( newBitmapDecoderOrNull(sketch, requestContext, fetchResult) ) } ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) addBitmapDecoder(DefaultBitmapDecoder.Factory()) }.build().apply { val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) val fetchResult = runBlocking { fetcher.fetch() } assertNoThrow { newBitmapDecoder(sketch, requestContext, fetchResult) } Assert.assertNotNull( newBitmapDecoderOrNull(sketch, requestContext, fetchResult) ) } } @Test fun testDrawableDecoder() { val context = getTestContext() val sketch = newSketch() val request = DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI) val requestContext = request.toRequestContext() ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) }.build().apply { val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) val fetchResult = runBlocking { fetcher.fetch() } assertThrow(IllegalStateException::class) { runBlocking(Dispatchers.Main) { newDrawableDecoder(sketch, requestContext, fetchResult) } } } ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) }.build().apply { val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) val fetchResult = runBlocking { fetcher.fetch() } assertThrow(IllegalArgumentException::class) { newDrawableDecoder(sketch, requestContext, fetchResult) } Assert.assertNull( newDrawableDecoderOrNull(sketch, requestContext, fetchResult) ) } ComponentRegistry.Builder().apply { addFetcher(AssetUriFetcher.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) }.build().apply { val fetcher = newFetcher(sketch, DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)) val fetchResult = runBlocking { fetcher.fetch() } assertNoThrow { newDrawableDecoder(sketch, requestContext, fetchResult) } Assert.assertNotNull( newDrawableDecoderOrNull(sketch, requestContext, fetchResult) ) } } @Test fun testMerged() { val componentRegistry = ComponentRegistry.Builder().apply { addFetcher(TestFetcher.Factory()) addBitmapDecoder(TestBitmapDecoder.Factory()) addDrawableDecoder(TestDrawableDecoder.Factory()) addRequestInterceptor(TestRequestInterceptor()) addBitmapDecodeInterceptor(TestBitmapDecodeInterceptor()) addDrawableDecodeInterceptor(TestDrawableDecodeInterceptor()) }.build().apply { Assert.assertEquals( "ComponentRegistry(" + "fetcherFactoryList=[TestFetcher]," + "bitmapDecoderFactoryList=[TestBitmapDecoder]," + "drawableDecoderFactoryList=[TestDrawableDecoder]," + "requestInterceptorList=[TestRequestInterceptor(sortWeight=0)]," + "bitmapDecodeInterceptorList=[TestBitmapDecodeInterceptor(sortWeight=0)]," + "drawableDecodeInterceptorList=[TestDrawableDecodeInterceptor(sortWeight=0)]" + ")", toString() ) } val componentRegistry1 = ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) addBitmapDecoder(DefaultBitmapDecoder.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) addRequestInterceptor(EngineRequestInterceptor()) addBitmapDecodeInterceptor(Test2BitmapDecodeInterceptor()) addDrawableDecodeInterceptor(Test2DrawableDecodeInterceptor()) }.build().apply { Assert.assertEquals( "ComponentRegistry(" + "fetcherFactoryList=[HttpUriFetcher]," + "bitmapDecoderFactoryList=[DefaultBitmapDecoder]," + "drawableDecoderFactoryList=[DefaultDrawableDecoder]," + "requestInterceptorList=[EngineRequestInterceptor(sortWeight=100)]," + "bitmapDecodeInterceptorList=[Test2BitmapDecodeInterceptor(sortWeight=0)]," + "drawableDecodeInterceptorList=[Test2DrawableDecodeInterceptor(sortWeight=0)]" + ")", toString() ) } Assert.assertNotEquals(componentRegistry, componentRegistry1) val componentRegistry2 = componentRegistry.merged(componentRegistry1).apply { Assert.assertEquals( "ComponentRegistry(" + "fetcherFactoryList=[TestFetcher,HttpUriFetcher]," + "bitmapDecoderFactoryList=[TestBitmapDecoder,DefaultBitmapDecoder]," + "drawableDecoderFactoryList=[TestDrawableDecoder,DefaultDrawableDecoder]," + "requestInterceptorList=[TestRequestInterceptor(sortWeight=0),EngineRequestInterceptor(sortWeight=100)]," + "bitmapDecodeInterceptorList=[TestBitmapDecodeInterceptor(sortWeight=0),Test2BitmapDecodeInterceptor(sortWeight=0)]," + "drawableDecodeInterceptorList=[TestDrawableDecodeInterceptor(sortWeight=0),Test2DrawableDecodeInterceptor(sortWeight=0)]" + ")", toString() ) } Assert.assertNotEquals(componentRegistry, componentRegistry2) Assert.assertNotEquals(componentRegistry1, componentRegistry2) Assert.assertSame(componentRegistry, componentRegistry.merged(null)) Assert.assertSame(componentRegistry, null.merged(componentRegistry)) } @Test fun testToString() { ComponentRegistry.Builder().build().apply { Assert.assertEquals( "ComponentRegistry(" + "fetcherFactoryList=[]," + "bitmapDecoderFactoryList=[]," + "drawableDecoderFactoryList=[]," + "requestInterceptorList=[]," + "bitmapDecodeInterceptorList=[]," + "drawableDecodeInterceptorList=[]" + ")", toString() ) } ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) addFetcher(Base64UriFetcher.Factory()) addFetcher(ResourceUriFetcher.Factory()) addBitmapDecoder(XmlDrawableBitmapDecoder.Factory()) addBitmapDecoder(DefaultBitmapDecoder.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) addRequestInterceptor(EngineRequestInterceptor()) addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor()) addBitmapDecodeInterceptor(BitmapTransformationDecodeInterceptor()) addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor()) }.build().apply { Assert.assertEquals( "ComponentRegistry(" + "fetcherFactoryList=[HttpUriFetcher,Base64UriFetcher,ResourceUriFetcher]," + "bitmapDecoderFactoryList=[XmlDrawableBitmapDecoder,DefaultBitmapDecoder]," + "drawableDecoderFactoryList=[DefaultDrawableDecoder]," + "requestInterceptorList=[EngineRequestInterceptor(sortWeight=100)]," + "bitmapDecodeInterceptorList=[BitmapTransformationDecodeInterceptor(sortWeight=90),EngineBitmapDecodeInterceptor(sortWeight=100)]," + "drawableDecodeInterceptorList=[EngineDrawableDecodeInterceptor(sortWeight=100)]" + ")", toString() ) } } @Test fun testEquals() { val componentRegistry0 = ComponentRegistry.Builder().build() val componentRegistry1 = ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) }.build() val componentRegistry11 = ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) }.build() val componentRegistry2 = ComponentRegistry.Builder().apply { addBitmapDecoder(XmlDrawableBitmapDecoder.Factory()) }.build() val componentRegistry3 = ComponentRegistry.Builder().apply { addDrawableDecoder(DefaultDrawableDecoder.Factory()) }.build() val componentRegistry4 = ComponentRegistry.Builder().apply { addRequestInterceptor(EngineRequestInterceptor()) }.build() val componentRegistry5 = ComponentRegistry.Builder().apply { addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor()) }.build() val componentRegistry6 = ComponentRegistry.Builder().apply { addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor()) }.build() Assert.assertEquals(componentRegistry0, componentRegistry0) Assert.assertEquals(componentRegistry1, componentRegistry11) Assert.assertNotEquals(componentRegistry1, Any()) Assert.assertNotEquals(componentRegistry1, null) Assert.assertNotEquals(componentRegistry0, componentRegistry1) Assert.assertNotEquals(componentRegistry0, componentRegistry2) Assert.assertNotEquals(componentRegistry0, componentRegistry3) Assert.assertNotEquals(componentRegistry0, componentRegistry4) Assert.assertNotEquals(componentRegistry0, componentRegistry5) Assert.assertNotEquals(componentRegistry0, componentRegistry6) Assert.assertNotEquals(componentRegistry1, componentRegistry2) Assert.assertNotEquals(componentRegistry1, componentRegistry3) Assert.assertNotEquals(componentRegistry1, componentRegistry4) Assert.assertNotEquals(componentRegistry1, componentRegistry5) Assert.assertNotEquals(componentRegistry1, componentRegistry6) Assert.assertNotEquals(componentRegistry2, componentRegistry3) Assert.assertNotEquals(componentRegistry2, componentRegistry4) Assert.assertNotEquals(componentRegistry2, componentRegistry5) Assert.assertNotEquals(componentRegistry2, componentRegistry6) Assert.assertNotEquals(componentRegistry3, componentRegistry4) Assert.assertNotEquals(componentRegistry3, componentRegistry5) Assert.assertNotEquals(componentRegistry3, componentRegistry6) Assert.assertNotEquals(componentRegistry4, componentRegistry5) Assert.assertNotEquals(componentRegistry4, componentRegistry6) Assert.assertNotEquals(componentRegistry5, componentRegistry6) } @Test fun testHashCode() { val componentRegistry0 = ComponentRegistry.Builder().build() val componentRegistry1 = ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) }.build() val componentRegistry2 = ComponentRegistry.Builder().apply { addBitmapDecoder(XmlDrawableBitmapDecoder.Factory()) }.build() val componentRegistry3 = ComponentRegistry.Builder().apply { addDrawableDecoder(DefaultDrawableDecoder.Factory()) }.build() val componentRegistry4 = ComponentRegistry.Builder().apply { addRequestInterceptor(EngineRequestInterceptor()) }.build() val componentRegistry5 = ComponentRegistry.Builder().apply { addBitmapDecodeInterceptor(EngineBitmapDecodeInterceptor()) }.build() val componentRegistry6 = ComponentRegistry.Builder().apply { addDrawableDecodeInterceptor(EngineDrawableDecodeInterceptor()) }.build() Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry1.hashCode()) Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry2.hashCode()) Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry3.hashCode()) Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry4.hashCode()) Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry5.hashCode()) Assert.assertNotEquals(componentRegistry0.hashCode(), componentRegistry6.hashCode()) Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry2.hashCode()) Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry3.hashCode()) Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry4.hashCode()) Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry5.hashCode()) Assert.assertNotEquals(componentRegistry1.hashCode(), componentRegistry6.hashCode()) Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry3.hashCode()) Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry4.hashCode()) Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry5.hashCode()) Assert.assertNotEquals(componentRegistry2.hashCode(), componentRegistry6.hashCode()) Assert.assertNotEquals(componentRegistry3.hashCode(), componentRegistry4.hashCode()) Assert.assertNotEquals(componentRegistry3.hashCode(), componentRegistry5.hashCode()) Assert.assertNotEquals(componentRegistry3.hashCode(), componentRegistry6.hashCode()) Assert.assertNotEquals(componentRegistry4.hashCode(), componentRegistry5.hashCode()) Assert.assertNotEquals(componentRegistry4.hashCode(), componentRegistry6.hashCode()) Assert.assertNotEquals(componentRegistry5.hashCode(), componentRegistry6.hashCode()) } }
apache-2.0
Ribesg/anko
dsl/test/org/jetbrains/android/anko/functional/FunctionalTestsForSupportV4.kt
1
1986
package org.jetbrains.android.anko.functional import org.jetbrains.android.anko.config.* import org.junit.Test class FunctionalTestsForSupportV4 : AbstractFunctionalTest() { val version = "support-v4" @Test fun testComplexListenerClassTest() { runFunctionalTest("ComplexListenerClassTest.kt", AnkoFile.LISTENERS, version) { files.add(AnkoFile.LISTENERS) tunes.add(ConfigurationTune.COMPLEX_LISTENER_CLASSES) } } @Test fun testComplexListenerSetterTest() { runFunctionalTest("ComplexListenerSetterTest.kt", AnkoFile.LISTENERS, version) { files.add(AnkoFile.LISTENERS) tunes.add(ConfigurationTune.COMPLEX_LISTENER_SETTERS) } } @Test fun testLayoutsTest() { runFunctionalTest("LayoutsTest.kt", AnkoFile.LAYOUTS, version) { files.add(AnkoFile.LAYOUTS) } } @Test fun testViewTest() { runFunctionalTest("ViewTest.kt", AnkoFile.VIEWS, version) { files.add(AnkoFile.VIEWS) tunes.add(ConfigurationTune.TOP_LEVEL_DSL_ITEMS) tunes.add(ConfigurationTune.HELPER_CONSTRUCTORS) } } @Test fun testPropertyTest() { runFunctionalTest("PropertyTest.kt", AnkoFile.PROPERTIES, version) { files.add(AnkoFile.PROPERTIES) } } @Test fun testServicesTest() { runFunctionalTest("ServicesTest.kt", AnkoFile.SERVICES, version) { files.add(AnkoFile.SERVICES) } } @Test fun testSimpleListenerTest() { runFunctionalTest("SimpleListenerTest.kt", AnkoFile.LISTENERS, version) { files.add(AnkoFile.LISTENERS) tunes.add(ConfigurationTune.SIMPLE_LISTENERS) } } @Test fun testSqlParserHelpersTest() { runFunctionalTest("SqlParserHelpersTest.kt", AnkoFile.SQL_PARSER_HELPERS, version) { files.add(AnkoFile.SQL_PARSER_HELPERS) } } }
apache-2.0
kjkrol/kotlin4fun-eshop-app
ordering-service/src/main/kotlin/kotlin4fun/eshop/ordering/integration/ProductCatalogClient.kt
1
1205
package kotlin4fun.eshop.ordering.integration import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import org.springframework.cloud.netflix.feign.FeignClient import org.springframework.hateoas.PagedResources import org.springframework.hateoas.Resource import org.springframework.hateoas.core.Relation import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import java.util.UUID @FeignClient(serviceId = "PRODUCT-CATALOG-SERVICE") internal interface ProductCatalogClient { @RequestMapping(path = arrayOf("/product"), method = arrayOf(RequestMethod.GET)) fun findAll(@RequestParam("ids") ids: List<UUID>): PagedResources<Resource<ProductResponse>> } @JsonIgnoreProperties(ignoreUnknown = true) @Relation(collectionRelation = "products") internal data class ProductResponse @JsonCreator constructor( @JsonProperty("productId") val productId: UUID, @JsonProperty("name") val name: String, @JsonProperty("price") val price: Double )
apache-2.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/ReadingListsFunnel.kt
1
3140
package org.wikipedia.analytics import org.json.JSONObject import org.wikipedia.Constants.InvokeSource import org.wikipedia.WikipediaApp import org.wikipedia.readinglist.database.ReadingList import org.wikipedia.settings.Prefs class ReadingListsFunnel : Funnel(WikipediaApp.instance, SCHEMA_NAME, REV_ID) { fun logAddClick(source: InvokeSource) { log("action", "addclick", "addsource", source.ordinal) } fun logAddToList(list: ReadingList, listCount: Int, source: InvokeSource) { log( "action", if (list.pages.isEmpty()) "addtonew" else "addtoexisting", "addsource", source.ordinal, "itemcount", list.pages.size, "listcount", listCount ) } fun logMoveClick(source: InvokeSource) { log("action", "moveclick", "addsource", source.ordinal) } fun logMoveToList(list: ReadingList, listCount: Int, source: InvokeSource) { log( "action", if (list.pages.isEmpty()) "movetonew" else "movetoexisting", "addsource", source.ordinal, "itemcount", list.pages.size, "listcount", listCount ) } fun logModifyList(list: ReadingList, listCount: Int) { log("action", "modifylist", "itemcount", list.pages.size, "listcount", listCount) } fun logDeleteList(list: ReadingList, listCount: Int) { log("action", "deletelist", "itemcount", list.pages.size, "listcount", listCount) } fun logDeleteItem(list: ReadingList, listCount: Int) { log("action", "deleteitem", "itemcount", list.pages.size, "listcount", listCount) } fun logShareList(list: ReadingList) { log("action", "share", "itemcount", list.pages.size) } fun logExportLists(listCount: Int) { log("action", "export", "listcount", listCount) } fun logImportStart() { log("action", "import_start") } fun logImportCancel(listCount: Int) { log("action", "import_cancel", "listcount", listCount) } fun logImportFinish(listCount: Int) { log("action", "import_finish", "listcount", listCount) } fun logReceiveStart() { log("action", "receive_start") } fun logReceivePreview(list: ReadingList) { log("action", "receive_preview", "itemcount", list.pages.size) } fun logReceiveCancel(list: ReadingList) { log("action", "receive_cancel", "itemcount", list.pages.size) } fun logReceiveFinish(list: ReadingList) { log("action", "receive_finish", "itemcount", list.pages.size) } fun logSurveyShown() { log("action", "survey_shown") } override fun preprocessData(eventData: JSONObject): JSONObject { preprocessData(eventData, "synced", Prefs.isReadingListSyncEnabled) return super.preprocessData(eventData) } override fun preprocessSessionToken(eventData: JSONObject) {} companion object { private const val SCHEMA_NAME = "MobileWikiAppReadingLists" private const val REV_ID = 24051158 } }
apache-2.0
matejdro/WearMusicCenter
wear/src/main/java/com/matejdro/wearmusiccenter/watch/util/Clock.kt
1
348
package com.matejdro.wearmusiccenter.watch.util import android.os.SystemClock interface SystemClockProvider { /** * @see android.os.SystemClock.elapsedRealtime */ fun elapsedRealtime(): Long } object DefaultSystemClockProvider : SystemClockProvider { override fun elapsedRealtime(): Long = SystemClock.elapsedRealtime() }
gpl-3.0
chadrick-kwag/datalabeling_app
app/src/main/java/com/example/chadrick/datalabeling/Models/RecentActivityLogManager.kt
1
4768
package com.example.chadrick.datalabeling.Models import android.content.Context import android.util.Log import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.* import java.lang.ref.WeakReference import java.nio.charset.Charset import java.util.* import java.util.concurrent.CancellationException import kotlin.collections.ArrayList /** * Created by chadrick on 17. 12. 5. */ class RecentActivityLogManager { // var mcontext: Context var mcontext: Context by WeakRefHolder() companion object { @Volatile private var INSTANCE: RecentActivityLogManager? = null fun getInstance(context: Context): RecentActivityLogManager = INSTANCE ?: synchronized(this) { INSTANCE ?: RecentActivityLogManager(context).also { INSTANCE = it } } val TAG: String = "RecentActivityLogManager" val RAitemMap = HashMap<Int, Pair<DataSet, Long>>() // Int is the dataset id of DataSet val jsonfilename = "recentactivitylog.json" lateinit var jsonfilefullpath: File } private constructor(context: Context) { // mcontext = context try { mcontext = context readparse() } catch(e: CancellationException){ } } private fun readparse() { jsonfilefullpath = File(mcontext.filesDir, jsonfilename) Log.d(TAG, "ralogfile=" + jsonfilefullpath) if (!jsonfilefullpath.exists()) { return } val inputstream = FileInputStream(jsonfilefullpath) var size = inputstream.available() val buffer = ByteArray(size) inputstream.read(buffer) inputstream.close() val jsonfilereadraw = String(buffer, Charset.forName("UTF-8")) Log.d(TAG, "jsonfile read raw=" + jsonfilereadraw) val rootobj = JSONObject(jsonfilereadraw) val RAarray = rootobj.getJSONArray("items") for (i in 0..RAarray.length() - 1) { try { val item = RAarray.getJSONObject(i) var extractedDS: DataSet = DataSet.deserialize(item.getString("dataset")) RAitemMap.put(extractedDS.id, Pair<DataSet, Long>(extractedDS, item.getLong("recent_access_time"))) } catch (e: JSONException) { // the file is corrupt. delete it. Log.d(TAG, "the ra json file is corrupt. delete it") jsonfilefullpath.delete() return } } // mid check Log.d(TAG, "RAitemMap size=" + RAitemMap.size) // print all objects for (item in RAitemMap) { Log.d(TAG, "key=" + item.key + ", value=" + item.value) } } fun updateRAitem(dataset: DataSet, access_datetime: Long) { RAitemMap.put(dataset.id, Pair<DataSet, Long>(dataset, access_datetime)) // val sortedMap = RAitemMap.toList().sortedBy { (key,value) -> -value }.toMap() // // print the contents of sortedMap // Log.d(TAG,"print sorted result") // for(item in sortedMap){ // Log.d(TAG,"key="+item.key+", value="+item.value) // } Log.d(TAG, "print RAitemMap") for (item in RAitemMap) { Log.d(TAG, "key.id=" + item.key + ", value=" + item.value) } savetojsonfile() } fun savetojsonfile() { Log.d(TAG, "inside savetojsonfile") // convert RAitemmap to json obj // create individual jsonojects for each RAitemmap item val convertedJsonobjs = ArrayList<JSONObject>() for (item in RAitemMap) { val jsonobj = JSONObject() jsonobj.put("dataset", item.value.first.serialize()) jsonobj.put("recent_access_time", item.value.second) convertedJsonobjs.add(jsonobj) } val itemjsonarray = JSONArray(convertedJsonobjs) Log.d(TAG, "print itemjsonarray = " + itemjsonarray.toString()) val rootobj = JSONObject() rootobj.put("items", itemjsonarray) // print completed jsonobj Log.d(TAG, "temp created root jsonobj: " + rootobj.toString()) if (jsonfilefullpath.exists()) { jsonfilefullpath.delete() } val fileWriter = FileWriter(jsonfilefullpath) val output = BufferedWriter(fileWriter) output.write(rootobj.toString()) output.close() } fun getsortedlist(): ArrayList<DataSet> { val pairlist = RAitemMap.toList().sortedBy { (key, value) -> -value.second } val dsidlist = ArrayList<DataSet>() pairlist.forEach { (key, value) -> dsidlist.add(value.first) } return dsidlist } }
mit
Devifish/ReadMe
app/src/main/java/cn/devifish/readme/view/base/BaseFragment.kt
1
1102
package cn.devifish.readme.view.base import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * Created by zhang on 2017/6/3. * Fragment基类 */ abstract class BaseFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (inflater != null && bindLayout() != 0) { return inflater.inflate(bindLayout(), container, false) } return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initVar() initView(view) } @LayoutRes protected abstract fun bindLayout(): Int protected abstract fun initVar() protected abstract fun initView(view: View) }
apache-2.0
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/exception/RateLimitException.kt
1
517
package com.stripe.android.core.exception import com.stripe.android.core.StripeError import com.stripe.android.core.networking.HTTP_TOO_MANY_REQUESTS /** * An [Exception] indicating that too many requests have hit the API too quickly. */ class RateLimitException( stripeError: StripeError? = null, requestId: String? = null, message: String? = stripeError?.message, cause: Throwable? = null ) : StripeException( stripeError, requestId, HTTP_TOO_MANY_REQUESTS, cause, message )
mit
AndroidX/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/node/ObserverNodeTest.kt
3
5380
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.node import androidx.compose.foundation.layout.Box import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalComposeUiApi::class) @MediumTest @RunWith(AndroidJUnit4::class) class ObserverNodeTest { @get:Rule val rule = createComposeRule() @Test fun simplyObservingValue_doesNotTriggerCallback() { // Arrange. val value by mutableStateOf(1) var callbackInvoked = false val observerNode = TestObserverNode { callbackInvoked = true } rule.setContent { Box(Modifier.modifierElementOf { observerNode }) } // Act. rule.runOnIdle { // Read value to observe changes. observerNode.observeReads { value.toString() } } // Assert. rule.runOnIdle { assertThat(callbackInvoked).isFalse() } } @Test fun changeInObservedValue_triggersCallback() { // Arrange. var value by mutableStateOf(1) var callbackInvoked = false val observerNode = TestObserverNode { callbackInvoked = true } rule.setContent { Box(Modifier.modifierElementOf { observerNode }) } // Act. rule.runOnIdle { // Read value to observe changes. observerNode.observeReads { value.toString() } // Write to the read value to trigger onObservedReadsChanged. value = 3 } // Assert. rule.runOnIdle { assertThat(callbackInvoked).isTrue() } } @Test(expected = IllegalStateException::class) fun unusedNodeDoesNotObserve() { // Arrange. var value by mutableStateOf(1) var callbackInvoked = false val observerNode = TestObserverNode { callbackInvoked = true } // Act. rule.runOnIdle { // Read value to observe changes. observerNode.observeReads { value.toString() } // Write to the read value to trigger onObservedReadsChanged. value = 3 } // Assert. rule.runOnIdle { assertThat(callbackInvoked).isFalse() } } @Test fun detachedNodeCanObserveReads() { // Arrange. var value by mutableStateOf(1) var callbackInvoked = false val observerNode = TestObserverNode { callbackInvoked = true } var attached by mutableStateOf(true) rule.setContent { Box(if (attached) modifierElementOf { observerNode } else Modifier) } // Act. // Read value while not attached. rule.runOnIdle { attached = false } rule.runOnIdle { observerNode.observeReads { value.toString() } } rule.runOnIdle { attached = true } // Write to the read value to trigger onObservedReadsChanged. rule.runOnIdle { value = 3 } // Assert. rule.runOnIdle { assertThat(callbackInvoked).isTrue() } } @Test fun detachedNodeDoesNotCallOnObservedReadsChanged() { // Arrange. var value by mutableStateOf(1) var callbackInvoked = false val observerNode = TestObserverNode { callbackInvoked = true } var attached by mutableStateOf(true) rule.setContent { Box(if (attached) modifierElementOf { observerNode } else Modifier) } // Act. rule.runOnIdle { // Read value to observe changes. observerNode.observeReads { value.toString() } } rule.runOnIdle { attached = false } // Write to the read value to trigger onObservedReadsChanged. rule.runOnIdle { value = 3 } // Assert. rule.runOnIdle { assertThat(callbackInvoked).isFalse() } } @ExperimentalComposeUiApi private inline fun <reified T : Modifier.Node> Modifier.modifierElementOf( crossinline create: () -> T, ): Modifier { return this.then(modifierElementOf(create) { name = "testNode" }) } class TestObserverNode( private val onObserveReadsChanged: () -> Unit, ) : ObserverNode, Modifier.Node() { override fun onObservedReadsChanged() { this.onObserveReadsChanged() } } }
apache-2.0
visiolink-android-dev/visiolink-app-plugin
src/main/kotlin/com/visiolink/app/task/AddAdtechModuleTask.kt
1
428
package com.visiolink.app.task import org.gradle.api.tasks.TaskAction /** * Task to add the AdTech sub module to an existing project. */ open class AddAdtechModuleTask: VisiolinkGroupTask() { init { description = "Task to add the AdTech sub module to an existing project" } @TaskAction fun action() { addSubModule("AdTechAdProvider", "adtech") println("Done adding AdTech") } }
apache-2.0
hannesa2/owncloud-android
owncloudDomain/src/main/java/com/owncloud/android/domain/camerauploads/FolderBackupRepository.kt
2
1313
/** * ownCloud Android client application * * @author Abel García de Prada * Copyright (C) 2021 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.domain.camerauploads import com.owncloud.android.domain.camerauploads.model.CameraUploadsConfiguration import com.owncloud.android.domain.camerauploads.model.FolderBackUpConfiguration import kotlinx.coroutines.flow.Flow interface FolderBackupRepository { fun getCameraUploadsConfiguration(): CameraUploadsConfiguration? fun getFolderBackupConfigurationStreamByName(name: String): Flow<FolderBackUpConfiguration?> fun saveFolderBackupConfiguration(folderBackUpConfiguration: FolderBackUpConfiguration) fun resetFolderBackupConfigurationByName(name: String) }
gpl-2.0
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/sequences/MapWithPreviousSequence.kt
1
1329
package com.xenoage.utils.sequences /** * A sequence that returns projected values from the underlying [sequence]. * It is identical to the [MappingSequence] from the * standard library but also provides the previous filtered value at each item. */ class MapWithPreviousSequence<I, O>( private val sequence: Sequence<I>, private val map: (current: I, previous: O?) -> O ) : Sequence<O> { override fun iterator(): Iterator<O> = object : Iterator<O> { val iterator = sequence.iterator() var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue var previousMappedItem: O? = null //at the beginning, no item was mapped yet private fun calcNext() { while (iterator.hasNext()) { val item = iterator.next() previousMappedItem = map(item, previousMappedItem) nextState = 1 return } nextState = 0 } override fun next(): O { if (nextState == -1) calcNext() if (nextState == 0) throw NoSuchElementException() val result = previousMappedItem!! nextState = -1 return result } override fun hasNext(): Boolean { if (nextState == -1) calcNext() return nextState == 1 } } } /** See [MapWithPreviousSequence]. */ fun <I, O> Sequence<I>.mapWithPrevious(map: (current: I, previous: O?) -> O): Sequence<O> = MapWithPreviousSequence(this, map)
agpl-3.0
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/sitrep/SitReportAdapter.kt
1
6540
package au.com.codeka.warworlds.client.game.sitrep import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.concurrency.Threads import au.com.codeka.warworlds.client.ctrl.fromHtml import au.com.codeka.warworlds.client.game.build.BuildViewHelper import au.com.codeka.warworlds.client.game.world.ImageHelper import au.com.codeka.warworlds.client.game.world.StarManager import au.com.codeka.warworlds.common.proto.Design import au.com.codeka.warworlds.common.proto.SituationReport import au.com.codeka.warworlds.common.proto.Star import au.com.codeka.warworlds.common.sim.DesignHelper import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.* class SitReportAdapter(private val layoutInflater: LayoutInflater) : RecyclerView.Adapter<SitReportAdapter.SitReportViewHolder>() { private val rows = ArrayList<RowData>() private val starRowMap = HashMap<Long, Set<Int>>() companion object { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM, yyyy", Locale.ENGLISH) val timeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("h:mm\na", Locale.ENGLISH) } fun refresh(sitReports: List<SituationReport>) { Threads.checkOnThread(Threads.UI) rows.clear() starRowMap.clear() var lastDate: LocalDate? = null for ((i, sitReport) in sitReports.withIndex()) { val date = LocalDateTime.ofEpochSecond(sitReport.report_time / 1000, 0, ZoneOffset.UTC).toLocalDate() if (lastDate == null || lastDate != date) { rows.add(RowData(date, null)) lastDate = date } rows.add(RowData(null, sitReport)) val positions = starRowMap[sitReport.star_id] ?: HashSet() starRowMap[sitReport.star_id] = positions positions.plus(i) } notifyDataSetChanged() } fun onStarUpdated(star: Star) { val positions = starRowMap[star.id] if (positions != null) { for (position in positions) { notifyItemChanged(position) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SitReportViewHolder { val view = layoutInflater.inflate(viewType, parent, false) return SitReportViewHolder(viewType, view) } override fun getItemCount(): Int { return rows.size } override fun getItemViewType(position: Int): Int { return when { rows[position].date != null -> R.layout.sitreport_row_day else -> R.layout.sitreport_row } } override fun onBindViewHolder(holder: SitReportViewHolder, position: Int) { holder.bind(rows[position]) } class SitReportViewHolder(viewType: Int, itemView: View) : RecyclerView.ViewHolder(itemView) { private val dateViewBinding: DateViewBinding? private val sitReportViewBinding: SitReportViewBinding? init { if (viewType == R.layout.sitreport_row_day) { dateViewBinding = DateViewBinding(itemView) sitReportViewBinding = null } else { dateViewBinding = null sitReportViewBinding = SitReportViewBinding(itemView) } } fun bind(row: RowData) { when { row.date != null -> dateViewBinding!!.bind(row.date) row.sitReport != null -> sitReportViewBinding!!.bind(row.sitReport) } } } class DateViewBinding(view: View) { private val dateView: TextView = view as TextView fun bind(date: LocalDate) { // TODO: special-case TODAY and YESTERDAY dateView.text = date.format(dateFormat) } } class SitReportViewBinding(view: View) { private val timeView: TextView = view.findViewById(R.id.time) private val starIconView: ImageView = view.findViewById(R.id.star_icon) private val designIconView: ImageView = view.findViewById(R.id.design_icon) private val reportTitleView: TextView = view.findViewById(R.id.report_title) private val reportDetailsView: TextView = view.findViewById(R.id.report_details) fun bind(sitReport: SituationReport) { val res = timeView.context.resources val reportTime = LocalDateTime.ofEpochSecond(sitReport.report_time / 1000, 0, ZoneOffset.UTC).toLocalTime() timeView.text = reportTime.format(timeFormat) val star = StarManager.getStar(sitReport.star_id) if (star != null) { ImageHelper.bindStarIcon(starIconView, star) } val design: Design? val buildCompleteReport = sitReport.build_complete_record val moveCompleteReport = sitReport.move_complete_record when { buildCompleteReport != null -> { design = DesignHelper.getDesign(buildCompleteReport.design_type) reportTitleView.text = fromHtml(res.getString(R.string.build_complete, star?.name ?: "...")) if (design.design_kind == Design.DesignKind.SHIP) { // TODO: handle was_destroyed when we have it. reportDetailsView.text = res.getString( R.string.fleet_details_not_destroyed, buildCompleteReport.count.toFloat(), design.display_name) } else { reportDetailsView.text = res.getString(R.string.build_details, design.display_name) } } moveCompleteReport != null -> { design = DesignHelper.getDesign(moveCompleteReport.design_type) reportTitleView.text = fromHtml(res.getString(R.string.fleet_move_complete, star?.name ?: "...")) val resId = if (design.design_kind == Design.DesignKind.SHIP && moveCompleteReport.was_destroyed) { R.string.fleet_details_destroyed } else /* if (design.design_kind == Design.DesignKind.SHIP) */ { R.string.fleet_details_not_destroyed } reportDetailsView.text = res.getString(resId, moveCompleteReport.num_ships, design.display_name) } else -> { design = null reportTitleView.text = fromHtml(res.getString(R.string.attack_on_star, star?.name ?: "...")) } } if (design != null) { BuildViewHelper.setDesignIcon(design, designIconView) } } } data class RowData(val date: LocalDate?, val sitReport: SituationReport?) }
mit
takuji31/Dagger2Android
dagger2android/src/main/java/jp/takuji31/dagger2android/ComponentStore.kt
1
141
package jp.takuji31.dagger2android /** * @author Takuji Nishibayashi */ public interface ComponentStore<T : Any> { var component: T? }
apache-2.0
Undin/intellij-rust
src/test/kotlin/org/rust/lang/core/stubs/RsBlockStubTest.kt
2
3098
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.stubs import com.intellij.psi.impl.DebugUtil import org.intellij.lang.annotations.Language import org.rust.RsTestBase import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.block import org.rust.lang.core.psi.ext.childOfType import org.rust.lang.core.resolve2.util.buildStub class RsBlockStubTest : RsTestBase() { fun `test empty`() = doTest(""" fn f() {} """, """ BLOCK:RsPlaceholderStub """) fun `test not stubbed`() = doTest(""" fn f() { 0; let x = 1; func(); impl Foo {} // block expr { 1 } } """, """ BLOCK:RsPlaceholderStub """) fun `test imports`() = doTest(""" fn f() { use foo1::item1; use foo2::item2 as item3; use foo3::{item4, item5}; } """, """ BLOCK:RsPlaceholderStub USE_ITEM:RsUseItemStub USE_SPECK:RsUseSpeckStub PATH:RsPathStub PATH:RsPathStub USE_ITEM:RsUseItemStub USE_SPECK:RsUseSpeckStub PATH:RsPathStub PATH:RsPathStub ALIAS:RsAliasStub USE_ITEM:RsUseItemStub USE_SPECK:RsUseSpeckStub PATH:RsPathStub USE_GROUP:RsPlaceholderStub USE_SPECK:RsUseSpeckStub PATH:RsPathStub USE_SPECK:RsUseSpeckStub PATH:RsPathStub """) fun `test items`() = doTest(""" fn f() { fn func(a: i32) -> i32 { 0 } struct Struct1; struct Struct2(i32); struct Struct3 { a: i32 } enum E { E1, E2(i32), E3 { a: i32 }, } } """, """ BLOCK:RsPlaceholderStub FUNCTION:RsFunctionStub STRUCT_ITEM:RsStructItemStub STRUCT_ITEM:RsStructItemStub STRUCT_ITEM:RsStructItemStub ENUM_ITEM:RsEnumItemStub ENUM_BODY:RsPlaceholderStub ENUM_VARIANT:RsEnumVariantStub ENUM_VARIANT:RsEnumVariantStub ENUM_VARIANT:RsEnumVariantStub """) fun `test macros`() = doTest(""" fn f() { macro macro1() { 1 } macro_rules! macro2 { () => { 1 }; } macro1!(1); } """, """ BLOCK:RsPlaceholderStub MACRO_2:RsMacro2Stub MACRO:RsMacroStub MACRO_CALL:RsMacroCallStub PATH:RsPathStub """) private fun doTest(@Language("Rust") code: String, expectedStubText: String) { InlineFile(code) val file = myFixture.file val block = file.childOfType<RsFunction>()!!.block!! val stub = block.buildStub()!! val stubText = DebugUtil.stubTreeToString(stub) assertEquals(expectedStubText.trimIndent() + "\n", stubText) } }
mit
Undin/intellij-rust
src/test/kotlin/org/rust/ide/hints/RsQuickDefinitionTest.kt
4
4104
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints import com.intellij.codeInsight.hint.ImplementationViewSession import com.intellij.codeInsight.hint.actions.ShowImplementationsAction import com.intellij.openapi.editor.ex.EditorEx import org.intellij.lang.annotations.Language import org.rust.RsTestBase class RsQuickDefinitionTest : RsTestBase() { fun `test struct`() = doTest(""" struct Foo { bar: i32 } fn bar(foo: Foo/*caret*/) {} """, """ struct Foo { bar: i32 } """) fun `test enum`() = doTest(""" enum Foo { L, R(i32) } fn bar(foo: Foo/*caret*/) {} """, """ enum Foo { L, R(i32) } """) fun `test trait`() = doTest(""" trait Foo { fn bar(&self); } fn bar<T: Foo/*caret*/>(foo: T) {} """, """ trait Foo { fn bar(&self); } """) fun `test type alias`() = doTest(""" type Foo = &'static str; fn bar(foo: Foo/*caret*/) {} """, """ type Foo = &'static str; """) fun `test const`() = doTest(""" const FOO: &'static [&str] = [ "some test text", "another test text" ]; fn main() { FOO/*caret*/; } """, """ const FOO: &'static [&str] = [ "some test text", "another test text" ]; """) fun `test function`() = doTest(""" fn foo() { } fn main() { foo/*caret*/(); } """, """ fn foo() { } """) fun `test method`() = doTest(""" struct Foo; impl Foo { fn foo(&self) { } } fn bar(foo: Foo) { foo.foo/*caret*/(); } """, """ fn foo(&self) { } """) fun `test field`() = doTest(""" struct Foo { bar: i32 } fn bar(foo: Foo) { foo.bar/*caret*/; } """, """ bar: i32 """) fun `test let binding`() = doTest(""" fn main() { let a = " Some text "; a/*caret*/; } """, """ let a = " Some text "; """) fun `test destructuring let binding`() = doTest(""" fn main() { let (a, b) = (" Some text ", 123); a/*caret*/; } """, """ let (a, b) = (" Some text ", 123); """) fun `test match arm`() = doTest(""" enum Foo { L, R(i32) } fn bar(foo: Foo) { match foo { L => {}, R(x) => { x/*caret*/; } } } """, """ R(x) => { x; } """) private fun doTest(@Language("Rust") code: String, expectedRaw: String) { InlineFile(code) val actualText = performShowImplementationAction() checkNotNull(actualText) val expected = expectedRaw.lines() .dropWhile { it.isBlank() } .dropLastWhile { it.isBlank() } .joinToString("\n") assertEquals(expected, actualText) } private fun performShowImplementationAction(): String? { var actualText: String? = null val action = object : ShowImplementationsAction() { override fun showImplementations(session: ImplementationViewSession, invokedFromEditor: Boolean, invokedByShortcut: Boolean) { if (session.implementationElements.isEmpty()) return actualText = session.implementationElements[0].text } } action.performForContext((myFixture.editor as EditorEx).dataContext) return actualText } }
mit
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/lints/RsUnnecessaryQualificationsInspection.kt
2
4663
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.parentOfType import org.rust.ide.inspections.RsProblemsHolder import org.rust.ide.inspections.fixes.SubstituteTextFix import org.rust.lang.core.parser.RustParserUtil import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.TYPES_N_VALUES_N_MACROS class RsUnnecessaryQualificationsInspection : RsLintInspection() { override fun getLint(element: PsiElement): RsLint = RsLint.UnusedQualifications override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() { override fun visitPath(path: RsPath) { val shouldCheckPath = path.parentOfType<RsUseItem>() == null && path.parentOfType<RsVisRestriction>() == null && path.rootPath() == path && path.canBeShortened() if (shouldCheckPath) { val target = getUnnecessarilyQualifiedPath(path) if (target != null) { val pathRestStart = target.referenceNameElement!!.startOffset val unnecessaryLength = pathRestStart - path.startOffset val range = TextRange(0, unnecessaryLength) val fix = SubstituteTextFix.delete( "Remove unnecessary path prefix", path.containingFile, TextRange(path.startOffset, pathRestStart) ) holder.registerLintProblem(path, "Unnecessary qualification", range, RsLintHighlightingType.UNUSED_SYMBOL, listOf(fix)) } } super.visitPath(path) } } /** * Consider a path like `a::b::c::d`. * We will try to walk it from the "root" (the rightmost sub-path). * First we try `d`, then `c::d`, then `b::c::d`, etc. * Once we find a path that can be resolved and which is shorter than the original path, we will return it. */ private fun getUnnecessarilyQualifiedPath(path: RsPath): RsPath? { if (path.resolveStatus == PathResolveStatus.UNRESOLVED) return null val target = path.reference?.resolve() ?: return null // From `a::b::c::d` generates paths `a::b::c::d`, `a::b::c`, `a::b` and `a`. val subPaths = generateSequence(path) { it.qualifier }.toList() // If any part of the path has type qualifiers/arguments, we don't want to erase parts of that path to the // right of the type, because the qualifiers/arguments can be important for type inference. val lastSubPathWithType = subPaths.indexOfLast { it.typeQual != null || it.typeArgumentList != null } .takeIf { it != -1 } ?: 0 val rootPathText = subPaths.getOrNull(0)?.referenceName ?: return null // From `a::b::c::d` generates strings `d`, `c::d`, `b::c::d`, `a::b::c::d`. val pathTexts = subPaths.drop(1).runningFold(rootPathText) { accumulator, subPath -> "${subPath.referenceName}::$accumulator" } val basePath = path.basePath() for ((subPath, subPathText) in subPaths.zip(pathTexts).drop(lastSubPathWithType)) { val fragment = RsPathCodeFragment( path.project, subPathText, false, path, RustParserUtil.PathParsingMode.TYPE, TYPES_N_VALUES_N_MACROS ) // If the subpath is resolvable, we want to ignore it if it is the last fragment ("base") of the original path. // However, leading `::` has to be handled in a special way. // If `a::b::c::d` resolves to the same item as `::a::b::c::d`, we don't want to ignore `a`. // To recognize this, we check if the current path corresponds to the base path, and if the base path // doesn't have a leading `::`. In that case, the paths are the same and there's nothing to shorten. // On the other hand, `subPathText` will never have a leading `::`, so if the base path has `::` and `a` // resolves to the same thing as `::a`, we can still shorten the path. val sameAsBase = subPath == basePath && !basePath.hasColonColon if (fragment.path?.reference?.resolve() == target && !sameAsBase) { return subPath } } return null } } private fun RsPath.canBeShortened(): Boolean { return path != null || coloncolon != null }
mit
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/crash/CrashReportFileMgr.kt
1
434
package com.exyui.android.debugbottle.components.crash import com.exyui.android.debugbottle.components.DTReportMgr import com.exyui.android.debugbottle.components.DTSettings /** * Created by yuriel on 9/13/16. */ internal object CrashReportFileMgr : DTReportMgr() { override val TAG: String = "CrashReportFileMgr" override val logPath: String = DTSettings.crashFileStorePath override val filePrefix: String = "crash" }
apache-2.0
charleskorn/batect
app/src/main/kotlin/batect/docker/pull/DockerRegistryCredentialsProvider.kt
1
1248
/* Copyright 2017-2020 Charles Korn. 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 batect.docker.pull class DockerRegistryCredentialsProvider( private val domainResolver: DockerRegistryDomainResolver, private val indexResolver: DockerRegistryIndexResolver, private val configurationFile: DockerRegistryCredentialsConfigurationFile ) { fun getCredentials(imageName: String): DockerRegistryCredentials? { val domain = domainResolver.resolveDomainForImage(imageName) val index = indexResolver.resolveRegistryIndex(domain) val source = configurationFile.getCredentialsForRegistry(index) if (source == null) { return null } return source.load() } }
apache-2.0
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/notifications/QuestInvitationData.kt
1
148
package com.habitrpg.android.habitica.models.notifications open class QuestInvitationData : NotificationData { var questKey: String? = null }
gpl-3.0
androidx/androidx
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/util/BoundaryNodes.kt
3
1071
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.util import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag @Composable fun BoundaryNode( testTag: String, content: @Composable () -> Unit ) { Column(Modifier.testTag(testTag)) { content() } } @Composable fun BoundaryNode( testTag: String ) { Column(Modifier.testTag(testTag)) {} }
apache-2.0
cat-in-the-dark/GamesServer
lib-libgdx/src/main/kotlin/org/catinthedark/shared/libgdx/control/Control.kt
1
5032
package org.catinthedark.shared.libgdx.control import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.controllers.Controller import com.badlogic.gdx.controllers.ControllerAdapter import com.badlogic.gdx.controllers.Controllers import com.badlogic.gdx.controllers.PovDirection import org.slf4j.LoggerFactory object Control { enum class Type { KEYBOARD, CONTROLLER } enum class Button { UP, DOWN, LEFT, RIGHT, BUTTON0, BUTTON1, BUTTON2, BUTTON3 } private val logger = LoggerFactory.getLogger(javaClass) private val types = mutableSetOf<Type>(Type.KEYBOARD) private var controller: Controller? = null init { val controllers = Controllers.getControllers() if (controllers.size > 0) { controller = controllers[0] types.add(Type.CONTROLLER) logger.info("Controller found: {}", controller?.name) } Controllers.addListener(object : ControllerAdapter() { override fun connected(controller: Controller?) { Control.controller = controller types.add(Type.CONTROLLER) logger.info("Controller connected: {}", Control.controller?.name) } override fun disconnected(controller: Controller?) { Control.controller = null types.remove(Type.CONTROLLER) logger.info("Controller disconnected: {}", controller?.name) } }) } fun avaiableTypes(): Set<Type> { return types } fun pressed(): Set<Button> { val controllerPressed = controllerButtons(*Button.values()) val keyboardPressed = keyboardButtons(*Button.values()) return controllerPressed union keyboardPressed } fun isPressed(vararg buttons: Button): Boolean { val controllerPressed = buttons intersect controllerButtons(*buttons) val keyboardPressed = buttons intersect keyboardButtons(*buttons) return (controllerPressed union keyboardPressed).size == buttons.size } private fun controllerButtons(vararg buttons: Button): Set<Button> { if (controller == null) { return setOf() } val pressedButtons = mutableSetOf<Button>() val direction = controller?.getPov(0) pressedButtons.addAll(when (direction) { PovDirection.center -> setOf() PovDirection.east -> setOf(Button.RIGHT) PovDirection.north -> setOf(Button.UP) PovDirection.northEast -> setOf(Button.UP, Button.RIGHT) PovDirection.northWest -> setOf(Button.UP, Button.LEFT) PovDirection.south -> setOf(Button.DOWN) PovDirection.southEast -> setOf(Button.DOWN, Button.RIGHT) PovDirection.southWest -> setOf(Button.DOWN, Button.LEFT) PovDirection.west -> setOf(Button.LEFT) else -> setOf() }) val axis0 = controller?.getAxis(0) val axis1 = controller?.getAxis(1) for (button in buttons) { when (button) { Button.LEFT -> if (axis0 != null && axis0 < -0.5) pressedButtons.add(button) Button.RIGHT -> if (axis0 != null && axis0 > 0.5) pressedButtons.add(button) Button.UP -> if (axis1 != null && axis1 < -0.5) pressedButtons.add(button) Button.DOWN -> if (axis1 != null && axis1 > 0.5) pressedButtons.add(button) else -> { } } } for (button in buttons) { val buttonCode = when (button) { Button.BUTTON0 -> 0 Button.BUTTON1 -> 1 Button.BUTTON2 -> 2 Button.BUTTON3 -> 3 else -> -1 } if (controller?.getButton(buttonCode) ?: false) { pressedButtons.add(button) } } return pressedButtons } private fun keyboardButtons(vararg buttons: Button): Set<Button> { val pressedButtons = mutableSetOf<Button>() for (button in buttons) { val keyCodes = when (button) { Button.UP -> setOf(Input.Keys.W, Input.Keys.UP, Input.Keys.DPAD_UP) Button.DOWN -> setOf(Input.Keys.S, Input.Keys.DOWN, Input.Keys.DPAD_DOWN) Button.LEFT -> setOf(Input.Keys.A, Input.Keys.LEFT, Input.Keys.DPAD_LEFT) Button.RIGHT -> setOf(Input.Keys.D, Input.Keys.RIGHT, Input.Keys.DPAD_RIGHT) Button.BUTTON0 -> setOf(Input.Keys.SPACE, Input.Keys.DPAD_CENTER) Button.BUTTON1 -> setOf(Input.Keys.SHIFT_LEFT) Button.BUTTON2 -> setOf(Input.Keys.SHIFT_RIGHT) Button.BUTTON3 -> setOf(Input.Keys.ENTER) } for (keyCode in keyCodes) { if (Gdx.input.isKeyPressed(keyCode)) { pressedButtons.add(button) } } } return pressedButtons } }
mit
noemus/kotlin-eclipse
kotlin-eclipse-ui-test/testData/completion/basic/java/TopLevelFromStandardLibraryWithoutParam.kt
1
272
package testing fun someFun() { defaultDocumentBuilderFa<caret> } // Important: This test checks that completion will find top level functions from jars. // If you going to update it make sure that methods are not auto-imported // EXIST: defaultDocumentBuilderFactory
apache-2.0
edx/edx-app-android
OpenEdXMobile/src/main/java/org/edx/mobile/module/prefs/RemoteFeaturePrefs.kt
1
500
package org.edx.mobile.module.prefs import android.content.Context import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteFeaturePrefs @Inject constructor(context: Context) { private val pref: PrefManager = PrefManager(context, PrefManager.Pref.REMOTE_FEATURES) fun setValuePropEnabled(isEnabled: Boolean) { pref.put(PrefManager.Key.VALUE_PROP, isEnabled) } fun isValuePropEnabled(): Boolean = pref.getBoolean(PrefManager.Key.VALUE_PROP, false) }
apache-2.0
handstandsam/ShoppingApp
app/src/main/java/com/handstandsam/shoppingapp/compose/Theme.kt
1
3108
package com.handstandsam.shoppingapp.compose import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Shapes import androidx.compose.material.Typography import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.handstandsam.shoppingapp.R private val appFontFamily = FontFamily( fonts = listOf( Font( resId = R.font.roboto_black, weight = FontWeight.W900, style = FontStyle.Normal ), Font( resId = R.font.roboto_black_italic, weight = FontWeight.W900, style = FontStyle.Italic ), Font( resId = R.font.roboto_bold, weight = FontWeight.W700, style = FontStyle.Normal ) ) ) private val defaultTypography = Typography() val appTypography = Typography( h1 = defaultTypography.h1.copy(fontFamily = appFontFamily), h2 = defaultTypography.h2.copy(fontFamily = appFontFamily), h3 = defaultTypography.h3.copy(fontFamily = appFontFamily), h4 = defaultTypography.h4.copy(fontFamily = appFontFamily), h5 = defaultTypography.h5.copy(fontFamily = appFontFamily), h6 = defaultTypography.h6.copy(fontFamily = appFontFamily), subtitle1 = defaultTypography.subtitle1.copy(fontFamily = appFontFamily), subtitle2 = defaultTypography.subtitle2.copy(fontFamily = appFontFamily), body1 = defaultTypography.body1.copy(fontFamily = appFontFamily), body2 = defaultTypography.body2.copy(fontFamily = appFontFamily), button = defaultTypography.button.copy(fontFamily = appFontFamily), caption = defaultTypography.caption.copy(fontFamily = appFontFamily), overline = defaultTypography.overline.copy(fontFamily = appFontFamily) ) private val dark = darkColors( // primary = purple200, // primaryVariant = purple700, // secondary = teal200 ) private val light = lightColors( // background = Color.White, // secondary = teal200, // background = Color.LightGray /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) val shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) ) @Composable fun MyApplicationTheme( isSystemInDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (isSystemInDarkTheme) dark else light MaterialTheme( colors = colors, typography = appTypography, shapes = shapes, content = content ) }
apache-2.0
CruGlobal/android-gto-support
gto-support-db/src/test/kotlin/org/ccci/gto/android/common/db/AbstractDaoClassInvalidationTest.kt
2
3618
package org.ccci.gto.android.common.db import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteTransactionListener import java.util.Stack import org.ccci.gto.android.common.db.model.Model1 import org.ccci.gto.android.common.db.model.Model2 import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.collection.IsEmptyCollection.empty import org.hamcrest.collection.IsIterableContainingInOrder.contains import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.whenever class AbstractDaoClassInvalidationTest : BaseAbstractDaoTest() { @Before fun setupDao() { db.mockTransactions() } @Test fun verifyInvalidateClassWithoutTransaction() { dao.invalidate(Model1::class.java) assertThat(dao.invalidatedClasses, contains(Model1::class.java)) } @Test fun verifyInvalidateClassWithSingleTransaction() { dao.transaction { dao.invalidate(Model1::class.java) assertThat(dao.invalidatedClasses, empty()) } assertThat(dao.invalidatedClasses, contains(Model1::class.java)) } @Test fun verifyUnsuccessfulInvalidateClassWithSingleTransaction() { try { dao.transaction { dao.invalidate(Model1::class.java) assertThat(dao.invalidatedClasses, empty()) throw RuntimeException("expected") } } catch (e: RuntimeException) { assertEquals("expected", e.message) } assertThat(dao.invalidatedClasses, empty()) } @Test fun verifyUnsuccessfulInvalidateClassWithNestedTransaction() { dao.transaction { dao.invalidate(Model1::class.java) assertThat(dao.invalidatedClasses, empty()) try { dao.transaction { dao.invalidate(Model2::class.java) assertThat(dao.invalidatedClasses, empty()) throw RuntimeException("expected") } } catch (e: RuntimeException) { assertEquals("expected", e.message) } assertThat(dao.invalidatedClasses, empty()) } assertThat(dao.invalidatedClasses, empty()) } private fun SQLiteDatabase.mockTransactions() { val listeners = Stack<SQLiteTransactionListener?>() val successful = Stack<Boolean>() val childFailed = Stack<Boolean>() whenever(beginTransactionWithListener(any())) doAnswer { listeners.push(it.arguments[0] as? SQLiteTransactionListener) successful.push(false) childFailed.push(false) listeners.peek()?.onBegin() } whenever(setTransactionSuccessful()) doAnswer { successful.pop() successful.push(true) Unit } whenever(endTransaction()) doAnswer { // a transaction is successful if setTransactionSuccessful() is called and no child transactions failed val success = successful.pop() val failedChild = childFailed.pop() if (success && !failedChild) { listeners.pop()?.onCommit() } else { // indicate that the child transaction failed if (childFailed.isNotEmpty()) { childFailed.pop() childFailed.push(true) } listeners.pop()?.onRollback() } } } }
mit
dkrivoruchko/SwitchMovie
app/src/debug/kotlin/info/dvkr/switchmovie/di/ApiKoinModule.kt
1
1190
package info.dvkr.switchmovie.di import android.net.TrafficStats import info.dvkr.switchmovie.BuildConfig import info.dvkr.switchmovie.data.repository.api.MovieApiService import okhttp3.CertificatePinner import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.dsl.module val apiKoinModule = module { single { OkHttpClient().newBuilder() .certificatePinner( CertificatePinner.Builder() .add(BuildConfig.API_BASE_DOMAIN, BuildConfig.API_BASE_DOMAIN_CERT_HASH) .build() ) .apply { if (BuildConfig.DEBUG) { addInterceptor { chain -> TrafficStats.setThreadStatsTag(50); chain.proceed(chain.request()) } addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.HEADERS }) } } .build() } single { MovieApiService( get(KoinQualifier.IO_COROUTINE_SCOPE), get(), BuildConfig.API_BASE_URL, BuildConfig.API_KEY, BuildConfig.API_BASE_IMAGE_URL ) } }
mit
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/data/dao/response/CommunitiesResponse.kt
2
940
package ru.fantlab.android.data.dao.response import com.github.kittinunf.fuel.core.ResponseDeserializable import ru.fantlab.android.data.dao.model.Community import ru.fantlab.android.provider.rest.DataManager data class CommunitiesResponse( val communitiesMain: ArrayList<Community.Main>, val communitiesAdditional: ArrayList<Community.Additional> ) { class Deserializer : ResponseDeserializable<CommunitiesResponse> { private val communitiesMain: ArrayList<Community.Main> = arrayListOf() private val communitiesAdditional: ArrayList<Community.Additional> = arrayListOf() override fun deserialize(content: String): CommunitiesResponse { val forumBlock = DataManager.gson.fromJson(content, Community::class.java) forumBlock.main.map { communitiesMain.add(it) } forumBlock.additional.map { communitiesAdditional.add(it) } return CommunitiesResponse(communitiesMain, communitiesAdditional) } } }
gpl-3.0
wordpress-mobile/AztecEditor-Android
wordpress-comments/src/test/java/org/wordpress/aztec/plugins/WordPressCommentTest.kt
1
22678
@file:Suppress("DEPRECATION") package org.wordpress.aztec.plugins import android.app.Activity import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.wordpress.aztec.AztecText import org.wordpress.aztec.Constants import org.wordpress.aztec.plugins.TestUtils.backspaceAt import org.wordpress.aztec.plugins.TestUtils.safeEmpty import org.wordpress.aztec.plugins.wpcomments.CommentsTextFormat import org.wordpress.aztec.plugins.wpcomments.WordPressCommentsPlugin import org.wordpress.aztec.plugins.wpcomments.spans.WordPressCommentSpan import org.wordpress.aztec.plugins.wpcomments.toolbar.MoreToolbarButton import org.wordpress.aztec.plugins.wpcomments.toolbar.PageToolbarButton /** * Tests for special comments ([WordPressCommentSpan.Comment.MORE] and [WordPressCommentSpan.Comment.PAGE]) */ @RunWith(RobolectricTestRunner::class) @Config(sdk = intArrayOf(25)) class WordPressCommentTest { lateinit var editText: AztecText private val HTML_COMMENT_MORE = "<!--more-->" private val HTML_COMMENT_PAGE = "<!--nextpage-->" private val HTML_LIST_ORDERED = "<ol><li>Ordered</li></ol>" private val HTML_LIST_ORDERED_SELECTED_1 = "<ol><li>Or</li></ol>" private val HTML_LIST_ORDERED_SELECTED_2 = "<ol><li>red</li></ol>" private val HTML_LIST_ORDERED_SPLIT_1 = "<ol><li>Or</li></ol>" private val HTML_LIST_ORDERED_SPLIT_2 = "<ol><li>dered</li></ol>" private val HTML_LIST_UNORDERED = "<ul><li>Unordered</li></ul>" private val HTML_LIST_UNORDERED_SELECTED_1 = "<ul><li>Un</li></ul>" private val HTML_LIST_UNORDERED_SELECTED_2 = "<ul><li>dered</li></ul>" private val HTML_LIST_UNORDERED_SPLIT_1 = "<ul><li>Un</li></ul>" private val HTML_LIST_UNORDERED_SPLIT_2 = "<ul><li>ordered</li></ul>" private val HTML_QUOTE = "<blockquote>Quote</blockquote>" private val HTML_QUOTE_SELECTED_1 = "<blockquote>Qu</blockquote>" private val HTML_QUOTE_SELECTED_2 = "<blockquote>e</blockquote>" private val HTML_QUOTE_SPLIT_1 = "<blockquote>Qu</blockquote>" private val HTML_QUOTE_SPLIT_2 = "<blockquote>ote</blockquote>" /** * Initialize variables. */ @Before fun init() { val activity = Robolectric.buildActivity(Activity::class.java).create().visible().get() editText = AztecText(activity) editText.setCalypsoMode(false) activity.setContentView(editText) editText.plugins.add(WordPressCommentsPlugin(editText)) editText.plugins.add(MoreToolbarButton(editText)) editText.plugins.add(PageToolbarButton(editText)) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment across multiple selected block elements. * If comment replaces selected text and block elements remain styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreAcrossMultipleBlocks() { Assert.assertTrue(safeEmpty(editText)) val html = HTML_LIST_ORDERED + HTML_LIST_UNORDERED + HTML_QUOTE editText.fromHtml(html) editText.setSelection(2, 20) // select between second character of ordered list and second character of quote (includes newline characters) editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_ORDERED_SELECTED_1$HTML_COMMENT_MORE$HTML_QUOTE_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment following an ordered list. * If comment is inserted and ordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreAfterOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(editText.length()) // select after list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_ORDERED$HTML_COMMENT_MORE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment following a quote. * If comment is inserted and quote remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreAfterQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(editText.length()) // select after quote editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_QUOTE$HTML_COMMENT_MORE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment following an unordered list. * If comment is inserted and unordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreAfterUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(editText.length()) // select after list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_UNORDERED$HTML_COMMENT_MORE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment preceding an ordered list. * If comment is inserted and ordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreBeforeOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.text.insert(0, "\n") backspaceAt(editText, 0) editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_COMMENT_MORE$HTML_LIST_ORDERED", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment preceding a quote. * If comment is inserted and quote remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreBeforeQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(0) // select before quote editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_COMMENT_MORE$HTML_QUOTE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment preceding an unordered list. * If comment is inserted and unordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreBeforeUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(0) // select before list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_COMMENT_MORE$HTML_LIST_UNORDERED", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment inside of ordered list. * If comment is inserted at point of selection and ordered list remains styled before and * after comment, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreInsideOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(2) // select after second character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_ORDERED_SPLIT_1$HTML_COMMENT_MORE$HTML_LIST_ORDERED_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment inside of quote. * If comment is inserted at point of selection and quote remains styled before and * after comment, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreInsideQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(2) // select after second character in quote editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_QUOTE_SPLIT_1$HTML_COMMENT_MORE$HTML_QUOTE_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment inside of unordered list. * If comment is inserted at point of selection and unordered list remains styled before and * after comment, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreInsideUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(2) // select after second character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_UNORDERED_SPLIT_1$HTML_COMMENT_MORE$HTML_LIST_UNORDERED_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment inside selected portion of ordered list. * If comment replaces selected text and ordered list remains styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreInsideSelectedOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(2, 4) // select between second and fourth character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_ORDERED_SELECTED_1$HTML_COMMENT_MORE$HTML_LIST_ORDERED_SELECTED_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment inside selected portion of quote. * If comment replaces selected text and quote remains styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreInsideSelectedQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(2, 4) // select between second and fourth character in quote editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_QUOTE_SELECTED_1$HTML_COMMENT_MORE$HTML_QUOTE_SELECTED_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.MORE] comment inside selected portion of unordered list. * If comment replaces selected text and unordered list remains styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertMoreInsideSelectedUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(2, 4) // select between second and fourth character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_MORE) Assert.assertEquals("$HTML_LIST_UNORDERED_SELECTED_1$HTML_COMMENT_MORE$HTML_LIST_UNORDERED_SELECTED_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment across multiple selected block elements. * If comment replaces selected text and block elements remain styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageAcrossMultipleBlocks() { Assert.assertTrue(safeEmpty(editText)) val html = HTML_LIST_ORDERED + HTML_LIST_UNORDERED + HTML_QUOTE editText.fromHtml(html) editText.setSelection(2, 20) // select between second character of ordered list and second character of quote (includes newline characters) editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_ORDERED_SELECTED_1$HTML_COMMENT_PAGE$HTML_QUOTE_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment following an ordered list. * If comment is inserted and ordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageAfterOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(editText.length()) // select after list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_ORDERED$HTML_COMMENT_PAGE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment following a quote. * If comment is inserted and quote remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageAfterQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(editText.length()) // select after quote editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_QUOTE$HTML_COMMENT_PAGE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment following an unordered list. * If comment is inserted and unordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageAfterUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(editText.length()) // select after list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_UNORDERED$HTML_COMMENT_PAGE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment preceding an ordered list. * If comment is inserted and ordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageBeforeOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(0) // select before list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_COMMENT_PAGE$HTML_LIST_ORDERED", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment preceding a quote. * If comment is inserted and quote remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageBeforeQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(0) // select before quote editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_COMMENT_PAGE$HTML_QUOTE", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment preceding an unordered list. * If comment is inserted and unordered list remains styled, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageBeforeUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(0) // select before list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_COMMENT_PAGE$HTML_LIST_UNORDERED", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment inside of ordered list. * If comment is inserted at point of selection and ordered list remains styled before and * after comment, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageInsideOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(2) // select after second character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_ORDERED_SPLIT_1$HTML_COMMENT_PAGE$HTML_LIST_ORDERED_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment inside of quote. * If comment is inserted at point of selection and quote remains styled before and * after comment, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageInsideQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(2) // select after second character in quote editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_QUOTE_SPLIT_1$HTML_COMMENT_PAGE$HTML_QUOTE_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment inside of unordered list. * If comment is inserted at point of selection and unordered list remains styled before and * after comment, [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageInsideUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(2) // select after second character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_UNORDERED_SPLIT_1$HTML_COMMENT_PAGE$HTML_LIST_UNORDERED_SPLIT_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment inside selected portion of ordered list. * If comment replaces selected text and ordered list remains styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageInsideSelectedOrderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_ORDERED) editText.setSelection(2, 4) // select between second and fourth character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_ORDERED_SELECTED_1$HTML_COMMENT_PAGE$HTML_LIST_ORDERED_SELECTED_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment inside selected portion of quote. * If comment replaces selected text and quote remains styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageInsideSelectedQuote() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_QUOTE) editText.setSelection(2, 4) // select between second and fourth character in quote editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_QUOTE_SELECTED_1$HTML_COMMENT_PAGE$HTML_QUOTE_SELECTED_2", editText.toHtml()) } /** * Insert [WordPressCommentSpan.Comment.PAGE] comment inside selected portion of unordered list. * If comment replaces selected text and unordered list remains styled before and after comment, * [AztecText] is correct. * * @throws Exception */ @Test @Throws(Exception::class) fun insertPageInsideSelectedUnorderedList() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_LIST_UNORDERED) editText.setSelection(2, 4) // select between second and fourth character in list editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_LIST_UNORDERED_SELECTED_1$HTML_COMMENT_PAGE$HTML_LIST_UNORDERED_SELECTED_2", editText.toHtml()) } @Test @Throws(Exception::class) fun insertTwoPageSpecialThenAddNewlinesInBetweenComments() { Assert.assertTrue(safeEmpty(editText)) editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals(HTML_COMMENT_PAGE, editText.toHtml()) val index = editText.length() editText.toggleFormatting(CommentsTextFormat.FORMAT_PAGE) Assert.assertEquals("$HTML_COMMENT_PAGE$HTML_COMMENT_PAGE", editText.toHtml()) editText.text.insert(index, Constants.NEWLINE_STRING) Assert.assertEquals("$HTML_COMMENT_PAGE<br>$HTML_COMMENT_PAGE", editText.toHtml()) editText.fromHtml(editText.toHtml()) Assert.assertEquals("${Constants.MAGIC_CHAR}\n\n${Constants.MAGIC_CHAR}", editText.text.toString()) Assert.assertEquals("$HTML_COMMENT_PAGE<br>$HTML_COMMENT_PAGE", editText.toHtml()) editText.text.insert(index, Constants.NEWLINE_STRING) Assert.assertEquals("$HTML_COMMENT_PAGE<br><br>$HTML_COMMENT_PAGE", editText.toHtml()) editText.fromHtml(editText.toHtml()) } @Test @Throws(Exception::class) fun addNewlinesAroundSpecialComments() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml("a$HTML_COMMENT_PAGE<br>$HTML_COMMENT_PAGE" + "b") editText.text.insert(1, Constants.NEWLINE_STRING) editText.text.insert(editText.length() - 1, Constants.NEWLINE_STRING) Assert.assertEquals("a<br><br>$HTML_COMMENT_PAGE<br>$HTML_COMMENT_PAGE<br>b", editText.toHtml()) editText.fromHtml(editText.toHtml()) Assert.assertEquals("a\n\n${Constants.MAGIC_CHAR}\n\n${Constants.MAGIC_CHAR}\n\nb", editText.text.toString()) } @Test @Throws(Exception::class) fun testInsertionRightNextToSpecialComments() { Assert.assertTrue(safeEmpty(editText)) editText.fromHtml(HTML_COMMENT_MORE) editText.setSelection(editText.length()) editText.text.append("b") Assert.assertEquals(HTML_COMMENT_MORE + "b", editText.toHtml()) editText.text.insert(0, "a") Assert.assertEquals("a" + HTML_COMMENT_MORE + "b", editText.toHtml()) Assert.assertEquals("a\n${Constants.MAGIC_CHAR}\nb", editText.text.toString()) } }
mpl-2.0
inorichi/tachiyomi-extensions
multisrc/overrides/mangacatalog/readsololevelingmangamanhwaonline/src/ReadSoloLevelingMangaManhwaOnline.kt
1
592
package eu.kanade.tachiyomi.extension.en.readsololevelingmangamanhwaonline import eu.kanade.tachiyomi.multisrc.mangacatalog.MangaCatalog import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.util.asJsoup class ReadSoloLevelingMangaManhwaOnline : MangaCatalog("Read Solo Leveling Manga Manhwa Online", "https://readsololeveling.org", "en") { override val sourceList = listOf( Pair("Solo Leveling", "$baseUrl/manga/solo-leveling/"), Pair("Light Novel", "$baseUrl/manga/solo-leveling-novel/"), ).sortedBy { it.first }.distinctBy { it.second } }
apache-2.0
googleads/googleads-mobile-android-examples
kotlin/admob/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopenexample/MyApplication.kt
1
8687
package com.google.android.gms.example.appopenexample import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import androidx.lifecycle.ProcessLifecycleOwner import androidx.multidex.MultiDexApplication import com.google.android.gms.ads.AdError import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.MobileAds import com.google.android.gms.ads.appopen.AppOpenAd import com.google.android.gms.ads.appopen.AppOpenAd.AppOpenAdLoadCallback import java.util.Date private const val AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294" private const val LOG_TAG = "MyApplication" /** Application class that initializes, loads and show ads when activities change states. */ class MyApplication : MultiDexApplication(), Application.ActivityLifecycleCallbacks, LifecycleObserver { private lateinit var appOpenAdManager: AppOpenAdManager private var currentActivity: Activity? = null override fun onCreate() { super.onCreate() registerActivityLifecycleCallbacks(this) // Log the Mobile Ads SDK version. Log.d(LOG_TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion()) MobileAds.initialize(this) {} ProcessLifecycleOwner.get().lifecycle.addObserver(this) appOpenAdManager = AppOpenAdManager() } /** LifecycleObserver method that shows the app open ad when the app moves to foreground. */ @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onMoveToForeground() { // Show the ad (if available) when the app moves to foreground. currentActivity?.let { appOpenAdManager.showAdIfAvailable(it) } } /** ActivityLifecycleCallback methods. */ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) { // An ad activity is started when an ad is showing, which could be AdActivity class from Google // SDK or another activity class implemented by a third party mediation partner. Updating the // currentActivity only when an ad is not showing will ensure it is not an ad activity, but the // one that shows the ad. if (!appOpenAdManager.isShowingAd) { currentActivity = activity } } override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} /** * Shows an app open ad. * * @param activity the activity that shows the app open ad * @param onShowAdCompleteListener the listener to be notified when an app open ad is complete */ fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) { // We wrap the showAdIfAvailable to enforce that other classes only interact with MyApplication // class. appOpenAdManager.showAdIfAvailable(activity, onShowAdCompleteListener) } /** * Interface definition for a callback to be invoked when an app open ad is complete (i.e. * dismissed or fails to show). */ interface OnShowAdCompleteListener { fun onShowAdComplete() } /** Inner class that loads and shows app open ads. */ private inner class AppOpenAdManager { private var appOpenAd: AppOpenAd? = null private var isLoadingAd = false var isShowingAd = false /** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */ private var loadTime: Long = 0 /** * Load an ad. * * @param context the context of the activity that loads the ad */ fun loadAd(context: Context) { // Do not load ad if there is an unused ad or one is already loading. if (isLoadingAd || isAdAvailable()) { return } isLoadingAd = true val request = AdRequest.Builder().build() AppOpenAd.load( context, AD_UNIT_ID, request, AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, object : AppOpenAdLoadCallback() { /** * Called when an app open ad has loaded. * * @param ad the loaded app open ad. */ override fun onAdLoaded(ad: AppOpenAd) { appOpenAd = ad isLoadingAd = false loadTime = Date().time Log.d(LOG_TAG, "onAdLoaded.") Toast.makeText(context, "onAdLoaded", Toast.LENGTH_SHORT).show() } /** * Called when an app open ad has failed to load. * * @param loadAdError the error. */ override fun onAdFailedToLoad(loadAdError: LoadAdError) { isLoadingAd = false Log.d(LOG_TAG, "onAdFailedToLoad: " + loadAdError.message) Toast.makeText(context, "onAdFailedToLoad", Toast.LENGTH_SHORT).show() } } ) } /** Check if ad was loaded more than n hours ago. */ private fun wasLoadTimeLessThanNHoursAgo(numHours: Long): Boolean { val dateDifference: Long = Date().time - loadTime val numMilliSecondsPerHour: Long = 3600000 return dateDifference < numMilliSecondsPerHour * numHours } /** Check if ad exists and can be shown. */ private fun isAdAvailable(): Boolean { // Ad references in the app open beta will time out after four hours, but this time limit // may change in future beta versions. For details, see: // https://support.google.com/admob/answer/9341964?hl=en return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4) } /** * Show the ad if one isn't already showing. * * @param activity the activity that shows the app open ad */ fun showAdIfAvailable(activity: Activity) { showAdIfAvailable( activity, object : OnShowAdCompleteListener { override fun onShowAdComplete() { // Empty because the user will go back to the activity that shows the ad. } } ) } /** * Show the ad if one isn't already showing. * * @param activity the activity that shows the app open ad * @param onShowAdCompleteListener the listener to be notified when an app open ad is complete */ fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) { // If the app open ad is already showing, do not show the ad again. if (isShowingAd) { Log.d(LOG_TAG, "The app open ad is already showing.") return } // If the app open ad is not available yet, invoke the callback then load the ad. if (!isAdAvailable()) { Log.d(LOG_TAG, "The app open ad is not ready yet.") onShowAdCompleteListener.onShowAdComplete() loadAd(activity) return } Log.d(LOG_TAG, "Will show ad.") appOpenAd!!.setFullScreenContentCallback( object : FullScreenContentCallback() { /** Called when full screen content is dismissed. */ override fun onAdDismissedFullScreenContent() { // Set the reference to null so isAdAvailable() returns false. appOpenAd = null isShowingAd = false Log.d(LOG_TAG, "onAdDismissedFullScreenContent.") Toast.makeText(activity, "onAdDismissedFullScreenContent", Toast.LENGTH_SHORT).show() onShowAdCompleteListener.onShowAdComplete() loadAd(activity) } /** Called when fullscreen content failed to show. */ override fun onAdFailedToShowFullScreenContent(adError: AdError) { appOpenAd = null isShowingAd = false Log.d(LOG_TAG, "onAdFailedToShowFullScreenContent: " + adError.message) Toast.makeText(activity, "onAdFailedToShowFullScreenContent", Toast.LENGTH_SHORT).show() onShowAdCompleteListener.onShowAdComplete() loadAd(activity) } /** Called when fullscreen content is shown. */ override fun onAdShowedFullScreenContent() { Log.d(LOG_TAG, "onAdShowedFullScreenContent.") Toast.makeText(activity, "onAdShowedFullScreenContent", Toast.LENGTH_SHORT).show() } } ) isShowingAd = true appOpenAd!!.show(activity) } } }
apache-2.0
BoD/CineToday
app/src/main/kotlin/org/jraf/android/cinetoday/databinding/adapters/TextViewBindingAdapter.kt
1
1298
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jraf.android.cinetoday.databinding.adapters import android.text.Html import android.widget.TextView import androidx.databinding.BindingAdapter object TextViewBindingAdapter { @JvmStatic @BindingAdapter("textHtml") fun setTextHtml(view: TextView, textHtml: String) { view.text = Html.fromHtml(textHtml, 0) } }
gpl-3.0
czyzby/ktx
tiled/src/test/kotlin/ktx/tiled/MapLayerTest.kt
2
2194
package ktx.tiled import com.badlogic.gdx.maps.MapLayer import com.badlogic.gdx.maps.MapLayers import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test class MapLayerTest { private val mapLayer = MapLayer().apply { properties.apply { put("active", true) put("customProperty", 123) } } @Test fun `should retrieve properties from MapLayer`() { assertEquals(true, mapLayer.property<Boolean>("active")) assertEquals(123, mapLayer.property<Int>("customProperty")) } @Test fun `should retrieve properties from MapLayer with default value`() { assertEquals(true, mapLayer.property("active", false)) assertEquals(123, mapLayer.property("customProperty", 0)) assertEquals(-1f, mapLayer.property("x", -1f)) } @Test fun `should retrieve properties from MapLayer without default value`() { assertNull(mapLayer.propertyOrNull("x")) assertEquals(123, mapLayer.propertyOrNull<Int>("customProperty")) } @Test fun `should check if property from MapLayer exists`() { assertTrue(mapLayer.containsProperty("active")) assertFalse(mapLayer.containsProperty("x")) } @Test(expected = MissingPropertyException::class) fun `should not retrieve non-existing property from MapLayer`() { mapLayer.property<String>("non-existing") } @Test fun `should return true when MapLayers is empty`() { val actual = MapLayers() assertTrue(actual.isEmpty()) } @Test fun `should return false when MapLayers is not empty`() { val actual = MapLayers() actual.add(MapLayer()) assertFalse(actual.isEmpty()) } @Test fun `should return true when MapLayers becomes empty`() { val actual = MapLayers() actual.add(MapLayer()) actual.remove(0) assertTrue(actual.isEmpty()) } @Test fun `should return true when MapLayers is not empty`() { val actual = MapLayers() actual.add(MapLayer()) assertTrue(actual.isNotEmpty()) } @Test fun `should return false when MapLayers is empty`() { val actual = MapLayers() assertFalse(actual.isNotEmpty()) } }
cc0-1.0
PropaFramework/Propa
src/main/kotlin/io/propa/framework/common/Delegates.kt
1
1142
package io.propa.framework.common import com.github.snabbdom._get import com.github.snabbdom._set import kotlin.reflect.KProperty /** * Created by gbaldeck on 6/16/2017. */ class PropaAssignOnce<T>(val exceptionMsgGet: String? = null, val exceptionMsgSet: String? = null){ private var value: T? = null operator fun getValue(thisRef: Any, property: KProperty<*>): T = value ?: throwPropaException(exceptionMsgGet ?: "Property '${property.name}' in ${thisRef::class.simpleName} has not been set.") operator fun setValue(thisRef: Any, property: KProperty<*>, value: T) = if(this.value == null) this.value = value else throwPropaException(exceptionMsgSet ?: "Property '${property.name}' in ${thisRef::class.simpleName} has already been set.") } class PropaDelegateProperty(val backingObj: () -> Any, val propertyName: String? = null){ operator fun getValue(thisRef: Any?, property: KProperty<*>): dynamic = backingObj()._get(propertyName ?: property.name) operator fun setValue(thisRef: Any?, property: KProperty<*>, value: dynamic) { backingObj()._set(propertyName ?: property.name, value) } }
mit
heinika/MyGankio
app/src/main/java/lijin/heinika/cn/mygankio/parser/ULParser.kt
1
2434
package lijin.heinika.cn.mygankio.parser import android.annotation.SuppressLint import android.content.Context import android.text.SpannableString import android.text.method.LinkMovementMethod import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.bumptech.glide.Glide import org.jsoup.Jsoup import org.jsoup.helper.StringUtil import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.nodes.Node import java.util.ArrayList import lijin.heinika.cn.mygankio.utils.SpanUtils /** * Created by yun on 2017/9/16. * ul解析 */ class ULParser : BaseParser() { private val TAG = ULParser::class.java.simpleName @SuppressLint("SetTextI18n") override fun parse(node: Node, context: Context): List<View>? { val lists = ArrayList<View>() Log.i(TAG, "parse: " + node.toString()) for (n in node.childNodes()) { val content = StringBuilder() var html = "" var src = "" val document = Jsoup.parse(n.toString()) if (document.getElementsByTag("li").size != 0) { val a = document.getElementsByTag("a")[0] content.append(a.text()).append("\n") html = a.attr("href") Log.i(TAG, "html:$html") if (document.getElementsByTag("img").size != 0) { val img = document.getElementsByTag("img")[0] src = img.attr("src") Log.i(TAG, "src:$src") } } if (!StringUtil.isBlank(content.toString())) { val textView = TextView(context) val spannableString = SpanUtils.getULSpannableString(content.toString(), html) textView.text = spannableString textView.movementMethod = LinkMovementMethod.getInstance() lists.add(textView) if (!StringUtil.isBlank(src)) { val imageView = ImageView(context) imageView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) Glide.with(context).load(src).into(imageView) lists.add(imageView) } } } return lists } }
apache-2.0
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/serviceContainer/BaseKeyedLazyInstance.kt
1
1352
/* * Copyright (C) 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.core.serviceContainer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.PluginAware import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.serviceContainer.LazyExtensionInstance abstract class BaseKeyedLazyInstance<T> : LazyExtensionInstance<T>(), PluginAware { @Transient var pluginDescriptor: PluginDescriptor? = null private set override fun setPluginDescriptor(pluginDescriptor: PluginDescriptor) { this.pluginDescriptor = pluginDescriptor } @Suppress("ReplaceNotNullAssertionWithElvisReturn") open fun getInstance(): T = getInstance(ApplicationManager.getApplication(), pluginDescriptor!!) }
apache-2.0
westnordost/osmagent
app/src/test/java/de/westnordost/streetcomplete/quests/AddProhibitedForPedestriansTest.kt
1
1357
package de.westnordost.streetcomplete.quests import de.westnordost.streetcomplete.data.osm.changes.StringMapEntryAdd import de.westnordost.streetcomplete.data.osm.changes.StringMapEntryModify import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao import de.westnordost.streetcomplete.quests.foot.AddProhibitedForPedestrians import de.westnordost.streetcomplete.quests.foot.ProhibitedForPedestriansAnswer.* import org.junit.Test import org.mockito.Mockito.mock class AddProhibitedForPedestriansTest { private val questType = AddProhibitedForPedestrians(mock(OverpassMapDataDao::class.java)) @Test fun `apply yes answer`() { questType.verifyAnswer(YES, StringMapEntryAdd("foot", "no")) } @Test fun `apply no answer`() { questType.verifyAnswer(NO, StringMapEntryAdd("foot", "yes")) } @Test fun `apply separate sidewalk answer`() { questType.verifyAnswer( mapOf("sidewalk" to "no"), HAS_SEPARATE_SIDEWALK, StringMapEntryAdd("foot", "use_sidepath"), StringMapEntryModify("sidewalk", "no", "separate") ) } @Test fun `apply living street answer`() { questType.verifyAnswer( mapOf("highway" to "residential"), IS_LIVING_STREET, StringMapEntryModify("highway", "residential", "living_street") ) } }
gpl-3.0
rhdunn/xquery-intellij-plugin
src/plugin-w3/main/uk/co/reecedunn/intellij/plugin/w3/lang/FullTextSyntaxValidator.kt
1
1810
/* * Copyright (C) 2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.w3.lang import uk.co.reecedunn.intellij.plugin.xpath.ast.full.text.FTContainsExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.full.text.FTScoreVar import uk.co.reecedunn.intellij.plugin.xpath.lang.FullTextSpec import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxErrorReporter import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidator import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires.XpmRequiresSpecificationVersion import uk.co.reecedunn.intellij.plugin.xquery.ast.full.text.FTOptionDecl object FullTextSyntaxValidator : XpmSyntaxValidator { override fun validate( element: XpmSyntaxValidationElement, reporter: XpmSyntaxErrorReporter ): Unit = when (element) { is FTContainsExpr -> reporter.requires(element, FULL_TEXT_1_0) is FTOptionDecl -> reporter.requires(element, FULL_TEXT_1_0) is FTScoreVar -> reporter.requires(element, FULL_TEXT_1_0) else -> { } } private val FULL_TEXT_1_0 = XpmRequiresSpecificationVersion(FullTextSpec.REC_1_0_20110317) }
apache-2.0
docker-client/docker-compose-v3
src/main/kotlin/de/gesellix/docker/compose/adapters/MapOrListToLabelAdapter.kt
1
1909
package de.gesellix.docker.compose.adapters import com.squareup.moshi.FromJson import com.squareup.moshi.JsonReader import com.squareup.moshi.ToJson import de.gesellix.docker.compose.types.Labels class MapOrListToLabelAdapter { @ToJson fun toJson(@LabelsType labels: Labels): Map<String, String> { throw UnsupportedOperationException() } @FromJson @LabelsType fun fromJson(reader: JsonReader): Labels { val labels = Labels() when (reader.peek()) { JsonReader.Token.BEGIN_ARRAY -> { reader.beginArray() while (reader.peek() != JsonReader.Token.END_ARRAY) { val entry = reader.nextString() val keyAndValue = entry.split(Regex("="), 2) labels.entries[keyAndValue[0]] = if (keyAndValue.size > 1) keyAndValue[1] else "" } reader.endArray() } JsonReader.Token.BEGIN_OBJECT -> { reader.beginObject() while (reader.peek() != JsonReader.Token.END_OBJECT) { val name = reader.nextName() val value: String? = if (reader.peek() == JsonReader.Token.NULL) { reader.nextNull() } else if (reader.peek() == JsonReader.Token.NUMBER) { val d = reader.nextDouble() if ((d % 1) == 0.0) { d.toInt().toString() } else { d.toString() } } else { reader.nextString() } labels.entries[name] = value ?: "" } reader.endObject() } else -> { // ... } } return labels } }
mit
fredyw/leetcode
src/main/kotlin/leetcode/Problem2085.kt
1
696
package leetcode /** * https://leetcode.com/problems/count-common-words-with-one-occurrence/ */ class Problem2085 { fun countWords(words1: Array<String>, words2: Array<String>): Int { val map1 = mutableMapOf<String, Int>() words1.forEach { map1[it] = (map1[it] ?: 0) + 1 } val map2 = mutableMapOf<String, Int>() words2.forEach { map2[it] = (map2[it] ?: 0) + 1 } var answer = 0 for ((key1, count1) in map1) { if (count1 > 1) { continue } val count2 = map2[key1] if (count2 != null && count2 == 1) { answer++ } } return answer } }
mit
jiaminglu/kotlin-native
backend.native/tests/external/codegen/boxInline/defaultValues/lambdaInlining/simple.kt
1
309
// FILE: 1.kt // SKIP_INLINE_CHECK_IN: inlineFun$default package test @Suppress("NOT_YET_SUPPORTED_IN_INLINE") inline fun inlineFun(capturedParam: String, lambda: () -> String = { capturedParam }): String { return lambda() } // FILE: 2.kt import test.* fun box(): String { return inlineFun("OK") }
apache-2.0
jiaminglu/kotlin-native
backend.native/tests/codegen/boxing/boxing15.kt
1
88
fun main(args: Array<String>) { println(foo(17)) } fun <T : Int> foo(x: T): Int = x
apache-2.0
dhleong/ideavim
test/org/jetbrains/plugins/ideavim/action/change/delete/JoinNotificationTest.kt
1
2523
@file:Suppress("RemoveCurlyBracesFromTemplate") package org.jetbrains.plugins.ideavim.action.change.delete import com.intellij.notification.EventLog import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.group.NotificationService import com.maddyhome.idea.vim.helper.StringHelper import com.maddyhome.idea.vim.option.IdeaJoinOptionsData import org.jetbrains.plugins.ideavim.VimOptionTestCase import org.jetbrains.plugins.ideavim.VimOptionTestConfiguration import org.jetbrains.plugins.ideavim.VimTestOption import org.jetbrains.plugins.ideavim.VimTestOptionType /** * @author Alex Plate */ class JoinNotificationTest : VimOptionTestCase(IdeaJoinOptionsData.name) { @VimOptionTestConfiguration(VimTestOption(IdeaJoinOptionsData.name, VimTestOptionType.TOGGLE, ["false"])) fun `test notification shown for no ideajoin`() { val before = "I found${c} it\n in a legendary land" configureByText(before) appReadySetup(false) typeText(StringHelper.parseKeys("J")) val notification = EventLog.getLogModel(myFixture.project).notifications.last() assertEquals(NotificationService.IDEAVIM_NOTIFICATION_TITLE, notification.title) assertTrue(IdeaJoinOptionsData.name in notification.content) assertEquals(3, notification.actions.size) } @VimOptionTestConfiguration(VimTestOption(IdeaJoinOptionsData.name, VimTestOptionType.TOGGLE, ["true"])) fun `test notification not shown for ideajoin`() { val before = "I found${c} it\n in a legendary land" configureByText(before) appReadySetup(false) typeText(StringHelper.parseKeys("J")) val notifications = EventLog.getLogModel(myFixture.project).notifications assertTrue(notifications.isEmpty() || notifications.last().isExpired || IdeaJoinOptionsData.name !in notifications.last().content) } @VimOptionTestConfiguration(VimTestOption(IdeaJoinOptionsData.name, VimTestOptionType.TOGGLE, ["false"])) fun `test notification not shown if was shown already`() { val before = "I found${c} it\n in a legendary land" configureByText(before) appReadySetup(true) typeText(StringHelper.parseKeys("J")) val notifications = EventLog.getLogModel(myFixture.project).notifications assertTrue(notifications.isEmpty() || notifications.last().isExpired || IdeaJoinOptionsData.name !in notifications.last().content) } private fun appReadySetup(notifierEnabled: Boolean) { EventLog.markAllAsRead(myFixture.project) VimPlugin.getVimState().isIdeaJoinNotified = notifierEnabled } }
gpl-2.0