content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package org.http4k.serverless import com.amazonaws.services.lambda.runtime.Context import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.junit.jupiter.api.Test import java.io.ByteArrayOutputStream class InvocationLambdaFunctionTest { @Test fun `adapts Direct request and response and receives context`() { val lambdaContext = LambdaContextMock("myFunction") val request = "input body" val lambda = object : InvocationLambdaFunction(AppLoaderWithContexts { env, contexts -> { assertThat(contexts[it].get<Context>(LAMBDA_CONTEXT_KEY), equalTo(lambdaContext)) assertThat(env, equalTo(System.getenv())) assertThat( it.removeHeader("x-http4k-context-lambda"), equalTo( Request(POST, "/2015-03-31/functions/myFunction/invocations") .header("X-Amz-Invocation-Type", "RequestResponse") .header("X-Amz-Log-Type", "Tail") .body(request) ) ) Response(OK).body(request + request) } }) {} assertThat( ByteArrayOutputStream().run { lambda.handleRequest(request.byteInputStream(), this, lambdaContext) toString() }, equalTo(request + request) ) } }
http4k-serverless/lambda/src/test/kotlin/org/http4k/serverless/InvocationLambdaFunctionTest.kt
1847849071
package org.http4k.traffic import org.http4k.core.HttpMessage import org.http4k.core.Request import org.http4k.core.Response /** * Combined Read/Write storage models, optimised for replay. */ interface ReadWriteStream : Sink, Replay { companion object { /** * Serialise and replay HTTP traffic to/from the FS in order. */ fun Disk(baseDir: String = ".", shouldStore: (HttpMessage) -> Boolean = { true }): ReadWriteStream = object : ReadWriteStream, Replay by Replay.DiskStream(baseDir), Sink by Sink.DiskStream(baseDir, shouldStore) {} /** * Serialise and replay HTTP traffic to/from Memory in order. */ fun Memory(stream: MutableList<Pair<Request, Response>> = mutableListOf(), shouldStore: (HttpMessage) -> Boolean = { true }): ReadWriteStream = object : ReadWriteStream, Replay by Replay.MemoryStream(stream), Sink by Sink.MemoryStream(stream, shouldStore) {} } }
http4k-core/src/main/kotlin/org/http4k/traffic/ReadWriteStream.kt
94078674
// 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.geofence import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingEvent class GeofenceBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.w(TAG(), "onReceive()") val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent.hasError()) { Log.w(TAG(), "geofence error: ${geofencingEvent.errorCode}") return } val reqId = geofencingEvent.triggeringGeofences[0].requestId val type = when(geofencingEvent.geofenceTransition) { Geofence.GEOFENCE_TRANSITION_ENTER -> "ENTER" Geofence.GEOFENCE_TRANSITION_EXIT -> "EXIT" else -> "DWELL" } Log.w(TAG(), "GEOFENCE TRIGGER(S) DETECTED for REQ ID: $reqId -- $type") GeofenceJobIntentService.addJob(context, intent) } }
geolocation/geofence/app/src/main/java/com/digitalwellbeingexperiments/toolkit/geofence/GeofenceBroadcastReceiver.kt
3796748751
package kodando.react.router.dom import kodando.react.Configurer import kodando.react.ReactProps import kodando.react.addComponent import kodando.react.createProps /** * Created by danfma on 04/04/17. */ private inline fun ReactProps.prompt(configurer: Configurer<PromptProps>) { addComponent(Module.PromptClass, createProps(configurer)) } @JsName("promptWithText") fun ReactProps.prompt(message: String, matched: Boolean = false) { prompt { this.messageText = message this.matched = matched } } @JsName("promptWithFunc") fun ReactProps.prompt(messageFactory: (Location) -> String, matched: Boolean = false) { prompt { this.messageFunc = messageFactory this.matched = matched } }
kodando-react-router-dom/src/main/kotlin/kodando/react/router/dom/Prompt.kt
2627689505
package cm.aptoide.aptoideviews.filters import android.widget.Button import androidx.core.content.ContextCompat import cm.aptoide.aptoideviews.R import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import com.fa.epoxysample.bundles.models.base.BaseViewHolder @EpoxyModelClass abstract class ClearFiltersModel : EpoxyModelWithHolder<ClearFiltersModel.CardHolder>() { @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var eventListener: FilterEventListener? = null @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var textColorStateList: Int? = null override fun bind(holder: CardHolder) { super.bind(holder) holder.clearButton.setOnClickListener { eventListener?.onFilterEvent(FilterEventListener.EventType.CLEAR_EVENT_CLICK, null) } textColorStateList?.let { color -> holder.clearButton.setTextColor( ContextCompat.getColorStateList(holder.itemView.context, color)) } } override fun getDefaultLayout(): Int { return R.layout.clear_filters_item } class CardHolder : BaseViewHolder() { val clearButton by bind<Button>(R.id.clear_button) } }
aptoide-views/src/main/java/cm/aptoide/aptoideviews/filters/ClearFiltersModel.kt
2524986510
package cat.xojan.random1.domain.interactor import android.app.DownloadManager import android.content.Context import cat.xojan.random1.data.SharedPrefDownloadPodcastRepository import cat.xojan.random1.domain.model.EventLogger import cat.xojan.random1.domain.model.Program import cat.xojan.random1.domain.model.Section import cat.xojan.random1.domain.repository.ProgramRepository import cat.xojan.random1.testutil.sectionList import io.reactivex.observers.TestObserver import org.junit.Ignore import org.junit.Test import org.mockito.Mockito.`when` import java.io.IOException class ProgramDataInteractorTest { private lateinit var mProgramRepo: ProgramRepository private lateinit var mDownloadsRepo: SharedPrefDownloadPodcastRepository private lateinit var mProgramDataInteractor: ProgramDataInteractor private lateinit var mMockContext: Context private lateinit var mDownloadManager: DownloadManager private lateinit var mEventLogger: EventLogger /*private val dummyProgram: Program get() { val program = program1 program.sections = sectionList return program } @Before fun setUp() { mProgramRepo = mock(ProgramRepository::class.java) mDownloadsRepo = mock(SharedPrefDownloadPodcastRepository::class.java) mMockContext = mock(Context::class.java) mDownloadManager = mock(DownloadManager::class.java) mEventLogger = mock(EventLogger::class.java) mProgramDataInteractor = ProgramDataInteractor(mProgramRepo, mDownloadsRepo, mMockContext, mEventLogger) } @Test @Ignore @Throws(IOException::class) fun load_programs_successfully_during_first_call() { `when`(mProgramRepo.getPrograms()).thenReturn(Single.just(programList)) val testSubscriber = TestObserver<List<Program>>() mProgramDataInteractor.loadPrograms().subscribe(testSubscriber) testSubscriber.assertValue(programList) }*/ /*@Test fun load_programs_successfully_after_first_call() { mProgramDataInteractor.programs = programList val testSubscriber = TestObserver<List<Program>>() mProgramDataInteractor.loadPrograms().subscribe(testSubscriber) testSubscriber.assertValue(programList) }*/ @Test @Ignore @Throws(IOException::class) fun fail_to_load_programs() { `when`(mProgramRepo.getPrograms(true)).thenThrow(IOException()) val testSubscriber = TestObserver<List<Program>>() mProgramDataInteractor.loadPrograms(true).subscribe(testSubscriber) testSubscriber.assertError(IOException::class.java) } @Test @Ignore fun get_sections_from_program() { val testSubscriber = TestObserver<List<Section>>() mProgramDataInteractor.loadSections("programId").subscribe(testSubscriber) testSubscriber.assertValue(sectionList) } /*@Test @Ignore @Throws(IOException::class) fun load_podcasts_by_program_successfully() { val program = dummyProgram `when`(mProgramRepo.getPodcast(anyString(), null)).thenReturn(Flowable.just(podcastList)) val testSubscriber = TestSubscriber<List<Podcast>>() mProgramDataInteractor.loadPodcasts(program, null, false).subscribe(testSubscriber) testSubscriber.assertValue(podcastList) } @Test @Throws(IOException::class) fun load_podcasts_by_section_successfully() { val program = dummyProgram val section = sectionList[0] `when`(mProgramRepo.getPodcast(anyString(), anyString())).thenReturn(Flowable.just(podcastList)) val testSubscriber = TestSubscriber<List<Podcast>>() mProgramDataInteractor.loadPodcasts(program, section, false).subscribe(testSubscriber) testSubscriber.assertValue(podcastList) } @Test @Ignore @Throws(IOException::class) fun fail_to_load_podcasts() { val program = dummyProgram `when`(mProgramRepo.getPodcast(anyString(), null)).thenThrow(IOException()) val testSubscriber = TestSubscriber<List<Podcast>>() mProgramDataInteractor.loadPodcasts(program, null, false).subscribe(testSubscriber) testSubscriber.assertError(IOException::class.java) } @Test fun add_downloaded_podcast_and_refresh_list_fail() { val testSubscriber = TestObserver<List<Podcast>>() mProgramDataInteractor.getDownloadedPodcasts().subscribe(testSubscriber) `when`(mMockContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)).thenReturn(File("downloads/")) `when`(mMockContext.getExternalFilesDir(Environment.DIRECTORY_PODCASTS)).thenReturn(File("podcasts/")) mProgramDataInteractor.addDownload("audioId1") testSubscriber.assertValue(ArrayList()) }*/ }
app/src/test/java/cat/xojan/random1/domain/interactor/ProgramDataInteractorTest.kt
2513304
package io.gitlab.arturbosch.detekt.formatting.wrappers import com.pinterest.ktlint.ruleset.standard.NoBlankLineBeforeRbraceRule import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.formatting.FormattingRule /** * See <a href="https://ktlint.github.io">ktlint-website</a> for documentation. * * @active since v1.0.0 * @autoCorrect since v1.0.0 */ class NoBlankLineBeforeRbrace(config: Config) : FormattingRule(config) { override val wrapping = NoBlankLineBeforeRbraceRule() override val issue = issueFor("Detects blank lines before rbraces") }
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/NoBlankLineBeforeRbrace.kt
4108302395
@file:Suppress("unused") package cases // reports 1 - only if ignoreSingleWhenExpression = false fun complexMethodWithSingleWhen1(i: Int) = when (i) { 1 -> print("one") 2 -> print("two") 3 -> print("three") else -> print(i) } // reports 1 - only if ignoreSingleWhenExpression = false fun complexMethodWithSingleWhen2(i: Int) { when (i) { 1 -> print("one") 2 -> print("two") 3 -> print("three") else -> print(i) } } // reports 1 - only if ignoreSingleWhenExpression = false fun complexMethodWithSingleWhen3(i: Int): String { return when (i) { 1 -> "one" 2 -> "two" 3 -> "three" else -> "" } } // reports 1 - only if ignoreSingleWhenExpression = false fun complexMethodWithSingleWhen4(i: Int) = when (i) { 1 -> "one" 2 -> "two" 3 -> "three" else -> "" } // reports 1 fun complexMethodWith2Statements(i: Int) { when (i) { 1 -> print("one") 2 -> print("two") 3 -> print("three") else -> print(i) } if (i == 1) { } }
detekt-rules/src/test/resources/cases/ComplexMethods.kt
3498298941
package de.westnordost.streetcomplete.location import android.Manifest.permission.ACCESS_FINE_LOCATION import android.location.Location import android.location.LocationManager import android.location.LocationManager.GPS_PROVIDER import android.location.LocationManager.NETWORK_PROVIDER import android.os.Looper import androidx.annotation.RequiresPermission /** Convenience wrapper around the location manager with easier API, making use of both the GPS * and Network provider */ class FineLocationManager(private val mgr: LocationManager, private var locationUpdateCallback: ((Location) -> Unit)) { private var lastLocation: Location? = null private val deviceHasGPS: Boolean get() = mgr.allProviders.contains(GPS_PROVIDER) private val deviceHasNetworkLocationProvider: Boolean get() = mgr.allProviders.contains(NETWORK_PROVIDER) private val locationListener = object : LocationUpdateListener { override fun onLocationChanged(location: Location) { if (isBetterLocation(location, lastLocation)) { lastLocation = location locationUpdateCallback(location) } } } private val singleLocationListener = object : LocationUpdateListener { override fun onLocationChanged(location: Location) { mgr.removeUpdates(this) locationUpdateCallback(location) } } @RequiresPermission(ACCESS_FINE_LOCATION) fun requestUpdates(minTime: Long, minDistance: Float) { if (deviceHasGPS) mgr.requestLocationUpdates(GPS_PROVIDER, minTime, minDistance, locationListener, Looper.getMainLooper()) if (deviceHasNetworkLocationProvider) mgr.requestLocationUpdates(NETWORK_PROVIDER, minTime, minDistance, locationListener, Looper.getMainLooper()) } @RequiresPermission(ACCESS_FINE_LOCATION) fun requestSingleUpdate() { if (deviceHasGPS) mgr.requestSingleUpdate(GPS_PROVIDER, singleLocationListener, Looper.getMainLooper()) if (deviceHasNetworkLocationProvider) mgr.requestSingleUpdate(NETWORK_PROVIDER, singleLocationListener, Looper.getMainLooper()) } fun removeUpdates() { mgr.removeUpdates(locationListener) mgr.removeUpdates(singleLocationListener) } } // taken from https://developer.android.com/guide/topics/location/strategies.html#kotlin private const val TWO_MINUTES = 1000L * 60 * 2 /** Determines whether one Location reading is better than the current Location fix * @param location The new Location that you want to evaluate * @param currentBestLocation The current Location fix, to which you want to compare the new one */ private fun isBetterLocation(location: Location, currentBestLocation: Location?): Boolean { // check whether this is a valid location at all. Happened once that lat/lon is NaN, maybe issue // of that particular device if (location.longitude.isNaN() || location.latitude.isNaN()) return false if (currentBestLocation == null) { // A new location is always better than no location return true } // Check whether the new location fix is newer or older val timeDelta = location.time - currentBestLocation.time val isSignificantlyNewer = timeDelta > TWO_MINUTES val isSignificantlyOlder = timeDelta < -TWO_MINUTES val isNewer = timeDelta > 0L // Check whether the new location fix is more or less accurate val accuracyDelta = location.accuracy - currentBestLocation.accuracy val isLessAccurate = accuracyDelta > 0f val isMoreAccurate = accuracyDelta < 0f val isSignificantlyLessAccurate = accuracyDelta > 200f // Check if the old and new location are from the same provider val isFromSameProvider = location.provider == currentBestLocation.provider // Determine location quality using a combination of timeliness and accuracy return when { // the user has likely moved isSignificantlyNewer -> return true // If the new location is more than two minutes older, it must be worse isSignificantlyOlder -> return false isMoreAccurate -> true isNewer && !isLessAccurate -> true isNewer && !isSignificantlyLessAccurate && isFromSameProvider -> true else -> false } }
app/src/main/java/de/westnordost/streetcomplete/location/FineLocationManager.kt
3909284196
package jeb import java.io.File import java.nio.file.Path import java.nio.file.Paths import java.util.* open class Storage { private val log = jeb.log open fun lastModified(dir: File, predicate: (File) -> Boolean) = dir. listFiles(). filter { predicate(it) }. maxBy { it.lastModified() } open fun fileExists(dir: File, predicate: (File) -> Boolean) = dir. listFiles(). filter(predicate). any() open fun fileExists(file: File) = file.exists() open fun remove(f: File) = f.deleteRecursively() open fun fullBackup(from: List<Source>, excludeFile: Path?, to: File) = rsync(from, excludeFile, null, to) open fun incBackup(from: List<Source>, excludeFile: Path?, base: File, to: File) = rsync(from, excludeFile, base, to) private fun rsync(sources: List<Source>, excludeFile: Path?, base: File?, dest: File) = try { // when single file is passed as source to rsync, then it's interprets // destination as full file name and do not create parent directory // but when sources is more than one or it's a directory, then it's // interprets destination as parent directory and creates it val (from, to) = if (sources.size > 1 || sources.first().path.toFile().isDirectory) { Pair(sources.map { toRsync(it) }.joinToString(" "), dest.absolutePath) } else { dest.absoluteFile.mkdirs() Pair(sources.first().absolutePath, Paths.get(dest.absolutePath, sources.first().path.fileName.toString())) } !"rsync -avh ${excludeFile?.let { "--exclude-from=" + it} ?: ""} --delete ${base?.let { "--link-dest=" + it.absolutePath } ?: ""} $from $to" } catch (e: JebExecException) { if (e.stderr.contains("vanished") && e.stderr.contains("/.sync/status")) { // it's workaround for case, when service's status file has been changed, while syncing // it's harmless and in this case follow output printed: // file has vanished: "/data/yandex-disk/.sync/status" // rsync warning: some files vanished before they could be transferred (code 24) at main.c(1183) [sender=3.1.0] // Do nothing in this case log.warn("Rsync error ignored") log.warn(e.toString()) } else { throw e } } open fun move(from: File, to: File) { !"mv ${from.absolutePath} ${to.absolutePath}" Thread.sleep(1000) // Dirty hack for functional test... to.setLastModified(System.currentTimeMillis()) } open fun findOne(dir: File, predicate: (File) -> Boolean): File? { val res = dir. listFiles(). filter(predicate) assert(res.size <= 1, { "To many files matches predicate: $res"}) return res.firstOrNull() } private fun toRsync(src: Source) = src.path.toString() + (if (src.type == BackupType.DIRECTORY) "/" else "") private operator fun String.not() { log.debug("Executing command: $this") val proc = Runtime.getRuntime().exec(this) val stdoutLines = LinkedList<String>() val stderrLines = LinkedList<String>() proc.inputStream.bufferedReader().lines().forEach(handleStdOutputLine(stdoutLines, OutputType.STDOUT)) proc.errorStream.bufferedReader().lines().forEach(handleStdOutputLine(stderrLines, OutputType.STDERR)) val returnCode = proc.waitFor() log.debug(""" returnCode=$returnCode stdout: ====== ${stdoutLines.joinToString("\n")} ====== stderr: ====== ${stderrLines.joinToString("\n")} ====== """.trimIndent()) if (returnCode != 0 || stderrLines.isNotEmpty()) { throw JebExecException( cmd = this, stdout = stdoutLines.joinToString("\n"), stderr = stderrLines.joinToString("\n"), returnCode = returnCode) } } private fun handleStdOutputLine(buffer: LinkedList<String>, type: OutputType): (String) -> Unit = { val msg = "[$type]: $it" when (type) { OutputType.STDOUT -> log.debug(msg) OutputType.STDERR -> log.error(msg) else -> throw AssertionError("Unknown type: $type") } buffer.add(it) if (buffer.size > 1000) { buffer.removeFirst() } } private enum class OutputType{ STDOUT, STDERR } }
src/main/kotlin/jeb/Storage.kt
563589700
package com.cooltee.service.impl import com.cooltee.redis.RedisClient import com.cooltee.service.interfaces.SessionService import com.cooltee.session.SessionInfo import com.cooltee.util.Utils import org.springframework.stereotype.Service /** * The Implements of Session Service * Created by Daniel on 2017/5/16. */ @Service class SessionServiceImpl : SessionService { private val cache: ThreadLocal<SessionInfo> = ThreadLocal() override fun getSessionInfo(): SessionInfo? { return cache.get() } override fun checkSigned(sessionId: String): Boolean { var sessionInfo = RedisClient.get(sessionId) as SessionInfo? if (sessionInfo == null) { sessionInfo = SessionInfo(Utils.generateUUID(), null, null) } val flag = sessionId == sessionInfo.sid if (flag) { cache.set(sessionInfo) } return flag } override fun destroyCache() { cache.remove() } override fun refreshEffective(sessionId: String) { RedisClient.expire(sessionId, 1800) } override fun save(sessionInfo: SessionInfo) { cache.set(sessionInfo) RedisClient.setex(sessionInfo.sid, 1800, sessionInfo) } override fun delete(sessionId: String) { RedisClient.del(sessionId) destroyCache() } }
vehicles_service/src/main/java/com/cooltee/service/impl/SessionServiceImpl.kt
4206669227
package i_introduction._10_Object_Expressions import util.TODO import util.doc10 import java.util.* fun todoTask10(): Nothing = TODO( """ Task 10. Read about object expressions that play the same role in Kotlin as anonymous classes do in Java. Add an object expression that provides a comparator to sort a list in a descending order using java.util.Collections class. In Kotlin you use Kotlin library extensions instead of java.util.Collections, but this example is still a good demonstration of mixing Kotlin and Java code. """, documentation = doc10() ) fun task10(): List<Int> { val arrayList = arrayListOf(1, 5, 2) Collections.sort(arrayList, object : Comparator<Int> { override fun compare(o1: Int, o2: Int): Int = o2.compareTo(o1) }) return arrayList }
src/i_introduction/_10_Object_Expressions/ObjectExpressions.kt
51702304
package com.moviereel.data.db.entities.movie import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.Ignore import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.moviereel.data.db.entities.* /** * @author lusinabrian on 15/05/17. * * * @Notes Data entry for the latest movie */ // @Entity(tableName = "movie_latest") data class MovieLatestEntity( @Expose //@ColumnInfo(name = "belongs_to_collection") var belongsToCollection: String? = null, @Expose //@ColumnInfo(name = "budget") var budget: Int = 0, @Expose //@ColumnInfo(name = "genres") //@Ignore var genres: ArrayList<GenreEntity>, @Expose @SerializedName("homepage") //@ColumnInfo(name = "homepage") var homepage: String, @Expose @SerializedName("imdb_id") //@ColumnInfo(name = "imdb_id") var imdbId: String, @Expose @SerializedName("production_companies") //@ColumnInfo(name = "production_companies") //@Ignore var productionCompanies: ArrayList<ProductionCompany>, @Expose @SerializedName("production_countries") //@ColumnInfo(name = "production_countries") //@Ignore var productionCountry: ArrayList<ProductionCountry>, @Expose @SerializedName("revenue") //@ColumnInfo(name = "revenue") var revenue: Int, @Expose @SerializedName("runtime") //@ColumnInfo(name = "runtime") var runtime: Int, @Expose @SerializedName("spoken_languages") //@ColumnInfo(name = "spoken_languages") //@Ignore var spokenLanguage: ArrayList<SpokenLanguage>, @Expose @SerializedName("status") //@ColumnInfo(name = "status") var status: String, @Expose @SerializedName("tagline") //@ColumnInfo(name = "tagline") var tagline: String ) : BaseEntity()
app/src/main/kotlin/com/moviereel/data/db/entities/movie/MovieLatestEntity.kt
1449204410
package de.westnordost.streetcomplete.quests.opening_hours import android.content.Context import androidx.appcompat.app.AlertDialog import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.opening_hours.model.Weekdays object WeekdaysPickerDialog { fun show(context: Context, weekdays: Weekdays?, callback: (Weekdays) -> Unit): AlertDialog { val selection = weekdays?.selection ?: BooleanArray(Weekdays.OSM_ABBR_WEEKDAYS.size) return AlertDialog.Builder(context) .setTitle(R.string.quest_openingHours_chooseWeekdaysTitle) .setMultiChoiceItems(Weekdays.getNames(context.resources), selection) { _, _, _ -> } .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok) { _, _ -> callback(Weekdays(selection)) } .show() } }
app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/WeekdaysPickerDialog.kt
79071376
package org.wordpress.android.fluxc.model.user import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.rest.wpcom.wc.user.WCUserRestClient.UserApiResponse import javax.inject.Inject class WCUserMapper @Inject constructor() { fun map(user: UserApiResponse, siteModel: SiteModel): WCUserModel { return WCUserModel().apply { remoteUserId = user.id username = user.username ?: "" firstName = user.firstName ?: "" lastName = user.lastName ?: "" email = user.email ?: "" roles = user.roles.toString() localSiteId = siteModel.id } } }
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/user/WCUserMapper.kt
3190589935
package com.boardgamegeek.ui.dialog import android.app.Dialog import android.os.Bundle import android.text.InputType import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.activityViewModels import com.boardgamegeek.R import com.boardgamegeek.databinding.DialogEditTextBinding import com.boardgamegeek.extensions.requestFocus import com.boardgamegeek.ui.viewmodel.BuddyViewModel class EditUsernameDialogFragment : DialogFragment() { private var _binding: DialogEditTextBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<BuddyViewModel>() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { _binding = DialogEditTextBinding.inflate(layoutInflater) val builder = AlertDialog.Builder(requireContext(), R.style.Theme_bgglight_Dialog_Alert) .setTitle(R.string.title_add_username) .setView(binding.root) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> val text = binding.editText.text?.toString() viewModel.addUsernameToPlayer(text?.trim() ?: "") } return builder.create().apply { requestFocus(binding.editText) } } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.editText.inputType = binding.editText.inputType or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS binding.editTextContainer.hint = getString(R.string.username) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
app/src/main/java/com/boardgamegeek/ui/dialog/EditUsernameDialogFragment.kt
2923837340
package org.wordpress.android.fluxc.store import android.content.SharedPreferences import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner import org.wordpress.android.fluxc.store.NotificationStore.Companion.WPCOM_PUSH_DEVICE_SERVER_ID import org.wordpress.android.fluxc.utils.PreferenceUtils @RunWith(MockitoJUnitRunner::class) class GetDeviceRegistrationStatusTest { private val preferences: SharedPreferences = mock() private val preferencesWrapper: PreferenceUtils.PreferenceUtilsWrapper = mock { on { getFluxCPreferences() } doReturn preferences } private val sut = GetDeviceRegistrationStatus(preferencesWrapper) @Test fun `when device id is not empty, return registered status`() { // given whenever(preferences.getString(WPCOM_PUSH_DEVICE_SERVER_ID, null)).doReturn("not-empty-id") // when val result = sut.invoke() // then assertEquals(GetDeviceRegistrationStatus.Status.REGISTERED, result) } @Test fun `when device id is empty, return unregistered status`() { // given whenever(preferences.getString(WPCOM_PUSH_DEVICE_SERVER_ID, null)).doReturn("") // when val result = sut.invoke() // then assertEquals(GetDeviceRegistrationStatus.Status.UNREGISTERED, result) } @Test fun `when device id is null, return unregistered status`() { // given whenever(preferences.getString(WPCOM_PUSH_DEVICE_SERVER_ID, null)).doReturn(null) // when val result = sut.invoke() // then assertEquals(GetDeviceRegistrationStatus.Status.UNREGISTERED, result) } }
example/src/test/java/org/wordpress/android/fluxc/store/GetDeviceRegistrationStatusTest.kt
3767489017
package pref.impl import android.content.Context import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.hamcrest.core.IsNull.nullValue import org.junit.Test import pref.BasePrefTest import pref.SimplePref import pref.ext.booleanPref import pref.ext.floatPref import pref.ext.intPref import pref.ext.longPref import pref.ext.stringPref import pref.ext.stringSetPref internal class GenericNullablePrefTest : BasePrefTest<GenericNullablePrefTest.TestNullablePref>() { override fun setupTestPref(context: Context) = TestNullablePref(context) internal class TestNullablePref(context: Context) : SimplePref(context, "TestNullablePref") { var nullableBoolean by booleanPref() var nullableFloat by floatPref() var nullableInt by intPref() var nullableLong by longPref() var nullableString by stringPref() var nullableStringSet by stringSetPref() } @Test fun `Test nullable booleanPref value and set new value`() { assertThat(testPref.nullableBoolean, `is`(nullValue())) testPref.nullableBoolean = true assertThat(testPref.nullableBoolean, `is`(true)) testPref.nullableBoolean = null assertThat(testPref.nullableBoolean, `is`(nullValue())) } @Test fun `Test nullable stringSetPref value and set new value`() { assertThat(testPref.nullableStringSet, `is`(nullValue())) val newValue = setOf("set", "test") testPref.nullableStringSet = newValue assertThat(testPref.nullableStringSet, `is`(newValue)) testPref.nullableStringSet = null assertThat(testPref.nullableStringSet, `is`(nullValue())) } @Test fun `Test nullable stringPref value and set new value`() { assertThat(testPref.nullableString, `is`(nullValue())) val newValue = "test" testPref.nullableString = newValue assertThat(testPref.nullableString, `is`(newValue)) testPref.nullableString = null assertThat(testPref.nullableString, `is`(nullValue())) } @Test fun `Test nullable longPref value and set new value`() { assertThat(testPref.nullableLong, `is`(nullValue())) val newValue = 30L testPref.nullableLong = newValue assertThat(testPref.nullableLong, `is`(newValue)) testPref.nullableLong = null assertThat(testPref.nullableLong, `is`(nullValue())) } @Test fun `Test nullable intPref value and set new value`() { assertThat(testPref.nullableInt, `is`(nullValue())) val newValue = 123 testPref.nullableInt = newValue assertThat(testPref.nullableInt, `is`(newValue)) testPref.nullableInt = null assertThat(testPref.nullableInt, `is`(nullValue())) } @Test fun `Test nullable floatPref value and set new value`() { assertThat(testPref.nullableFloat, `is`(nullValue())) val newValue = 0.5F testPref.nullableFloat = newValue assertThat(testPref.nullableFloat, `is`(newValue)) testPref.nullableFloat = null assertThat(testPref.nullableFloat, `is`(nullValue())) } }
pref/src/test/java/pref/impl/GenericNullablePrefTest.kt
2816029323
/** * File : Delimiter.kt * License : * Original - Copyright (c) 2010 - 2016 Boxfuse GmbH * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.builtamont.cassandra.migration.internal.dbsupport /** * Represents a CQL statement delimiter. * * @param delimiter The actual delimiter string. * @param isAloneOnLine Whether the delimiter sits alone on a new line or not. */ class Delimiter(val delimiter: String, val isAloneOnLine: Boolean) { /** * @return The computed delimiter instance hash value. */ override fun hashCode(): Int { var result = delimiter.hashCode() result = 31 * result + if (isAloneOnLine) 1 else 0 return result } /** * @return {@code true} if this delimiter instance is the same as the given object. */ override fun equals(other: Any?): Boolean { /** * @return {@code true} if this version instance is not the same as the given object. */ fun isNotSame(): Boolean { return other == null || javaClass != other.javaClass } /** * @return {@code true} if delimiter is alone on line. */ fun isDelimiterAloneOnLine(): Boolean { val delimiter1 = other as Delimiter? return isAloneOnLine == delimiter1!!.isAloneOnLine && delimiter == delimiter1.delimiter } return when { this === other -> true isNotSame() -> false else -> isDelimiterAloneOnLine() } } }
src/main/java/com/builtamont/cassandra/migration/internal/dbsupport/Delimiter.kt
848784679
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.api.v2alpha import io.grpc.Context object ContextKeys { /** This is the context key for the authenticated Principal. */ val PRINCIPAL_CONTEXT_KEY: Context.Key<MeasurementPrincipal> = Context.key("principal") }
src/main/kotlin/org/wfanet/measurement/api/v2alpha/ContextKeys.kt
653945193
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers import com.google.cloud.spanner.Value import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation import org.wfanet.measurement.gcloud.spanner.set import org.wfanet.measurement.internal.kingdom.Account import org.wfanet.measurement.internal.kingdom.account import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.AccountNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.PermissionDeniedException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.AccountReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementConsumerOwnerReader /** * Creates an account in the database. * * Throws a subclass of [KingdomInternalException] on [execute]. * @throws [PermissionDeniedException] Permission denied due to ownership of MeasurementConsumer * @throws [AccountNotFoundException] Creator's Account not found */ class CreateAccount( private val externalCreatorAccountId: ExternalId?, private val externalOwnedMeasurementConsumerId: ExternalId? ) : SimpleSpannerWriter<Account>() { override suspend fun TransactionScope.runTransaction(): Account { val internalAccountId = idGenerator.generateInternalId() val externalAccountId = idGenerator.generateExternalId() val activationToken = idGenerator.generateExternalId() val source = this@CreateAccount return account { transactionContext.bufferInsertMutation("Accounts") { if (source.externalCreatorAccountId != null) { val readCreatorAccountResult = readAccount(source.externalCreatorAccountId) set("CreatorAccountId" to readCreatorAccountResult.accountId) externalCreatorAccountId = source.externalCreatorAccountId.value if (source.externalOwnedMeasurementConsumerId != null) { MeasurementConsumerOwnerReader() .checkOwnershipExist( transactionContext, readCreatorAccountResult.accountId, source.externalOwnedMeasurementConsumerId ) ?.let { externalOwnedMeasurementConsumerId = source.externalOwnedMeasurementConsumerId.value set("OwnedMeasurementConsumerId" to it.measurementConsumerId) } ?: throw PermissionDeniedException() } } set("AccountId" to internalAccountId) set("ExternalAccountId" to externalAccountId) set("ActivationState" to Account.ActivationState.UNACTIVATED) set("ActivationToken" to activationToken) set("CreateTime" to Value.COMMIT_TIMESTAMP) set("UpdateTime" to Value.COMMIT_TIMESTAMP) } this.externalAccountId = externalAccountId.value activationState = Account.ActivationState.UNACTIVATED this.activationToken = activationToken.value } } private suspend fun TransactionScope.readAccount( externalAccountId: ExternalId ): AccountReader.Result = AccountReader().readByExternalAccountId(transactionContext, externalAccountId) ?: throw AccountNotFoundException(externalAccountId) }
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateAccount.kt
2396688870
package com.sys1yagi.swipe.core.entity.swipe import com.sys1yagi.swipe.core.testtool.TestAssetsUtils import com.sys1yagi.swipe.core.tool.SwipeEntityDecoder import com.sys1yagi.swipe.core.tool.json.JsonConverter import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test class SwipeElementTest { lateinit var swipeDocument: SwipeDocument @Before fun setUp() { val swipeEntityDecoder = SwipeEntityDecoder() swipeDocument = swipeEntityDecoder.decodeToSwipe( JsonConverter.getInstance(), TestAssetsUtils.loadFromAssets("swipe.swipe")!!) } @Test fun inheritElement() { val element = swipeDocument.pages[0].elements[1] val namedElement = swipeDocument.elements["logo"] val inherited = element.inheritElement(namedElement) assertThat(inherited) .isNotNull() assertThat(inherited.x).isEqualTo("300") assertThat(inherited.w).isEqualTo("192") val back = inherited.elements!![0] assertThat(back.id).isEqualTo("back") assertThat(back.w).isEqualTo("128") assertThat(back.h).isEqualTo("176") assertThat(back.cornerRadius).isEqualTo(12f) assertThat(back.shadow?.opacity).isEqualTo(0.2f) assertThat(back.shadow?.offset!![0]).isEqualTo(0) assertThat(back.shadow?.offset!![1]).isEqualTo(8) assertThat(back.shadow?.radius).isEqualTo(8) } }
core/src/test/java/com/sys1yagi/swipe/core/entity/swipe/SwipeElementTest.kt
862182736
package es.unizar.webeng.hello.controller import org.hamcrest.CoreMatchers.* import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* import org.springframework.test.web.servlet.result.MockMvcResultHandlers.* import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* /** * The [WebMvcTest] annotation is used for Spring MVC tests. It disables full * autoconfiguration and instead apply only configuration relevant to MVC tests. * * The [WebMvcTest] annotation autoconfigure MockMvc instance as well. * * Using HelloController::class as parameter, we are asking to initialize only one web controller, * and you need to provide remaining dependencies required using Mock objects. */ @WebMvcTest(HelloController::class) class HelloControllerMVCTests { /** * The variable [message] takes the value of the key [app.message] in the resource file [application.properties]. */ @Value("\${app.message}") private lateinit var message: String /** * The [Autowired] annotation marks a Constructor, Setter method, Properties and Config() method * as to be autowired that is injecting beans (Objects) at runtime by Spring Dependency Injection mechanism. * It enables you to inject the object dependency implicitly. */ @Autowired private lateinit var mockMvc: MockMvc /** * Integration test that calls a GET request to /, * prints the request and response * and verifies that response HTTP status is Ok (ensuring that the request was successfully executed) * and also the model attribute [message] has the expected value. */ @Test fun testMessage() { mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isOk) .andExpect(model().attribute("message", equalTo(message))) } }
src/test/kotlin/controller/HelloControllerMVCTests.kt
671095178
/* * Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.timeperiod.models import debop4k.timeperiod.* /** * 분기를 표현 * @author debop [email protected] */ enum class Quarter(val value: Int) { /** 1/4 분기 */ FIRST(1), /** 2/4 분기 */ SECOND(2), /** 3/4 분기 */ THIRD(3), /** 4/4 분기 */ FOURTH(4); operator fun plus(delta: Int): Quarter { val amount = delta % QuartersPerYear return quarterArray[(ordinal + (amount + 4)) % 4] } operator fun minus(delta: Int): Quarter = plus(-(delta % 12)) val months: IntArray get() = when (this) { FIRST -> FirstQuarterMonths SECOND -> SecondQuarterMonths THIRD -> ThirdQuarterMonths FOURTH -> FourthQuarterMonths } val startMonth: Int get() = this.ordinal * MonthsPerQuarter + 1 val endMonth: Int get() = this.value * MonthsPerQuarter companion object { val quarterArray: Array<Quarter> = Quarter.values() @JvmStatic fun of(q: Int): Quarter { if (q < 1 || q > 4) throw IllegalArgumentException("Invalid q for Quarter. 1..4") return quarterArray[q - 1] } @JvmStatic fun ofMonth(monthOfYear: Int): Quarter { return quarterArray[(monthOfYear - 1) / MonthsPerQuarter] } } }
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/models/Quarter.kt
746109554
/* * Copyright 2015, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.keygen import us.eharning.atomun.core.ValidationException import us.eharning.atomun.core.ec.ECKey /** * Generator of deterministic EC keys. */ interface DeterministicKeyGenerator { /** * Return whether or not this generator has private key generation bits. * * @return true if generator has private bits. */ fun hasPrivate(): Boolean /** * Generate a private key for the given sequence. * * @param sequence * integer representing the key to generate. * * @return generated private key. * * @throws ValidationException * if no private key is available or if somehow an invalid key is generated. */ @Throws(ValidationException::class) fun generate(sequence: Int): ECKey /** * Generate a public key for the given sequence. * * @param sequence * integer representing the key to generate. * * @return generated public key. * * @throws ValidationException * if somehow an invalid key is generated. */ @Throws(ValidationException::class) fun generatePublic(sequence: Int): ECKey /** * Export the private/public bits of this key generator for later import dependent on what is available. * * @return exported key data in string form. */ fun export(): String /** * Export the public bits of this key generator for later import. * * @return exported public key in string form. */ fun exportPublic(): String }
src/main/java/us/eharning/atomun/keygen/DeterministicKeyGenerator.kt
337162211
package com.andreapivetta.blu.data.model import io.realm.RealmObject import io.realm.annotations.Index import io.realm.annotations.PrimaryKey import twitter4j.DirectMessage import java.io.Serializable open class PrivateMessage( @PrimaryKey open var id: Long = 0, open var senderId: Long = 0, open var recipientId: Long = 0, @Index open var otherId: Long = 0, open var timeStamp: Long = System.currentTimeMillis(), open var text: String = "", open var otherUserName: String = "", open var otherUserProfilePicUrl: String = "", open var isRead: Boolean = false) : RealmObject(), Comparable<PrivateMessage>, Serializable { companion object { val NEW_PRIVATE_MESSAGE_INTENT = "com.andreapivetta.blu.data.model.NEW_PRIVATE_MESSAGE_INTENT" fun valueOf(directMessage: DirectMessage, userId: Long, inverted: Boolean = false): PrivateMessage { if (inverted) return getInverted(directMessage, userId) val otherUserId = if (directMessage.recipientId == userId) directMessage.senderId else directMessage.recipientId val otherUsername = if (userId == directMessage.senderId) directMessage.recipientScreenName else directMessage.senderScreenName val otherUserProfilePicUrl: String = if (userId == directMessage.senderId) directMessage.recipient.biggerProfileImageURL else directMessage.sender.biggerProfileImageURL return PrivateMessage(directMessage.id, directMessage.senderId, directMessage.recipientId, otherUserId, directMessage.createdAt.time, directMessage.text, otherUsername, otherUserProfilePicUrl, false) } private fun getInverted(directMessage: DirectMessage, userId: Long): PrivateMessage { val otherUserId = if (directMessage.recipientId != userId) directMessage.senderId else directMessage.recipientId val otherUsername = if (userId != directMessage.senderId) directMessage.recipientScreenName else directMessage.senderScreenName val otherUserProfilePicUrl: String = if (userId != directMessage.senderId) directMessage.recipient.biggerProfileImageURL else directMessage.sender.biggerProfileImageURL return PrivateMessage(directMessage.id, directMessage.senderId, directMessage.recipientId, otherUserId, directMessage.createdAt.time, directMessage.text, otherUsername, otherUserProfilePicUrl, false) } } override fun compareTo(other: PrivateMessage) = (other.timeStamp - this.timeStamp).toInt() }
app/src/main/java/com/andreapivetta/blu/data/model/PrivateMessage.kt
3511669037
package io.gitlab.arturbosch.detekt.api import io.gitlab.arturbosch.detekt.test.compileContentForTest import org.jetbrains.kotlin.psi.KtAnnotated import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import kotlin.test.assertFalse import kotlin.test.assertTrue /** * @author Marvin Ramin */ internal class SuppressibleSpec : Spek({ given("a Test rule") { it("should not be suppressed by a @Deprecated annotation") { assertFalse { checkSuppression("Deprecated", "This should no longer be used") } } it("should not be suppressed by a @Suppress annotation for another rule") { assertFalse { checkSuppression("Suppress", "NotATest") } } it("should not be suppressed by a @SuppressWarnings annotation for another rule") { assertFalse { checkSuppression("SuppressWarnings", "NotATest") } } it("should be suppressed by a @Suppress annotation for the rule") { assertTrue { checkSuppression("Suppress", "Test") } } it("should be suppressed by a @SuppressWarnings annotation for the rule") { assertTrue { checkSuppression("SuppressWarnings", "Test") } } it("should be suppressed by a @SuppressWarnings annotation for 'all' rules") { assertTrue { checkSuppression("Suppress", "all") } } it("should be suppressed by a @SuppressWarnings annotation for 'ALL' rules") { assertTrue { checkSuppression("SuppressWarnings", "ALL") } } it("should not be suppressed by a @Suppress annotation with a Checkstyle prefix") { assertFalse { checkSuppression("Suppress", "Checkstyle:Test") } } it("should not be suppressed by a @SuppressWarnings annotation with a Checkstyle prefix") { assertFalse { checkSuppression("SuppressWarnings", "Checkstyle:Test") } } it("should be suppressed by a @Suppress annotation with a 'Detekt' prefix") { assertTrue { checkSuppression("Suppress", "Detekt:Test") } } it("should be suppressed by a @SuppressWarnings annotation with a 'Detekt' prefix") { assertTrue { checkSuppression("SuppressWarnings", "Detekt:Test") } } it("should be suppressed by a @Suppress annotation with a 'detekt' prefix") { assertTrue { checkSuppression("Suppress", "detekt:Test") } } it("should be suppressed by a @SuppressWarnings annotation with a 'detekt' prefix") { assertTrue { checkSuppression("SuppressWarnings", "detekt:Test") } } it("should be suppressed by a @Suppress annotation with a 'detekt' prefix with a dot") { assertTrue { checkSuppression("Suppress", "detekt.Test") } } it("should be suppressed by a @SuppressWarnings annotation with a 'detekt' prefix with a dot") { assertTrue { checkSuppression("SuppressWarnings", "detekt.Test") } } it("should not be suppressed by a @Suppress annotation with a 'detekt' prefix with a wrong separator") { assertFalse { checkSuppression("Suppress", "detekt/Test") } } it("should not be suppressed by a @SuppressWarnings annotation with a 'detekt' prefix with a wrong separator") { assertFalse { checkSuppression("SuppressWarnings", "detekt/Test") } } it("should be suppressed by a @Suppress annotation with an alias") { assertTrue { checkSuppression("Suppress", "alias") } } it("should be suppressed by a @SuppressWarnings annotation with an alias") { assertTrue { checkSuppression("SuppressWarnings", "alias") } } } }) private fun checkSuppression(annotation: String, argument: String): Boolean { val annotated = """ @$annotation("$argument") class Test {} """ val file = compileContentForTest(annotated) val annotatedClass = file.children.first { it is KtClass } as KtAnnotated return annotatedClass.isSuppressedBy("Test", setOf("alias")) }
detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/SuppressibleSpec.kt
2739743538
package voice.playback.session.search import android.provider.MediaStore import androidx.datastore.core.DataStore import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.updateAndGet import kotlinx.coroutines.test.runTest import org.junit.Test import voice.common.BookId import voice.data.Book import voice.data.BookContent import voice.data.Chapter import voice.data.repo.BookRepository import voice.playback.PlayerController import java.time.Instant import java.util.UUID class BookSearchHandlerTest { private val searchHandler: BookSearchHandler private val repo = mockk<BookRepository>() private val player = mockk<PlayerController>(relaxUnitFun = true) private val currentBookId = MemoryDataStore<BookId?>(null) private val anotherBook = book(listOf(chapter(), chapter())) private val bookToFind = book(listOf(chapter(), chapter())) init { coEvery { repo.all() } coAnswers { listOf(anotherBook, bookToFind) } searchHandler = BookSearchHandler(repo, player, currentBookId) } @Test fun unstructuredSearchByBook() = runTest { val bookSearch = VoiceSearch(query = bookToFind.content.name) searchHandler.handle(bookSearch) currentBookIdShouldBe(bookToFind) verify(exactly = 1) { player.play() } } private suspend fun currentBookIdShouldBe(book: Book = bookToFind) { currentBookId.data.first() shouldBe book.content.id } @Test fun unstructuredSearchByArtist() = runTest { val bookSearch = VoiceSearch(query = bookToFind.content.author) searchHandler.handle(bookSearch) currentBookIdShouldBe() verify(exactly = 1) { player.play() } } @Test fun unstructuredSearchByChapter() = runTest { val bookSearch = VoiceSearch(query = bookToFind.chapters.first().name) searchHandler.handle(bookSearch) currentBookIdShouldBe() verify(exactly = 1) { player.play() } } @Test fun mediaFocusAnyNoneFoundButPlayed() = runTest { val bookSearch = VoiceSearch(mediaFocus = "vnd.android.cursor.item/*") searchHandler.handle(bookSearch) currentBookIdShouldBe(anotherBook) verify(exactly = 1) { player.play() } } @Test fun mediaFocusArtist() = runTest { val bookSearch = VoiceSearch( mediaFocus = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE, artist = bookToFind.content.author, ) searchHandler.handle(bookSearch) currentBookIdShouldBe() verify(exactly = 1) { player.play() } } @Test fun mediaFocusArtistInTitleNoArtistInBook() = runTest { val bookToFind = bookToFind.copy( content = bookToFind.content.copy( author = null, name = "The book of Tim", ), ) coEvery { repo.all() } coAnswers { listOf(bookToFind) } val bookSearch = VoiceSearch( mediaFocus = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE, query = "Tim", artist = "Tim", ) searchHandler.handle(bookSearch) currentBookIdShouldBe() verify(exactly = 1) { player.play() } } @Test fun mediaFocusAlbum() = runTest { val bookSearch = VoiceSearch( mediaFocus = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE, artist = bookToFind.content.author, album = bookToFind.content.name, query = null, ) searchHandler.handle(bookSearch) currentBookIdShouldBe() verify(exactly = 1) { player.play() } } } fun book(chapters: List<Chapter>): Book { return Book( content = BookContent( author = UUID.randomUUID().toString(), name = UUID.randomUUID().toString(), positionInChapter = 42, playbackSpeed = 1F, addedAt = Instant.EPOCH, chapters = chapters.map { it.id }, cover = null, currentChapter = chapters.first().id, isActive = true, lastPlayedAt = Instant.EPOCH, skipSilence = false, id = BookId(UUID.randomUUID().toString()), gain = 0F, ), chapters = chapters, ) } private fun chapter(): Chapter { return Chapter( id = Chapter.Id(UUID.randomUUID().toString()), name = UUID.randomUUID().toString(), duration = 10000, fileLastModified = Instant.EPOCH, markData = emptyList(), ) } private class MemoryDataStore<T>(initial: T) : DataStore<T> { private val value = MutableStateFlow(initial) override val data: Flow<T> get() = value override suspend fun updateData(transform: suspend (t: T) -> T): T { return value.updateAndGet { transform(it) } } }
playback/src/test/kotlin/voice/playback/session/search/BookSearchHandlerTest.kt
78079077
package net.twisterrob.test.jfixture.examples.journey import com.flextrade.jfixture.JFixture import net.twisterrob.test.jfixture.createList import net.twisterrob.test.jfixture.examples.journey.TransportMode.TRAIN import net.twisterrob.test.jfixture.invoke import net.twisterrob.test.jfixture.setField import net.twisterrob.test.jfixture.valuesExcluding import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.ParameterizedTest.INDEX_PLACEHOLDER import org.junit.jupiter.params.provider.CsvSource import java.time.Duration import java.time.temporal.ChronoUnit class JourneyMapperTest { private val sut = JourneyMapper() private val fixture = JFixture() @CsvSource("1, 0", "2, 1", "3, 2", "4, 3") @ParameterizedTest(name = "changeCount[$INDEX_PLACEHOLDER]: when {0} legs, expect {1} changes") fun `changeCount is mapped correctly`(legCount: Int, expectedChanges: Int) { fixture.customise().repeatCount(legCount) val journey: Journey = fixture() val result = sut.invoke(journey) assertThat(result.changeCount, equalTo(expectedChanges)) } @Test fun `trainOnly is true for a TRAIN-only journey`() { fixture.customise().sameInstance(TransportMode::class.java, TRAIN) val journey: Journey = fixture() val result = sut.invoke(journey) assertThat(result.trainOnly, equalTo(true)) } @Test fun `trainOnly is false for a TRAIN-less journey`() { fixture.customise().lazyInstance(TransportMode::class.java) { fixture.create().fromList(*Enum.valuesExcluding(TRAIN)) } val journey: Journey = fixture() val result = sut.invoke(journey) assertThat(result.trainOnly, equalTo(false)) } @Test fun `trainOnly is true for a TRAIN-only journey v2`() { fixture.customise().propertyOf(Leg::class.java, "mode", TRAIN) val journey: Journey = fixture() val result = sut.invoke(journey) assertThat(result.trainOnly, equalTo(true)) } @Test fun `trainOnly is true for a TRAIN-only journey v3`() { fixture.customise().intercept(Leg::class.java) { it.setField("mode", TRAIN) } val journey: Journey = fixture() val result = sut.invoke(journey) assertThat(result.trainOnly, equalTo(true)) } @Test fun `duration returns time for whole journey`() { val journey: Journey = fixture() journey.legs.last().setField("arrival", journey.legs.first().departure.plusMinutes(15)) val result = sut.invoke(journey) assertThat(result.length, equalTo(Duration.of(15, ChronoUnit.MINUTES))) } @Test fun `2 passengers 1 leg`() { val journey: Journey = fixture() journey.setField("legs", fixture.createList<Leg>(2)) journey.setField("passengers", fixture.createList<Passenger>(1)) } }
JFixturePlayground/src/test/java/net/twisterrob/test/jfixture/examples/journey/JourneyMapperTest.kt
2419832967
package com.vsouhrada.apps.fibo.core.db.bl import com.vsouhrada.kotlin.android.anko.fibo.domain.model.UserDO import com.vsouhrada.kotlin.android.anko.fibo.function.signin.login.model.AuthCredentials /** * @author vsouhrada * @version 0.1 * @since 0.1 */ interface IUserBL { fun existUser(): Boolean fun saveUser(credentials: AuthCredentials) fun getUserById(id: Int): UserDO? fun getUser(credentials: AuthCredentials): UserDO? }
app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/function/common/user/bl/IUserBL.kt
2353453214
/* * 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. */ /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.util import com.intellij.diff.DiffRequestFactoryImpl import com.intellij.diff.DiffTestCase import com.intellij.openapi.diff.DiffBundle import com.intellij.util.containers.ContainerUtil import java.io.File class DiffUtilTest : DiffTestCase() { fun `test getSortedIndexes`() { fun <T> doTest(vararg values: T, comparator: (T, T) -> Int) { val list = values.toList() val sortedIndexes = DiffUtil.getSortedIndexes(list, comparator) val expected = ContainerUtil.sorted(list, comparator) val actual = (0..values.size - 1).map { values[sortedIndexes[it]] } assertOrderedEquals(expected, actual) assertEquals(sortedIndexes.toSet().size, list.size) } doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v1 - v2 } doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v1 - v2 } doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v1 - v2 } doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v2 - v1 } doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v2 - v1 } doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v2 - v1 } } fun `test merge conflict partially resolved confirmation message`() { fun doTest(changes: Int, conflicts: Int, expected: String) { val actual = DiffBundle.message("merge.dialog.apply.partially.resolved.changes.confirmation.message", changes, conflicts) assertTrue(actual.startsWith(expected), actual) } doTest(1, 0, "There is one change left") doTest(0, 1, "There is one conflict left") doTest(1, 1, "There is one change and one conflict left") doTest(2, 0, "There are 2 changes left") doTest(0, 2, "There are 2 conflicts left") doTest(2, 2, "There are 2 changes and 2 conflicts left") doTest(1, 2, "There is one change and 2 conflicts left") doTest(2, 1, "There are 2 changes and one conflict left") doTest(2, 3, "There are 2 changes and 3 conflicts left") } fun `test diff content titles`() { fun doTest(path: String, expected: String) { val filePath = createFilePath(path) val actual1 = DiffRequestFactoryImpl.getContentTitle(filePath) val actual2 = DiffRequestFactoryImpl.getTitle(filePath, null, " <-> ") val actual3 = DiffRequestFactoryImpl.getTitle(null, filePath, " <-> ") val expectedNative = expected.replace('/', File.separatorChar) assertEquals(expectedNative, actual1) assertEquals(expectedNative, actual2) assertEquals(expectedNative, actual3) } doTest("file.txt", "file.txt") doTest("/path/to/file.txt", "file.txt (/path/to)") doTest("/path/to/dir/", "/path/to/dir") } fun `test diff request titles`() { fun doTest(path1: String, path2: String, expected: String) { val filePath1 = createFilePath(path1) val filePath2 = createFilePath(path2) val actual = DiffRequestFactoryImpl.getTitle(filePath1, filePath2, " <-> ") assertEquals(expected.replace('/', File.separatorChar), actual) } doTest("file1.txt", "file1.txt", "file1.txt") doTest("/path/to/file1.txt", "/path/to/file1.txt", "file1.txt (/path/to)") doTest("/path/to/dir1/", "/path/to/dir1/", "/path/to/dir1") doTest("file1.txt", "file2.txt", "file1.txt <-> file2.txt") doTest("/path/to/file1.txt", "/path/to/file2.txt", "file1.txt <-> file2.txt (/path/to)") doTest("/path/to/dir1/", "/path/to/dir2/", "dir1 <-> dir2 (/path/to)") doTest("/path/to/file1.txt", "/path/to_another/file1.txt", "file1.txt (/path/to <-> /path/to_another)") doTest("/path/to/file1.txt", "/path/to_another/file2.txt", "file1.txt <-> file2.txt (/path/to <-> /path/to_another)") doTest("/path/to/dir1/", "/path/to_another/dir2/", "dir1 <-> dir2 (/path/to <-> /path/to_another)") doTest("file1.txt", "/path/to/file1.txt", "file1.txt <-> /path/to/file1.txt") doTest("file1.txt", "/path/to/file2.txt", "file1.txt <-> /path/to/file2.txt") doTest("/path/to/dir1/", "/path/to/file2.txt", "dir1/ <-> file2.txt (/path/to)") doTest("/path/to/file1.txt", "/path/to/dir2/", "file1.txt <-> dir2/ (/path/to)") doTest("/path/to/dir1/", "/path/to_another/file2.txt", "dir1/ <-> file2.txt (/path/to <-> /path/to_another)") } }
platform/diff-impl/tests/com/intellij/diff/util/DiffUtilTest.kt
1519071941
package com.task.data.remote /** * Created by ahmedEltaher on 3/23/17. */ internal interface RemoteSource { suspend fun requestNews(): ServiceResponse? }
app/src/main/java/com/task/data/remote/RemoteSource.kt
1100084206
package com.quickblox.sample.pushnotifications.kotlin import android.app.Application import android.util.Log import com.google.android.gms.common.GoogleApiAvailability import com.quickblox.auth.session.QBSession import com.quickblox.auth.session.QBSessionManager import com.quickblox.auth.session.QBSessionParameters import com.quickblox.auth.session.QBSettings import com.quickblox.messages.services.QBPushManager import com.quickblox.sample.pushnotifications.kotlin.utils.ActivityLifecycle import com.quickblox.sample.pushnotifications.kotlin.utils.shortToast // app credentials private const val APPLICATION_ID = "" private const val AUTH_KEY = "" private const val AUTH_SECRET = "" private const val ACCOUNT_KEY = "" // default user config const val DEFAULT_USER_PASSWORD = "quickblox" class App : Application() { private val TAG = App::class.java.simpleName companion object { private lateinit var instance: App fun getInstance(): App = instance } override fun onCreate() { super.onCreate() instance = this registerActivityLifecycleCallbacks(ActivityLifecycle) checkConfig() initCredentials() initQBSessionManager() initPushManager() } private fun checkConfig() { if (APPLICATION_ID.isEmpty() || AUTH_KEY.isEmpty() || AUTH_SECRET.isEmpty() || ACCOUNT_KEY.isEmpty() || DEFAULT_USER_PASSWORD.isEmpty()) { throw AssertionError(getString(R.string.error_qb_credentials_empty)) } } private fun initCredentials() { QBSettings.getInstance().init(applicationContext, APPLICATION_ID, AUTH_KEY, AUTH_SECRET) QBSettings.getInstance().accountKey = ACCOUNT_KEY // uncomment and put your Api and Chat servers endpoints if you want to point the sample // against your own server. // // QBSettings.getInstance().setEndpoints("https://your_api_endpoint.com", "your_chat_endpoint", ServiceZone.PRODUCTION); // QBSettings.getInstance().zone = ServiceZone.PRODUCTION } private fun initQBSessionManager() { QBSessionManager.getInstance().addListener(object : QBSessionManager.QBSessionListener { override fun onSessionCreated(qbSession: QBSession) { Log.d(TAG, "Session Created") } override fun onSessionUpdated(qbSessionParameters: QBSessionParameters) { Log.d(TAG, "Session Updated") } override fun onSessionDeleted() { Log.d(TAG, "Session Deleted") } override fun onSessionRestored(qbSession: QBSession) { Log.d(TAG, "Session Restored") } override fun onSessionExpired() { Log.d(TAG, "Session Expired") } override fun onProviderSessionExpired(provider: String) { Log.d(TAG, "Session Expired for provider: $provider") } }) } private fun initPushManager() { QBPushManager.getInstance().addListener(object : QBPushManager.QBSubscribeListener { override fun onSubscriptionCreated() { shortToast("Subscription Created") Log.d(TAG, "SubscriptionCreated") } override fun onSubscriptionError(e: Exception, resultCode: Int) { Log.d(TAG, "SubscriptionError" + e.localizedMessage) if (resultCode >= 0) { val error = GoogleApiAvailability.getInstance().getErrorString(resultCode) Log.d(TAG, "SubscriptionError playServicesAbility: $error") } shortToast(e.localizedMessage) } override fun onSubscriptionDeleted(success: Boolean) { } }) } }
sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/App.kt
1251657918
package me.danwi.ezajax.container import org.apache.commons.io.FileUtils import java.io.File import java.util.jar.JarFile /** * 扫描 * Created by demon on 2017/2/13. */ /** * 获取到所有的类 */ fun scanAllClasses(): List<String> { //获取到classpath val url = Thread.currentThread().contextClassLoader.getResource("") val classesPath = File(url.path) var classes = (getClassesFromPath(classesPath)) //获取到lib目录 val jarsPath = File(url.path.replace("classes", "lib")) var jars = jarsPath.listFiles { dir, filename -> filename.endsWith(".jar") } jars.forEach { classes += getClassesFromJar(it) } return classes } /** * 获取到指定文件目录下所有的class包名 */ private fun getClassesFromPath(path: File): List<String> { return FileUtils.listFiles(path, arrayOf("class"), true) .map { it.absolutePath .drop(path.absolutePath.length + 1) .replace(File.separatorChar, '.') .dropLast(6) } } /** * 获取指定jar文件里面所有的class包名 */ private fun getClassesFromJar(jarFile: File): List<String> { val jar = JarFile(jarFile) return jar.entries() .toList() .filter { it.name.endsWith(".class") } .map { it.name.replace(File.separatorChar, '.').dropLast(6) } }
core/src/me/danwi/ezajax/container/Scanner.kt
2852685392
package com.ternaryop.photoshelf.adapter import android.view.View import androidx.recyclerview.widget.RecyclerView /** * Created by dave on 10/03/18. * Base Adapter */ abstract class AbsBaseAdapter<VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() { fun setEmptyView(view: View, onAdapterChanged: ((RecyclerView.Adapter<VH>) -> Boolean)? = null) { registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onChanged() { super.onChanged() if (onAdapterChanged == null || onAdapterChanged(this@AbsBaseAdapter)) { view.visibility = if (itemCount == 0) View.VISIBLE else View.GONE } } }) } }
core/src/main/java/com/ternaryop/photoshelf/adapter/AbsBaseAdapter.kt
2938126510
package org.tasks.jobs import android.content.Context import androidx.hilt.work.HiltWorker import androidx.work.WorkerParameters import com.todoroo.astrid.gcal.GCalHelper import com.todoroo.astrid.repeats.RepeatTaskHelper import dagger.assisted.Assisted import dagger.assisted.AssistedInject import org.tasks.analytics.Firebase import org.tasks.data.CaldavDao import org.tasks.data.TaskDao import org.tasks.injection.BaseWorker @HiltWorker class AfterSaveWork @AssistedInject constructor( @Assisted context: Context, @Assisted workerParams: WorkerParameters, firebase: Firebase, private val repeatTaskHelper: RepeatTaskHelper, private val taskDao: TaskDao, private val caldavDao: CaldavDao, private val gCalHelper: GCalHelper ) : BaseWorker(context, workerParams, firebase) { override suspend fun run(): Result { val taskId = inputData.getLong(EXTRA_ID, -1) val task = taskDao.fetch(taskId) ?: return Result.failure() if (inputData.getBoolean(EXTRA_SUPPRESS_COMPLETION_SNACKBAR, false)) { task.suppressRefresh() } gCalHelper.updateEvent(task) if (caldavDao.getAccountForTask(taskId)?.isSuppressRepeatingTasks != true) { repeatTaskHelper.handleRepeat(task) } return Result.success() } companion object { const val EXTRA_ID = "extra_id" const val EXTRA_SUPPRESS_COMPLETION_SNACKBAR = "extra_suppress_snackbar" } }
app/src/main/java/org/tasks/jobs/AfterSaveWork.kt
3997353999
package com.icetea09.vivid.model import android.os.Parcel import android.os.Parcelable class Image : Parcelable { var id: Long = 0 var name: String? = null var path: String? = null var isSelected: Boolean = false constructor(id: Long, name: String, path: String, isSelected: Boolean) { this.id = id this.name = name this.path = path this.isSelected = isSelected } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeLong(this.id) dest.writeString(this.name) dest.writeString(this.path) dest.writeByte(if (this.isSelected) 1.toByte() else 0.toByte()) } protected constructor(parcel: Parcel) { this.id = parcel.readLong() this.name = parcel.readString() this.path = parcel.readString() this.isSelected = parcel.readByte().toInt() != 0 } companion object { @JvmField @Suppress("unused") val CREATOR: Parcelable.Creator<Image> = object : Parcelable.Creator<Image> { override fun createFromParcel(source: Parcel): Image { return Image(source) } override fun newArray(size: Int): Array<Image> { return arrayOf() } } } }
library/src/main/java/com/icetea09/vivid/model/Image.kt
1666319363
package com.spectralogic.ds3autogen.go.generators.client.command import com.spectralogic.ds3autogen.go.models.client.ReadCloserBuildLine import com.spectralogic.ds3autogen.go.models.client.RequestBuildLine import org.assertj.core.api.Assertions import org.junit.Test class DeleteObjectsCommandGeneratorTest { private val generator = DeleteObjectsCommandGenerator() @Test fun toReaderBuildLineTest() { Assertions.assertThat<RequestBuildLine>(generator.toReaderBuildLine()) .isNotEmpty .contains(ReadCloserBuildLine("buildDeleteObjectsPayload(request.ObjectNames)")) } }
ds3-autogen-go/src/test/kotlin/com/spectralogic/ds3autogen/go/generators/client/command/DeleteObjectsCommandGeneratorTest.kt
4220366582
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.table import javafx.scene.control.cell.TextFieldTableCell import uk.co.nickthecoder.paratask.util.uncamel import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId open class TimestampColumn<R>( name: String, label: String = name.uncamel(), getter: (R) -> Long) : Column<R, Long>( name = name, label = label, getter = getter, width = 150, filterGetter = { row: R -> LocalDateTime.ofInstant(Instant.ofEpochMilli(getter(row)), ZoneId.systemDefault()) }) { init { setCellFactory { DateTableCell() } styleClass.add("timestamp") } class DateTableCell<R> : TextFieldTableCell<R, Long>() { override fun updateItem(item: Long?, empty: Boolean) { super.updateItem(item, empty) if (empty || item == null) { setText(null) } else { val dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(item), ZoneId.systemDefault()) setText(LocalDateTimeColumn.format(dateTime)) } } } }
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/table/TimestampColumn.kt
3015959655
/* * Copyright 2016 Benoît Prioux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.binout.soccer.interfaces.rest import io.github.binout.soccer.application.* import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @RequestMapping("rest/players") class PlayersResource( private val getAllPlayers: GetAllPlayers, private val getAllLeaguePlayers: GetAllLeaguePlayers, private val replacePlayer: ReplacePlayer, private val getPlayer: GetPlayer) { @GetMapping fun all() : List<RestPlayer> = getAllPlayers.execute().map { it.toRestModel() } @GetMapping("league") fun allLeague() : List<RestPlayer> = getAllLeaguePlayers.execute().map { it.toRestModel() } @PutMapping("{name}") fun put(@PathVariable("name") name: String, @RequestBody restPlayer: RestPlayer): ResponseEntity<*> { replacePlayer.execute(name, restPlayer.email, restPlayer.isPlayerLeague, restPlayer.isGoalkeeper) return ResponseEntity.ok().build<Any>() } @GetMapping("{name}") fun get(name: String): ResponseEntity<*> = getPlayer.execute(name) ?.let { ResponseEntity.ok(it.toRestModel()) } ?: ResponseEntity.notFound().build<Any>() } @RestController @RequestMapping("rest/players-stats") class PlayerStatsResource(val getAllPlayerStats: GetAllPlayerStats) { @GetMapping fun all() : List<RestPlayerStat> = getAllPlayerStats.execute().map { it.toRestModel() } }
src/main/kotlin/io/github/binout/soccer/interfaces/rest/PlayersResource.kt
1271576295
package net.nemerosa.ontrack.extension.chart.support import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.model.exceptions.InputException import java.time.LocalDateTime data class Interval( val start: LocalDateTime, val end: LocalDateTime, ) { fun split(intervalPeriod: IntervalPeriod): List<Interval> { check(start < end) { "Start must be < end" } val result = mutableListOf<Interval>() var start = this.start while (start < this.end) { val end = intervalPeriod.addTo(start) result += Interval(start, end) start = end } return result } operator fun contains(timestamp: LocalDateTime): Boolean = timestamp >= start && timestamp < end companion object { private val fixed = "(\\d+)([dwmy])".toRegex() private val explicit = "(\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d)-(\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d)".toRegex() fun parse(value: String, ref: LocalDateTime = Time.now()): Interval { val f = fixed.matchEntire(value) return if (f != null) { val count = f.groupValues[1].toLong() val type = f.groupValues[2] fixed(value, count, type, ref) } else { val x = explicit.matchEntire(value) if (x != null) { val start = Time.fromStorage(x.groupValues[1]) ?: throw IntervalFormatException("Cannot parse interval start date: ${x.groupValues[1]}") val end = Time.fromStorage(x.groupValues[2]) ?: throw IntervalFormatException("Cannot parse interval start date: ${x.groupValues[2]}") Interval(start, end) } else { throw IntervalFormatException("Cannot parse interval: $value") } } } private fun fixed(value: String, count: Long, type: String, ref: LocalDateTime): Interval { val start = when (type) { "d" -> ref.minusDays(count) "w" -> ref.minusWeeks(count) "m" -> ref.minusMonths(count) "y" -> ref.minusYears(count) else -> throw IntervalFormatException("Unknown time interval [$type] in $value") } return Interval(start, ref) } } } class IntervalFormatException(message: String) : InputException(message)
ontrack-extension-chart/src/main/java/net/nemerosa/ontrack/extension/chart/support/Interval.kt
2820749153
/* * Copyright 2010-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.kotlin.backend.konan.lower import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.lower.irBlock import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName import org.jetbrains.kotlin.backend.konan.ir.buildSimpleAnnotation import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrFieldImpl import org.jetbrains.kotlin.ir.descriptors.WrappedFieldDescriptor import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrLocalDelegatedPropertyReference import org.jetbrains.kotlin.ir.expressions.IrPropertyReference import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrFieldSymbolImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.typeWith import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.name.Name internal class PropertyDelegationLowering(val context: Context) : FileLoweringPass { private var tempIndex = 0 private val kTypeGenerator = KTypeGenerator(context) private fun getKPropertyImplConstructor(receiverTypes: List<IrType>, returnType: IrType, isLocal: Boolean, isMutable: Boolean) : Pair<IrConstructorSymbol, List<IrType>> { val symbols = context.ir.symbols val classSymbol = if (isLocal) { assert(receiverTypes.isEmpty()) { "Local delegated property cannot have explicit receiver" } when { isMutable -> symbols.kLocalDelegatedMutablePropertyImpl else -> symbols.kLocalDelegatedPropertyImpl } } else { when (receiverTypes.size) { 0 -> when { isMutable -> symbols.kMutableProperty0Impl else -> symbols.kProperty0Impl } 1 -> when { isMutable -> symbols.kMutableProperty1Impl else -> symbols.kProperty1Impl } 2 -> when { isMutable -> symbols.kMutableProperty2Impl else -> symbols.kProperty2Impl } else -> throw AssertionError("More than 2 receivers is not allowed") } } val arguments = (receiverTypes + listOf(returnType)) return classSymbol.constructors.single() to arguments } override fun lower(irFile: IrFile) { // Somehow there is no reasonable common ancestor for IrProperty and IrLocalDelegatedProperty, // so index by IrDeclaration. val kProperties = mutableMapOf<IrDeclaration, Pair<IrExpression, Int>>() val arrayClass = context.ir.symbols.array.owner val arrayItemGetter = arrayClass.functions.single { it.name == Name.identifier("get") } val anyType = context.irBuiltIns.anyType val kPropertyImplType = context.ir.symbols.kProperty1Impl.typeWith(anyType, anyType) val kPropertiesFieldType: IrType = context.ir.symbols.array.typeWith(kPropertyImplType) val kPropertiesField = WrappedFieldDescriptor().let { IrFieldImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, DECLARATION_ORIGIN_KPROPERTIES_FOR_DELEGATION, IrFieldSymbolImpl(it), "KPROPERTIES".synthesizedName, kPropertiesFieldType, DescriptorVisibilities.PRIVATE, isFinal = true, isExternal = false, isStatic = true, ).apply { it.bind(this) parent = irFile annotations += buildSimpleAnnotation(context.irBuiltIns, startOffset, endOffset, context.ir.symbols.sharedImmutable.owner) } } irFile.transformChildrenVoid(object : IrElementTransformerVoidWithContext() { override fun visitPropertyReference(expression: IrPropertyReference): IrExpression { expression.transformChildrenVoid(this) val startOffset = expression.startOffset val endOffset = expression.endOffset val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset) irBuilder.run { val receiversCount = listOf(expression.dispatchReceiver, expression.extensionReceiver).count { it != null } return when (receiversCount) { 1 -> createKProperty(expression, this) // Has receiver. 2 -> error("Callable reference to properties with two receivers is not allowed: ${expression.symbol.owner.name}") else -> { // Cache KProperties with no arguments. val field = kProperties.getOrPut(expression.symbol.owner) { createKProperty(expression, this) to kProperties.size } irCall(arrayItemGetter).apply { dispatchReceiver = irGetField(null, kPropertiesField) putValueArgument(0, irInt(field.second)) } } } } } override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression { expression.transformChildrenVoid(this) val startOffset = expression.startOffset val endOffset = expression.endOffset val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset) irBuilder.run { val receiversCount = listOf(expression.dispatchReceiver, expression.extensionReceiver).count { it != null } if (receiversCount == 2) throw AssertionError("Callable reference to properties with two receivers is not allowed: ${expression}") else { // Cache KProperties with no arguments. // TODO: what about `receiversCount == 1` case? val field = kProperties.getOrPut(expression.symbol.owner) { createLocalKProperty( expression.symbol.owner.name.asString(), expression.getter.owner.returnType, this ) to kProperties.size } return irCall(arrayItemGetter).apply { dispatchReceiver = irGetField(null, kPropertiesField) putValueArgument(0, irInt(field.second)) } } } } }) if (kProperties.isNotEmpty()) { val initializers = kProperties.values.sortedBy { it.second }.map { it.first } // TODO: move to object for lazy initialization. irFile.declarations.add(0, kPropertiesField.apply { initializer = IrExpressionBodyImpl(startOffset, endOffset, context.createArrayOfExpression(startOffset, endOffset, kPropertyImplType, initializers)) }) } } private fun createKProperty(expression: IrPropertyReference, irBuilder: IrBuilderWithScope): IrExpression { val startOffset = expression.startOffset val endOffset = expression.endOffset return irBuilder.irBlock(expression) { val receiverTypes = mutableListOf<IrType>() val dispatchReceiver = expression.dispatchReceiver.let { if (it == null) null else irTemporary(value = it, nameHint = "\$dispatchReceiver${tempIndex++}") } val extensionReceiver = expression.extensionReceiver.let { if (it == null) null else irTemporary(value = it, nameHint = "\$extensionReceiver${tempIndex++}") } val returnType = expression.getter?.owner?.returnType ?: expression.field!!.owner.type val getterCallableReference = expression.getter?.owner?.let { getter -> getter.extensionReceiverParameter.let { if (it != null && expression.extensionReceiver == null) receiverTypes.add(it.type) } getter.dispatchReceiverParameter.let { if (it != null && expression.dispatchReceiver == null) receiverTypes.add(it.type) } val getterKFunctionType = this@PropertyDelegationLowering.context.ir.symbols.getKFunctionType( returnType, receiverTypes ) IrFunctionReferenceImpl( startOffset = startOffset, endOffset = endOffset, type = getterKFunctionType, symbol = expression.getter!!, typeArgumentsCount = getter.typeParameters.size, valueArgumentsCount = getter.valueParameters.size, reflectionTarget = expression.getter!! ).apply { this.dispatchReceiver = dispatchReceiver?.let { irGet(it) } this.extensionReceiver = extensionReceiver?.let { irGet(it) } for (index in 0 until expression.typeArgumentsCount) putTypeArgument(index, expression.getTypeArgument(index)) } } val setterCallableReference = expression.setter?.owner?.let { setter -> if (!isKMutablePropertyType(expression.type)) null else { val setterKFunctionType = this@PropertyDelegationLowering.context.ir.symbols.getKFunctionType( context.irBuiltIns.unitType, receiverTypes + returnType ) IrFunctionReferenceImpl( startOffset = startOffset, endOffset = endOffset, type = setterKFunctionType, symbol = expression.setter!!, typeArgumentsCount = setter.typeParameters.size, valueArgumentsCount = setter.valueParameters.size, reflectionTarget = expression.setter!! ).apply { this.dispatchReceiver = dispatchReceiver?.let { irGet(it) } this.extensionReceiver = extensionReceiver?.let { irGet(it) } for (index in 0 until expression.typeArgumentsCount) putTypeArgument(index, expression.getTypeArgument(index)) } } } val (symbol, constructorTypeArguments) = getKPropertyImplConstructor( receiverTypes = receiverTypes, returnType = returnType, isLocal = false, isMutable = setterCallableReference != null) val initializer = irCall(symbol.owner, constructorTypeArguments).apply { putValueArgument(0, irString(expression.symbol.owner.name.asString())) putValueArgument(1, with(kTypeGenerator) { irKType(returnType) }) if (getterCallableReference != null) putValueArgument(2, getterCallableReference) if (setterCallableReference != null) putValueArgument(3, setterCallableReference) } +initializer } } private fun createLocalKProperty(propertyName: String, propertyType: IrType, irBuilder: IrBuilderWithScope): IrExpression { irBuilder.run { val (symbol, constructorTypeArguments) = getKPropertyImplConstructor( receiverTypes = emptyList(), returnType = propertyType, isLocal = true, isMutable = false) val initializer = irCall(symbol.owner, constructorTypeArguments).apply { putValueArgument(0, irString(propertyName)) putValueArgument(1, with(kTypeGenerator) { irKType(propertyType) }) } return initializer } } private fun isKMutablePropertyType(type: IrType): Boolean { if (type !is IrSimpleType) return false val expectedClass = when (type.arguments.size) { 0 -> return false 1 -> context.ir.symbols.kMutableProperty0 2 -> context.ir.symbols.kMutableProperty1 3 -> context.ir.symbols.kMutableProperty2 else -> throw AssertionError("More than 2 receivers is not allowed") } return type.classifier == expectedClass } private object DECLARATION_ORIGIN_KPROPERTIES_FOR_DELEGATION : IrDeclarationOriginImpl("KPROPERTIES_FOR_DELEGATION") }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/DelegationLowering.kt
3653606020
package com.jraska.github.client.repo.ui import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.airbnb.epoxy.SimpleEpoxyAdapter import com.airbnb.epoxy.SimpleEpoxyModel import com.google.android.material.floatingactionbutton.FloatingActionButton import com.jraska.github.client.core.android.viewModel import com.jraska.github.client.repo.R import com.jraska.github.client.repo.RepoDetailViewModel import com.jraska.github.client.repo.model.RepoDetail import com.jraska.github.client.users.ui.ErrorHandler import com.jraska.github.client.users.ui.SimpleTextModel internal class RepoDetailActivity : AppCompatActivity() { private val viewModel: RepoDetailViewModel by lazy { viewModel(RepoDetailViewModel::class.java) } private val repoDetailRecycler: RecyclerView get() = findViewById(R.id.repo_detail_recycler) private fun fullRepoName(): String { return intent.getStringExtra(EXTRA_FULL_REPO_NAME)!! } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_repo_detail) setSupportActionBar(findViewById(R.id.toolbar)) repoDetailRecycler.layoutManager = LinearLayoutManager(this) title = fullRepoName() val liveData = viewModel.repoDetail(fullRepoName()) liveData.observe(this, { this.setState(it) }) findViewById<FloatingActionButton>(R.id.repo_detail_github_fab) .setOnClickListener { viewModel.onGitHubIconClicked(fullRepoName()) } } private fun setState(state: RepoDetailViewModel.ViewState) { when (state) { is RepoDetailViewModel.ViewState.Loading -> showLoading() is RepoDetailViewModel.ViewState.Error -> setError(state.error) is RepoDetailViewModel.ViewState.ShowRepo -> setRepoDetail(state.repo) } } private fun showLoading() { findViewById<RecyclerView>(R.id.repo_detail_recycler).adapter = SimpleEpoxyAdapter().apply { addModels(SimpleEpoxyModel(R.layout.item_loading)) } } private fun setError(error: Throwable) { ErrorHandler.displayError(error, repoDetailRecycler) } private fun setRepoDetail(repoDetail: RepoDetail) { val adapter = SimpleEpoxyAdapter() adapter.addModels(RepoDetailHeaderModel(repoDetail)) val languageText = getString( R.string.repo_detail_language_used_template, repoDetail.data.language ) adapter.addModels(SimpleTextModel(languageText)) val issuesText = getString( R.string.repo_detail_issues_template, repoDetail.data.issuesCount.toString() ) adapter.addModels(SimpleTextModel(issuesText)) repoDetailRecycler.adapter = adapter } companion object { private const val EXTRA_FULL_REPO_NAME = "fullRepoName" fun start(from: Activity, fullRepoName: String) { val intent = Intent(from, RepoDetailActivity::class.java) intent.putExtra(EXTRA_FULL_REPO_NAME, fullRepoName) from.startActivity(intent) } } }
feature/repo/src/main/java/com/jraska/github/client/repo/ui/RepoDetailActivity.kt
1444672207
package com.xiaojinzi.component.support import com.xiaojinzi.component.anno.support.CheckClassNameAnno /** * 懒加载设计 * time : 2018/11/27 * * @author : xiaojinzi */ @CheckClassNameAnno interface Callable<T> { /** * 获取实际的兑现 * * @return 获取实现对象 */ fun get(): T }
ComponentImpl/src/main/java/com/xiaojinzi/component/support/Callable.kt
3631609961
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql import org.specs2.mutable.Specification import org.joda.time._ class TimeAndDateSpec extends Specification with DatabaseTestHelper { "when processing times and dates" should { "support a time object" in { withHandler { handler -> val create = """CREATE TEMP TABLE messages ( id bigserial NOT NULL, moment time NOT NULL, CONSTRAINT bigserial_column_pkey PRIMARY KEY (id ) )""" executeDdl(handler, create) executePreparedStatement(handler, "INSERT INTO messages (moment) VALUES (?)", Array[Any](new LocalTime(4, 5, 6))) val rows = executePreparedStatement(handler, "select * from messages").rows.get val time = rows(0)("moment").asInstanceOf[LocalTime] time.getHourOfDay === 4 time.getMinuteOfHour === 5 time.getSecondOfMinute === 6 } } "support a time object with microseconds" in { withHandler { handler -> val create = """CREATE TEMP TABLE messages ( id bigserial NOT NULL, moment time(6) NOT NULL, CONSTRAINT bigserial_column_pkey PRIMARY KEY (id ) )""" executeDdl(handler, create) executePreparedStatement(handler, "INSERT INTO messages (moment) VALUES (?)", Array[Any](new LocalTime(4, 5, 6, 134))) val rows = executePreparedStatement(handler, "select * from messages").rows.get val time = rows(0)("moment").asInstanceOf[LocalTime] time.getHourOfDay === 4 time.getMinuteOfHour === 5 time.getSecondOfMinute === 6 time.getMillisOfSecond === 134 } } "support a time with timezone object" in { pending("need to find a way to implement this") withHandler { handler -> val create = """CREATE TEMP TABLE messages ( id bigserial NOT NULL, moment time with time zone NOT NULL, CONSTRAINT bigserial_column_pkey PRIMARY KEY (id ) )""" executeDdl(handler, create) executeQuery(handler, "INSERT INTO messages (moment) VALUES ('04:05:06 -3:00')") val rows = executePreparedStatement(handler, "select * from messages").rows.get val time = rows(0)("moment").asInstanceOf[LocalTime] time.getHourOfDay === 4 time.getMinuteOfHour === 5 time.getSecondOfMinute === 6 } } "support timestamp with timezone" in { withHandler { handler -> val create = """CREATE TEMP TABLE messages ( id bigserial NOT NULL, moment timestamp with time zone NOT NULL, CONSTRAINT bigserial_column_pkey PRIMARY KEY (id ) )""" executeDdl(handler, create) executeQuery(handler, "INSERT INTO messages (moment) VALUES ('1999-01-08 04:05:06 -3:00')") val rows = executePreparedStatement(handler, "SELECT * FROM messages").rows.get rows.length === 1 val dateTime = rows(0)("moment").asInstanceOf[DateTime] // Note: Since this assertion depends on Brazil locale, I think epoch time assertion is preferred // dateTime.getZone.toTimeZone.getRawOffset === -10800000 dateTime.getMillis === 915779106000L } } "support timestamp with timezone and microseconds" in { foreach(1.until(6)) { index -> withHandler { handler -> val create = """CREATE TEMP TABLE messages ( id bigserial NOT NULL, moment timestamp(%d) with time zone NOT NULL, CONSTRAINT bigserial_column_pkey PRIMARY KEY (id ) )""".format(index) executeDdl(handler, create) val seconds = (index.toString * index).toLong executeQuery(handler, "INSERT INTO messages (moment) VALUES ('1999-01-08 04:05:06.%d -3:00')".format(seconds)) val rows = executePreparedStatement(handler, "SELECT * FROM messages").rows.get rows.length === 1 val dateTime = rows(0)("moment").asInstanceOf[DateTime] // Note: Since this assertion depends on Brazil locale, I think epoch time assertion is preferred // dateTime.getZone.toTimeZone.getRawOffset === -10800000 dateTime.getMillis must be_>=(915779106000L) dateTime.getMillis must be_<(915779107000L) } } } "support current_timestamp with timezone" in { withHandler { handler -> val millis = System.currentTimeMillis val create = """CREATE TEMP TABLE messages ( id bigserial NOT NULL, moment timestamp with time zone NOT NULL, CONSTRAINT bigserial_column_pkey PRIMARY KEY (id ) )""" executeDdl(handler, create) executeQuery(handler, "INSERT INTO messages (moment) VALUES (current_timestamp)") val rows = executePreparedStatement(handler, "SELECT * FROM messages").rows.get rows.length === 1 val dateTime = rows(0)("moment").asInstanceOf[DateTime] dateTime.getMillis must beCloseTo(millis, 500) } } "handle sending a time with timezone and return a LocalDateTime for a timestamp without timezone column" in { withTimeHandler { conn -> val date = new DateTime(2190319) executePreparedStatement(conn, "CREATE TEMP TABLE TEST(T TIMESTAMP)") executePreparedStatement(conn, "INSERT INTO TEST(T) VALUES(?)", Array(date)) val result = executePreparedStatement(conn, "SELECT T FROM TEST") val date2 = result.rows.get.head(0) date2 === date.toDateTime(DateTimeZone.UTC).toLocalDateTime } } "supports sending a local date and later a date time object for the same field" in { withTimeHandler { conn -> val date = new LocalDate(2016, 3, 5) executePreparedStatement(conn, "CREATE TEMP TABLE TEST(T TIMESTAMP)") executePreparedStatement(conn, "INSERT INTO TEST(T) VALUES(?)", Array(date)) val result = executePreparedStatement(conn, "SELECT T FROM TEST WHERE T = ?", Array(date)) result.rows.get.size === 1 val dateTime = new LocalDateTime(2016, 3, 5, 0, 0, 0, 0) val dateTimeResult = executePreparedStatement(conn, "SELECT T FROM TEST WHERE T = ?", Array(dateTime)) dateTimeResult.rows.get.size === 1 } } "handle sending a LocalDateTime and return a LocalDateTime for a timestamp without timezone column" in { withTimeHandler { conn -> val date1 = new LocalDateTime(2190319) await(conn.sendPreparedStatement("CREATE TEMP TABLE TEST(T TIMESTAMP)")) await(conn.sendPreparedStatement("INSERT INTO TEST(T) VALUES(?)", Seq(date1))) val result = await(conn.sendPreparedStatement("SELECT T FROM TEST")) val date2 = result.rows.get.head(0) date2 === date1 } } "handle sending a date with timezone and retrieving the date with the same time zone" in { withTimeHandler { conn -> val date1 = new DateTime(2190319) await(conn.sendPreparedStatement("CREATE TEMP TABLE TEST(T TIMESTAMP WITH TIME ZONE)")) await(conn.sendPreparedStatement("INSERT INTO TEST(T) VALUES(?)", Seq(date1))) val result = await(conn.sendPreparedStatement("SELECT T FROM TEST")) val date2 = result.rows.get.head(0) date2 === date1 } } "support intervals" in { withHandler { handler -> executeDdl(handler, "CREATE TEMP TABLE intervals (duration interval NOT NULL)") val p = new Period(1,2,0,4,5,6,7,8) /* postgres normalizes weeks */ executePreparedStatement(handler, "INSERT INTO intervals (duration) VALUES (?)", Array(p)) val rows = executeQuery(handler, "SELECT duration FROM intervals").rows.get rows.length === 1 rows(0)(0) === p } } } }
postgresql-async/src/test/kotlin/com/github/mauricio/async/db/postgresql/TimeAndDateSpec.kt
776459542
package de.xikolo.testing.instrumented.ui import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Espresso.pressBack import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.swipeUp import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.filters.LargeTest import androidx.test.rule.ActivityTestRule import de.xikolo.R import de.xikolo.config.Feature import de.xikolo.controllers.main.MainActivity import de.xikolo.testing.instrumented.mocking.base.BaseMockedTest import de.xikolo.testing.instrumented.ui.helper.NavigationHelper import de.xikolo.testing.instrumented.ui.helper.ViewHierarchyHelper.childAtPosition import org.hamcrest.Matchers.allOf import org.junit.Before import org.junit.Rule import org.junit.Test @LargeTest class ChannelsTest : BaseMockedTest() { @Rule @JvmField var activityTestRule = ActivityTestRule(MainActivity::class.java) /** * Navigates in the app to the channel list. (if applicable) */ @Before fun navigateToChannelList() { if (!Feature.enabled("channels")) { return } NavigationHelper.selectNavigationItem(context, R.string.title_section_channels) } /** * Tests the loading behavior of the channels list. (if applicable) * This is done by testing refreshing via the overflow menu and then asserting at least one list item is shown. */ @Test fun channelLoading() { if (!Feature.enabled("channels")) { return } NavigationHelper.refreshThroughOverflow(context) val cardView = onView( allOf( withId(R.id.container), childAtPosition( allOf( withId(R.id.content_view), childAtPosition( withId(R.id.refresh_layout), 0 ) ), 0 ) ) ) cardView.check( ViewAssertions.matches(isDisplayed()) ) } /** * Tests the behavior of the channel details view. (if applicable) * The first item in the channel list is clicked and then a swipe gesture is performed to simulate scrolling. */ @Test fun channelDetails() { if (!Feature.enabled("channels")) { return } val cardView = onView( allOf( withId(R.id.container), childAtPosition( allOf( withId(R.id.content_view), childAtPosition( withId(R.id.refresh_layout), 0 ) ), 0 ) ) ) cardView.check( ViewAssertions.matches(isDisplayed()) ) cardView.perform(click()) onView( withId(R.id.contentLayout) ).perform(swipeUp()) pressBack() } }
app/src/androidTest/java/de/xikolo/testing/instrumented/ui/ChannelsTest.kt
71444264
package com.esorokin.lantector.ui.plugin.base interface CompositionPlugin : Plugin { fun <T : Plugin> attach(plugin: T): T fun detach(plugin: Plugin) }
app/src/main/java/com/esorokin/lantector/ui/plugin/base/CompositionPlugin.kt
3564754512
package com.emogoth.android.phone.mimi.db import android.util.Log import com.emogoth.android.phone.mimi.db.MimiDatabase.Companion.getInstance import com.emogoth.android.phone.mimi.db.models.HiddenThread import io.reactivex.Single import java.util.concurrent.TimeUnit object HiddenThreadTableConnection { val LOG_TAG: String = HiddenThreadTableConnection::class.java.simpleName @JvmStatic fun fetchHiddenThreads(boardName: String): Single<List<HiddenThread>> { return getInstance()?.hiddenThreads()?.getHiddenThreadsForBoard(boardName) ?.onErrorReturn { throwable: Throwable? -> Log.e(LOG_TAG, "Error loading hidden threads from the database", throwable) emptyList() } ?: Single.just(emptyList()) } @JvmStatic fun hideThread(boardName: String, threadId: Long, sticky: Boolean): Single<Boolean> { return Single.defer { val hiddenThread = HiddenThread() hiddenThread.boardName = boardName hiddenThread.threadId = threadId hiddenThread.time = System.currentTimeMillis() hiddenThread.sticky = (if (sticky) 1 else 0) getInstance()?.hiddenThreads()?.upsert(hiddenThread) ?: return@defer Single.just(false) Single.just(true) } } @JvmStatic fun clearAll(): Single<Boolean> { return Single.defer { getInstance()?.hiddenThreads()?.clear() ?: Single.just(false) Single.just(true) } } @JvmStatic fun prune(days: Int): Single<Boolean> { return Single.defer { val oldestTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(days.toLong()) getInstance()?.hiddenThreads()?.prune(oldestTime) ?: Single.just(false) Single.just(true) } } }
mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/HiddenThreadTableConnection.kt
3218896020
/* * 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.utils fun String.toCamelCase(separator: Char = '_', firstCapital: Boolean = true): String { val builder = StringBuilder() var capitalFlag = firstCapital for (c in this) { when (c) { separator -> capitalFlag = true else -> { builder.append(if (capitalFlag) Character.toUpperCase(c) else Character.toLowerCase(c)) capitalFlag = false } } } return builder.toString() } fun String.toUPPER_CASE(): String { val builder = StringBuilder() for (c in this) { if (c.isUpperCase() && builder.length() > 0) builder.append('_') builder.append(c.toUpperCase()) } return builder.toString() }
dsl/src/org/jetbrains/android/anko/utils/stringUtils.kt
2191528533
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.ui import android.content.Context import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.widget.TextView import com.ichi2.anki.R import com.ichi2.anki.reviewer.Binding import timber.log.Timber typealias KeyCode = Int /** * Square dialog which allows a user to select a [Binding] for a key press * This does not yet support bluetooth headsets. */ class KeyPicker(val rootLayout: View) { private val textView: TextView = rootLayout.findViewById(R.id.key_picker_selected_key) private val context: Context get() = rootLayout.context private var text: String set(value) { textView.text = value } get() = textView.text.toString() private var onBindingChangedListener: ((Binding) -> Unit)? = null private var isValidKeyCode: ((KeyCode) -> Boolean)? = null /** Currently bound key */ private var binding: Binding? = null fun getBinding(): Binding? = binding fun dispatchKeyEvent(event: KeyEvent): Boolean { if (event.action != KeyEvent.ACTION_DOWN) return true // When accepting a keypress, we only want to find the keycode, not the unicode character. val isValidKeyCode = isValidKeyCode val maybeBinding = Binding.key(event).stream().filter { x -> x.isKeyCode && (isValidKeyCode == null || isValidKeyCode(x.getKeycode()!!)) }.findFirst() if (!maybeBinding.isPresent) { return true } val newBinding = maybeBinding.get() Timber.d("Changed key to '%s'", newBinding) binding = newBinding text = newBinding.toDisplayString(context) onBindingChangedListener?.invoke(newBinding) return true } fun setBindingChangedListener(listener: (Binding) -> Unit) { onBindingChangedListener = listener } fun setKeycodeValidation(validation: (KeyCode) -> Boolean) { isValidKeyCode = validation } init { textView.requestFocus() textView.setOnKeyListener { _, _, event -> dispatchKeyEvent(event) } } companion object { fun inflate(context: Context): KeyPicker { val layout = LayoutInflater.from(context).inflate(R.layout.dialog_key_picker, null) return KeyPicker(layout) } } }
AnkiDroid/src/main/java/com/ichi2/ui/KeyPicker.kt
3625765633
package com.sksamuel.rxhive.parquet.setters import org.apache.parquet.io.api.Binary import org.apache.parquet.io.api.RecordConsumer object EnumSetter : Setter { override fun set(consumer: RecordConsumer, value: Any) { when (value) { is String -> consumer.addBinary(Binary.fromString(value)) else -> throw UnsupportedOperationException("Unsupported value $value for enum type") } } }
rxhive-parquet/src/main/kotlin/com/sksamuel/rxhive/parquet/setters/EnumSetter.kt
1360609749
package com.ztiany.acc import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { companion object { const val LIVE_DATA = "LiveData" const val RXJAVA = "RxJava" const val TYPE = "TYPE" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupView() } private fun setupView() { btnLiveData.setOnClickListener { val intent = Intent(this, ContentActivity::class.java) intent.putExtra(TYPE, LIVE_DATA) startActivity(intent) } btnRxJava.setOnClickListener { val intent = Intent(this, ContentActivity::class.java) intent.putExtra(TYPE, RXJAVA) startActivity(intent) } } }
Android/AAC-Sample/Paging-Sample/src/main/java/com/ztiany/acc/MainActivity.kt
3225569719
package com.telenav.osv.data.collector.datatype.datatypes import com.telenav.osv.data.collector.datatype.util.LibraryUtil /** * Class which uses the proximity sensor to retrieve whether or not an object is close the it */ class ProximityObject(isClose: Boolean, statusCode: Int) : BaseObject<Boolean?>(isClose, statusCode, LibraryUtil.PROXIMITY) { constructor(statusCode: Int) : this(false, statusCode) {} val isClose: Boolean get() = actualValue!! init { dataSource = LibraryUtil.PHONE_SOURCE } }
app/src/main/java/com/telenav/osv/data/collector/datatype/datatypes/ProximityObject.kt
1392409627
package com.uchuhimo.privateAccess class A(private val a: Int) { fun accessOtherA(otherA: A) { println(otherA.a) } } class B<out T : Number>(private var b: T) { fun accessOtherB(otherB: B<Int>) { // `b` is private to `this` since variance // otherB.b println(otherB.getB()) } fun getB(): T = b } fun main(args: Array<String>) { val a1 = A(1) val a2 = A(2) a1.accessOtherA(a2) val b1 = B(1) val b2 = B(2) b1.accessOtherB(b2) }
lang/src/main/kotlin/com/uchuhimo/privateAccess/Play.kt
1091109617
package com.matejdro.wearmusiccenter.view.buttonconfig import android.Manifest import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.graphics.PorterDuff import android.graphics.drawable.VectorDrawable import android.os.Bundle import android.os.PersistableBundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentContainerView import com.matejdro.wearmusiccenter.R import com.matejdro.wearmusiccenter.actions.NullAction import com.matejdro.wearmusiccenter.actions.PhoneAction import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonGesture import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonInfo import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_DOUBLE_TAP import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_LONG_TAP import com.matejdro.wearmusiccenter.common.buttonconfig.GESTURE_SINGLE_TAP import com.matejdro.wearmusiccenter.common.buttonconfig.NUM_BUTTON_GESTURES import com.matejdro.wearmusiccenter.config.ActionConfig import com.matejdro.wearmusiccenter.config.CustomIconStorage import com.matejdro.wearmusiccenter.config.buttons.ButtonConfig import com.matejdro.wearmusiccenter.databinding.PopupGesturePickerBinding import com.matejdro.wearmusiccenter.di.LocalActivityConfig import com.matejdro.wearmusiccenter.view.ActivityResultReceiver import com.matejdro.wearmusiccenter.view.actionconfigs.ActionConfigFragment import com.matejdro.wearutils.miscutils.BitmapUtils import dagger.android.support.AndroidSupportInjection import javax.inject.Inject class GesturePickerFragment : DialogFragment() { companion object { const val REQUEST_CODE_SAVE_NOTIFICATION = 1578 private const val PARAM_SETS_PLAYBACK_ACTIONS = "SetsPlaybackActions" private const val PARAM_BUTTON_INFO = "ButtonInfo" private const val PARAM_BUTTON_NAME = "ButtonName" private const val PARAM_SUPPORTS_LONG_PRESS = "SupportsLongPress" private const val REQUEST_CODE_PICK_ACTION = 5891 private const val REQUEST_CODE_PICK_ACTION_TO = REQUEST_CODE_PICK_ACTION + NUM_BUTTON_GESTURES private const val REQUEST_CODE_PICK_ICON = 5991 fun newInstance(setsPlaybackButtons: Boolean, baseButtonInfo: ButtonInfo, buttonName: String, supportsLongPress: Boolean): GesturePickerFragment { val fragment = GesturePickerFragment() val args = Bundle() args.putBoolean(PARAM_SETS_PLAYBACK_ACTIONS, setsPlaybackButtons) args.putParcelable(PARAM_BUTTON_INFO, baseButtonInfo.serialize()) args.putString(PARAM_BUTTON_NAME, buttonName) args.putBoolean(PARAM_SUPPORTS_LONG_PRESS, supportsLongPress) fragment.arguments = args return fragment } } private var setsPlaybackButtons: Boolean = false private lateinit var binding: PopupGesturePickerBinding private lateinit var baseButtonInfo: ButtonInfo private lateinit var buttonName: String private var supportsLongPress: Boolean = false private lateinit var actions: Array<PhoneAction?> @Inject @LocalActivityConfig lateinit var config: ActionConfig @Inject lateinit var customIconStorage: CustomIconStorage private lateinit var buttonConfig: ButtonConfig private lateinit var buttons: Array<ButtonSet> private var anyActionChanged = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) baseButtonInfo = ButtonInfo(requireArguments().getParcelable(PARAM_BUTTON_INFO)!!) buttonName = requireArguments().getString(PARAM_BUTTON_NAME)!! setsPlaybackButtons = requireArguments().getBoolean(PARAM_SETS_PLAYBACK_ACTIONS) supportsLongPress = requireArguments().getBoolean(PARAM_SUPPORTS_LONG_PRESS) AndroidSupportInjection.inject(this) setStyle(STYLE_NORMAL, R.style.AppTheme_Dialog_Short) buttonConfig = if (setsPlaybackButtons) config.getPlayingConfig() else config.getStoppedConfig() actions = Array(NUM_BUTTON_GESTURES) { buttonConfig.getScreenAction(baseButtonInfo.copy(gesture = it)) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = PopupGesturePickerBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dialog!!.setCanceledOnTouchOutside(true) dialog!!.setTitle(buttonName) buttons = arrayOf( ButtonSet(binding.singlePressButton, binding.singlePressConfigFragment), ButtonSet(binding.doublePressButton, binding.doublePressConfigFragment), ButtonSet(binding.longPressButton, binding.longPressConfigFragment) ) updateButton(buttons.elementAt(0), GESTURE_SINGLE_TAP) updateButton(buttons.elementAt(1), GESTURE_DOUBLE_TAP) updateButton(buttons.elementAt(2), GESTURE_LONG_TAP) binding.customizeIcon.isVisible = !baseButtonInfo.physicalButton binding.longPressDescription.isVisible = supportsLongPress binding.longPressButton.isVisible = supportsLongPress binding.customizeIcon.setOnClickListener { startIconSelection() } binding.singlePressButton.setOnClickListener { changeAction(GESTURE_SINGLE_TAP) } binding.doublePressButton.setOnClickListener { changeAction(GESTURE_DOUBLE_TAP) } binding.longPressButton.setOnClickListener { changeAction(GESTURE_LONG_TAP) } binding.okButton.setOnClickListener { save() } binding.cancelButton.setOnClickListener { dismiss() } } private fun changeAction(gesture: Int) { val requestCode = REQUEST_CODE_PICK_ACTION + gesture startActivityForResult(Intent(activity, ActionPickerActivity::class.java), requestCode) } private fun updateButton(buttonSet: ButtonSet, @ButtonGesture gesture: Int) { val phoneAction = actions[gesture] updateButton(buttonSet, phoneAction) } private fun updateButton(buttonSet: ButtonSet, phoneAction: PhoneAction?) { var mutableAction = phoneAction if (mutableAction == null) { mutableAction = NullAction(requireActivity()) } var icon = customIconStorage[mutableAction] if (icon is VectorDrawable) { icon = icon.mutate() icon.setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY) } val iconSize = resources.getDimensionPixelSize(R.dimen.action_icon_size) icon.setBounds(0, 0, iconSize, iconSize) buttonSet.button.text = mutableAction.title buttonSet.button.setCompoundDrawables(icon, null, null, null) val configFragmentClass = mutableAction.configFragment if (configFragmentClass != null) { @Suppress("UNCHECKED_CAST") val configFragment: ActionConfigFragment<PhoneAction> = configFragmentClass.newInstance() as ActionConfigFragment<PhoneAction> childFragmentManager.beginTransaction() .replace(buttonSet.configFragmentContainer.id, configFragment) .commit() configFragment.load(mutableAction) } else { val existingFragment = childFragmentManager.findFragmentById(buttonSet.configFragmentContainer.id) existingFragment?.let { childFragmentManager.beginTransaction() .remove(it) .commit() } } } fun save() { val anyActionHasConfigFragment = buttons .mapNotNull { childFragmentManager.findFragmentById(it.configFragmentContainer.id) } .isNotEmpty() if (anyActionChanged || anyActionHasConfigFragment) { for ((gesture, action) in actions.withIndex()) { val button = buttons[gesture] if (action != null) { @Suppress("UNCHECKED_CAST") (childFragmentManager.findFragmentById(button.configFragmentContainer.id) as? ActionConfigFragment<PhoneAction>) ?.save(action) } val buttonInfo = baseButtonInfo.copy(gesture = gesture) buttonConfig.saveButtonAction(buttonInfo, action) } (activity as ActivityResultReceiver) .onActivityResult(REQUEST_CODE_SAVE_NOTIFICATION, Activity.RESULT_OK, null) } dismiss() } private fun startIconSelection() { if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestStoragePermission() return } try { var intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" intent = Intent.createChooser(intent, getString(R.string.icon_selection_title)) startActivityForResult(intent, REQUEST_CODE_PICK_ICON) } catch (ignored: ActivityNotFoundException) { AlertDialog.Builder(requireContext()) .setTitle(R.string.icon_selection_title) .setMessage(R.string.icon_selection_no_icon_pack) .setPositiveButton(android.R.string.ok, null) .show() } } private fun requestStoragePermission() { AlertDialog.Builder(requireContext()) .setTitle(R.string.icon_selection_title) .setMessage(R.string.icon_selection_no_storage_permission) .setPositiveButton(android.R.string.ok, null) .setOnDismissListener { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE_PICK_ACTION) } .show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode != Activity.RESULT_OK || data == null) { return } if (requestCode in REQUEST_CODE_PICK_ACTION until REQUEST_CODE_PICK_ACTION_TO) { val gesture = requestCode - REQUEST_CODE_PICK_ACTION val actionBundle = data.getParcelableExtra<PersistableBundle>(ActionPickerActivity.EXTRA_ACTION_BUNDLE) val action = PhoneAction.deserialize<PhoneAction>(requireActivity(), actionBundle) anyActionChanged = anyActionChanged || action != actions[gesture] actions[gesture] = action updateButton(buttons[gesture], action) } else if (requestCode == REQUEST_CODE_PICK_ICON) { val iconUri = data.data!! val action = actions[GESTURE_SINGLE_TAP].let { if (it == null) { val newAction = NullAction(requireContext()) actions[GESTURE_SINGLE_TAP] = newAction newAction } else { it } } val bitmap = BitmapUtils.getBitmap(BitmapUtils.getDrawableFromUri(activity, iconUri)) ?: return action.customIconUri = iconUri customIconStorage.setIcon(iconUri, bitmap) anyActionChanged = true updateButton(buttons[GESTURE_SINGLE_TAP], action) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (permissions.isNotEmpty() && permissions[0] == Manifest.permission.READ_EXTERNAL_STORAGE && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startIconSelection() } } private class ButtonSet(val button: Button, val configFragmentContainer: FragmentContainerView) }
mobile/src/main/java/com/matejdro/wearmusiccenter/view/buttonconfig/GesturePickerFragment.kt
4012428972
package de.vanita5.twittnuker.view import android.content.Context import android.util.AttributeSet import org.mariotaku.chameleon.Chameleon import org.mariotaku.chameleon.ChameleonUtils import org.mariotaku.chameleon.view.ChameleonSwitchCompat class ToolbarToggleSwitch @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null ) : ChameleonSwitchCompat(context, attributeSet) { override fun createAppearance(context: Context, attributeSet: AttributeSet, theme: Chameleon.Theme): Appearance? { val appearance = Appearance() appearance.accentColor = if (theme.isToolbarColored) { ChameleonUtils.getColorDependent(theme.colorToolbar) } else { theme.colorAccent } appearance.isDark = !ChameleonUtils.isColorLight(theme.colorBackground) return appearance } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/ToolbarToggleSwitch.kt
3297658164
package com.stripe.android.view import android.graphics.Color import androidx.annotation.ColorInt import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.CustomerSession import com.stripe.android.PaymentSessionFixtures import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.robolectric.RobolectricTestRunner import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) internal class StripeColorUtilsTest { private val activityScenarioFactory = ActivityScenarioFactory( ApplicationProvider.getApplicationContext() ) @BeforeTest fun setup() { CustomerSession.instance = mock() } @Test fun getThemeAccentColor_getsNonzeroColor() { activityScenarioFactory.create<PaymentFlowActivity>( PaymentSessionFixtures.PAYMENT_FLOW_ARGS ).use { activityScenario -> activityScenario.onActivity { assertThat(Color.alpha(StripeColorUtils(it).colorAccent)) .isGreaterThan(0) } } } @Test fun getThemeColorControlNormal_getsNonzeroColor() { activityScenarioFactory.create<PaymentFlowActivity>( PaymentSessionFixtures.PAYMENT_FLOW_ARGS ).use { activityScenario -> activityScenario.onActivity { assertThat(Color.alpha(StripeColorUtils(it).colorControlNormal)) .isGreaterThan(0) } } } @Test fun isColorTransparent_whenColorIsZero_returnsTrue() { assertTrue(StripeColorUtils.isColorTransparent(0)) } @Test fun isColorTransparent_whenColorIsNonzeroButHasLowAlpha_returnsTrue() { @ColorInt val invisibleBlue = 0x050000ff @ColorInt val invisibleRed = 0x0bff0000 assertTrue(StripeColorUtils.isColorTransparent(invisibleBlue)) assertTrue(StripeColorUtils.isColorTransparent(invisibleRed)) } @Test fun isColorTransparent_whenColorIsNotCloseToTransparent_returnsFalse() { @ColorInt val brightWhite = -0x1 @ColorInt val completelyBlack = -0x1000000 assertFalse(StripeColorUtils.isColorTransparent(brightWhite)) assertFalse(StripeColorUtils.isColorTransparent(completelyBlack)) } @Test fun isColorDark_forExampleLightColors_returnsFalse() { @ColorInt val middleGray = 0x888888 @ColorInt val offWhite = 0xfaebd7 @ColorInt val lightCyan = 0x8feffb @ColorInt val lightYellow = 0xfcf4b2 @ColorInt val lightBlue = 0x9cdbff assertFalse(StripeColorUtils.isColorDark(middleGray)) assertFalse(StripeColorUtils.isColorDark(offWhite)) assertFalse(StripeColorUtils.isColorDark(lightCyan)) assertFalse(StripeColorUtils.isColorDark(lightYellow)) assertFalse(StripeColorUtils.isColorDark(lightBlue)) assertFalse(StripeColorUtils.isColorDark(Color.WHITE)) } @Test fun isColorDark_forExampleDarkColors_returnsTrue() { @ColorInt val logoBlue = 0x6772e5 @ColorInt val slate = 0x525f7f @ColorInt val darkPurple = 0x6b3791 @ColorInt val darkishRed = 0x9e2146 assertTrue(StripeColorUtils.isColorDark(logoBlue)) assertTrue(StripeColorUtils.isColorDark(slate)) assertTrue(StripeColorUtils.isColorDark(darkPurple)) assertTrue(StripeColorUtils.isColorDark(darkishRed)) assertTrue(StripeColorUtils.isColorDark(Color.BLACK)) } }
payments-core/src/test/java/com/stripe/android/view/StripeColorUtilsTest.kt
1611802194
package com.ivantrogrlic.leaguestats.model /** * Created by ivanTrogrlic on 20/07/2017. */ data class Participant(val stats: ParticipantStats, val participantId: Int, val spell1Id: Int, val spell2Id: Int, val championId: Int, val spell1Name: String?, val spell2Name: String?, val championName: String?)
app/src/main/java/com/ivantrogrlic/leaguestats/model/Participant.kt
1931804191
package com.stripe.android.core.networking import com.stripe.android.core.Logger import com.stripe.android.core.exception.APIConnectionException import com.stripe.android.core.networking.DefaultAnalyticsRequestExecutor.Companion.FIELD_EVENT import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.same import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import kotlin.test.Test @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) class AnalyticsRequestExecutorTest { private val logger: Logger = mock() private val testDispatcher = UnconfinedTestDispatcher() private val stripeNetworkClient: StripeNetworkClient = mock() private val analyticsRequestExecutor = DefaultAnalyticsRequestExecutor( stripeNetworkClient = stripeNetworkClient, logger = logger, workContext = testDispatcher ) private val analyticsRequest = AnalyticsRequest(mapOf(FIELD_EVENT to TEST_EVENT), emptyMap()) @Test fun `executeAsync should log and delegate to stripeNetworkClient`() = runTest { analyticsRequestExecutor.executeAsync(analyticsRequest) verify(logger).info( "Event: $TEST_EVENT" ) verify(stripeNetworkClient).executeRequest(same(analyticsRequest)) } @Test fun `executeAsync should log error when stripeNetworkClient fails`() = runTest { val expectedException = APIConnectionException("something went wrong") whenever(stripeNetworkClient.executeRequest(any())).thenThrow(expectedException) analyticsRequestExecutor.executeAsync(analyticsRequest) verify(logger).info( "Event: $TEST_EVENT" ) verify(stripeNetworkClient).executeRequest(same(analyticsRequest)) verify(logger).error( eq("Exception while making analytics request"), same(expectedException) ) } private companion object { const val TEST_EVENT = "TEST_EVENT" } }
stripe-core/src/test/java/com/stripe/android/core/networking/AnalyticsRequestExecutorTest.kt
964562532
package com.github.kotlinz.kotlinz.data.identity import com.github.kotlinz.kotlinz.K1 import com.github.kotlinz.kotlinz.type.monad.Comonad interface IdentityComonad: Comonad<Identity.T>, IdentityFunctor { override fun <A> extract(v: K1<Identity.T, A>): A = Identity.narrow(v).value override fun <A> duplicate(v: K1<Identity.T, A>): Identity<K1<Identity.T, A>> { return Identity(Identity.Companion.narrow(v)) } override fun <A, B> extend(f: (K1<Identity.T, A>) -> B, v: K1<Identity.T, A>): Identity<B> { return Identity.narrow(fmap(f, duplicate(v))) } }
src/main/kotlin/com/github/kotlinz/kotlinz/data/identity/IdentityComonad.kt
896760814
package eu.livotov.labs.androidappskeleton import android.Manifest import android.content.Context import android.location.Location import android.location.LocationManager import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability class LocationHelper() { companion object { private val PK = 180 / 3.1415926 private val EARTH_RADIUS = 6371.0 fun findDistanceInKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double = Math.acos(Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2)) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * (Math.cos(Math.toRadians(lon1)) * Math.cos(Math.toRadians(lon2)) + Math.sin(Math.toRadians(lon1)) * Math.sin(Math.toRadians(lon2)))) * EARTH_RADIUS fun findDistanceInKm(fromLocation: Location, toLocation: Location): Double = Math.abs(fromLocation.distanceTo(toLocation)).toDouble() / 1000 fun isLocationServiceEnabled(ctx: Context = App.self): Boolean { var lm: LocationManager? = null var gps_enabled = false var network_enabled = false if (lm == null) { lm = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager } try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER) } catch (ignored: Exception) { } try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) } catch (ignored: Exception) { } return gps_enabled || network_enabled } fun isGoogleServicesPresent(ctx: Context = App.self): Boolean { return try { GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(ctx) == ConnectionResult.SUCCESS } catch (err: Throwable) { false } } fun getLocationServicesGlobalStatus(): LocationServicesStatus { return if (!App.hasPermissions(Manifest.permission.ACCESS_COARSE_LOCATION)) { LocationServicesStatus.NoPermissions } else if (!isLocationServiceEnabled()) { LocationServicesStatus.NotEnabled } else if (!isGoogleServicesPresent()) { LocationServicesStatus.HasGeopositionButNoGoogleServices } else { LocationServicesStatus.FullyPresent } } } } enum class LocationServicesStatus { FullyPresent, NoPermissions, HasGeopositionButNoGoogleServices, NotEnabled }
template-kotlin/mobile/src/main/java/helpers/location.kt
3300767186
package sg.studium.neurals.model import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import org.apache.commons.io.IOUtils import org.deeplearning4j.nn.multilayer.MultiLayerNetwork import org.deeplearning4j.util.ModelSerializer import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize import org.nd4j.linalg.dataset.api.preprocessor.serializer.NormalizerSerializer import org.nd4j.linalg.factory.Nd4j import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.InputStream import java.io.OutputStream import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream /** * Practically usable Dl4j [MultiLayerNetwork] with [NormalizerStandardize] and column labels. */ class Dl4jModel( private val colsX: List<String>, private val colsY: List<String>, private val normalizer: NormalizerStandardize?, private val net: MultiLayerNetwork ) : Model { private val colsXMap: Map<String, Int> by lazy { colsX.withIndex().associate { (idx, v) -> Pair(v, idx) } } override fun predict(explanatory: Map<String, Any>): Map<String, Double> { val features = DoubleArray(colsX.size, { 0.0 }) explanatory.forEach { (s, v) -> if (v is String) { // categorical, "feature[value]" case, set to 1.0 features[colsXMap["$s[$v]"]!!] = 1.0 } else if (v is Number) { // numeric case features[colsXMap[s]!!] = v.toDouble() } else { throw RuntimeException("Should be String or Number, got ${v.javaClass}") } } val output = predict(features) return output.withIndex().associate { (idx, value) -> Pair(colsY[idx], value) } } override fun predict(X: DoubleArray): DoubleArray { val features = Nd4j.create(X) normalizer?.transform(features) val output = net.output(features) assert(output.rows() == 1) assert(output.columns() == colsY.size) return DoubleArray(output.columns(), { output.getDouble(it) }) } /** * Saves the model into a zip file. * * Recommended suffix: ".dl4jmodel.zip" */ fun save(outputStream: OutputStream) { val mapper = ObjectMapper().registerModule(KotlinModule()) val zout = ZipOutputStream(outputStream) zout.putNextEntry(ZipEntry("colsX.json")) zout.write(mapper.writeValueAsBytes(colsX)) zout.closeEntry() zout.putNextEntry(ZipEntry("colsY.json")) zout.write(mapper.writeValueAsBytes(colsY)) zout.closeEntry() if (normalizer != null) { val baosNormalizer = ByteArrayOutputStream() NormalizerSerializer.getDefault().write(normalizer, baosNormalizer) zout.putNextEntry(ZipEntry("normalizer.data")) zout.write(baosNormalizer.toByteArray()) zout.closeEntry() } val modelBaos = ByteArrayOutputStream() ModelSerializer.writeModel(net, modelBaos, true) zout.putNextEntry(ZipEntry("model.dl4j.zip")) zout.write(modelBaos.toByteArray()) zout.closeEntry() zout.close() } companion object { /** * @param allColumnNames list of all column names, X and Y * @param colsY list of Y column names * @param normalizer optional normalizer that was used to train the model * @param net the trained network * @return created model */ fun build(allColumnNames: List<String>, colsY: List<String>, normalizer: NormalizerStandardize?, net: MultiLayerNetwork): Dl4jModel { val colsX = allColumnNames.filter { scIt -> !colsY.any { scIt.startsWith("$it[") || scIt == it } } return Dl4jModel(colsX, colsY, normalizer, net) } /** * @param allColumnNames array of all column names, X and Y * @param colsY array of Y column names * @param normalizer optional normalizer that was used to train the model * @param net the trained network * @return created model */ fun build(allColumnNames: Array<String>, colsY: Array<String>, normalizer: NormalizerStandardize?, net: MultiLayerNetwork): Dl4jModel { return build(allColumnNames.toList(), colsY.toList(), normalizer, net) } /** * Loads the model from a zip file. * * Recommended suffix: ".dl4jmodel.zip" */ fun load(inputStream: InputStream): Dl4jModel { val mapper = ObjectMapper().registerModule(KotlinModule()) var colsX: List<String>? = null var colsY: List<String>? = null var normalizer: NormalizerStandardize? = null var net: MultiLayerNetwork? = null val zin = ZipInputStream(inputStream) var entry = zin.nextEntry while (entry != null) { val bar = IOUtils.toByteArray(zin) @Suppress("UNCHECKED_CAST") when { entry.name == "colsX.json" -> colsX = mapper.readValue(bar, List::class.java) as List<String> entry.name == "colsY.json" -> colsY = mapper.readValue(bar, List::class.java) as List<String> entry.name == "normalizer.data" -> normalizer = NormalizerSerializer.getDefault().restore(ByteArrayInputStream(bar)) entry.name == "model.dl4j.zip" -> net = ModelSerializer.restoreMultiLayerNetwork(ByteArrayInputStream(bar), true) else -> throw RuntimeException("Unknown entry: ${entry.name}") } entry = zin.nextEntry } if (colsX == null) throw RuntimeException("Zip file does not have 'colsX.json'") if (colsY == null) throw RuntimeException("Zip file does not have 'colsY.json'") if (net == null) throw RuntimeException("Zip file does not have 'model.dl4j.zip'") return Dl4jModel( colsX, colsY, normalizer, net) } } }
src/main/java/sg/studium/neurals/model/Dl4jModel.kt
2428003862
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * Maps dropout * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["Dropout"],frameworkName = "onnx") class Dropout : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { var inputVariable = sd.getVariable(op.inputsToOp[0]) val p = if(attributes.containsKey("ratio")) { val fVal = attributes["ratio"] as Float fVal.toDouble() } else if(op.inputsToOp.size > 1) { val dropoutVar = sd.getVariable(op.inputsToOp[1]).arr.getDouble(0) dropoutVar } else { 0.5 } val outputVar = sd.nn().dropout(outputNames[0],inputVariable,true,p) return mapOf(outputVar.name() to listOf(outputVar)) } }
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Dropout.kt
1791593070
package com.xenoage.utils.document.command import com.xenoage.utils.document.Document /** * Classes implementing this interface can be notified when a [Command] has been * executed or undone on a [Document]. * * This is for example useful to keep the state of undo and redo buttons of the GUI up to date. */ interface CommandListener { /** * This method is called, when the given [Command] was performed on * the given [Document]. */ fun commandExecuted(document: Document, command: Command) /** * This method is called, when the given [Command] was undone on * the given [Document]. When multiple steps are undone at the same time, * the last undone command is given. */ fun commandUndone(document: Document, command: Command) }
utils-kotlin/src/com/xenoage/utils/document/command/CommandListener.kt
744413555
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiTreeChangeEvent import com.intellij.psi.PsiTreeChangeListener import com.intellij.psi.impl.PsiTreeChangeEventImpl import java.util.* sealed class RsPsiTreeChangeEvent { /** * Event can relate to changes in a file system, e.g. file creation/deletion/movement. * In this case the property is set to null. */ open val file: PsiFile? get() = null sealed class ChildAddition( override val file: PsiFile?, val parent: PsiElement ) : RsPsiTreeChangeEvent() { abstract val child: PsiElement? class Before( file: PsiFile?, parent: PsiElement, override val child: PsiElement? ) : ChildAddition(file, parent) class After( file: PsiFile?, parent: PsiElement, override val child: PsiElement ) : ChildAddition(file, parent) override fun toString(): String = "ChildAddition.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, child=`${child?.text}`)" } sealed class ChildRemoval( override val file: PsiFile?, val parent: PsiElement, /** Invalid in [ChildRemoval.After] */ val child: PsiElement ) : RsPsiTreeChangeEvent() { class Before(file: PsiFile?, parent: PsiElement, child: PsiElement) : ChildRemoval(file, parent, child) class After(file: PsiFile?, parent: PsiElement, child: PsiElement) : ChildRemoval(file, parent, child) override fun toString(): String = "ChildRemoval.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, child=`${child.safeText}`)" } sealed class ChildReplacement( override val file: PsiFile?, val parent: PsiElement, /** Invalid in [ChildReplacement.After] */ val oldChild: PsiElement ) : RsPsiTreeChangeEvent() { abstract val newChild: PsiElement? class Before( file: PsiFile?, parent: PsiElement, oldChild: PsiElement, override val newChild: PsiElement? ) : ChildReplacement(file, parent, oldChild) class After( file: PsiFile?, parent: PsiElement, oldChild: PsiElement, override val newChild: PsiElement ) : ChildReplacement(file, parent, oldChild) override fun toString(): String = "ChildReplacement.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, " + "oldChild=`${oldChild.safeText}`, newChild=`${newChild?.text}`)" } @Suppress("MemberVisibilityCanBePrivate") sealed class ChildMovement( override val file: PsiFile?, val oldParent: PsiElement, val newParent: PsiElement, val child: PsiElement ) : RsPsiTreeChangeEvent() { class Before(file: PsiFile?, oldParent: PsiElement, newParent: PsiElement, child: PsiElement) : ChildMovement(file, oldParent, newParent, child) class After(file: PsiFile?, oldParent: PsiElement, newParent: PsiElement, child: PsiElement) : ChildMovement(file, oldParent, newParent, child) override fun toString(): String = "ChildMovement.${javaClass.simpleName}(file=$file, oldParent=`${oldParent.text}`, " + "newParent=`${newParent.text}`, child=`${child.text}`)" } sealed class ChildrenChange( override val file: PsiFile?, val parent: PsiElement, /** * "generic change" event means that "something changed inside an element" and * sends before/after all events for concrete PSI changes in the element. */ val isGenericChange: Boolean ) : RsPsiTreeChangeEvent() { class Before(file: PsiFile?, parent: PsiElement, isGenericChange: Boolean) : ChildrenChange(file, parent, isGenericChange) class After(file: PsiFile?, parent: PsiElement, isGenericChange: Boolean) : ChildrenChange(file, parent, isGenericChange) override fun toString(): String = "ChildrenChange.${javaClass.simpleName}(file=$file, parent=`${parent.text}`, " + "isGenericChange=$isGenericChange)" } @Suppress("MemberVisibilityCanBePrivate") sealed class PropertyChange( val propertyName: String, val oldValue: Any?, val newValue: Any?, val element: PsiElement?, val child: PsiElement?, ) : RsPsiTreeChangeEvent() { class Before( propertyName: String, oldValue: Any?, newValue: Any?, element: PsiElement?, child: PsiElement? ) : PropertyChange(propertyName, oldValue, newValue, element, child) class After( propertyName: String, oldValue: Any?, newValue: Any?, element: PsiElement?, child: PsiElement? ) : PropertyChange(propertyName, oldValue, newValue, element, child) override fun toString(): String { val oldValue = if (oldValue is Array<*>) Arrays.toString(oldValue) else oldValue val newValue = if (newValue is Array<*>) Arrays.toString(newValue) else newValue return "PropertyChange.${javaClass.simpleName}(propertyName='$propertyName', " + "oldValue=$oldValue, newValue=$newValue, element=$element, child=$child)" } } } abstract class RsPsiTreeChangeAdapter : PsiTreeChangeListener { abstract fun handleEvent(event: RsPsiTreeChangeEvent) override fun beforePropertyChange(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.PropertyChange.Before( event.propertyName, event.oldValue, event.newValue, event.element, event.child ) ) } override fun propertyChanged(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.PropertyChange.After( event.propertyName, event.oldValue, event.newValue, event.element, event.child ) ) } override fun beforeChildReplacement(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildReplacement.Before( event.file, event.parent, event.oldChild, event.newChild ) ) } override fun childReplaced(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildReplacement.After( event.file, event.parent, event.oldChild, event.newChild ) ) } override fun beforeChildAddition(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildAddition.Before( event.file, event.parent, event.child ) ) } override fun childAdded(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildAddition.After( event.file, event.parent, event.child ) ) } override fun beforeChildMovement(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildMovement.Before( event.file, event.oldParent, event.newParent, event.child ) ) } override fun childMoved(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildMovement.After( event.file, event.oldParent, event.newParent, event.child ) ) } override fun beforeChildRemoval(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildRemoval.Before( event.file, event.parent, event.child ) ) } override fun childRemoved(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildRemoval.After( event.file, event.parent, event.child ) ) } override fun beforeChildrenChange(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildrenChange.Before( event.file, event.parent, (event as? PsiTreeChangeEventImpl)?.isGenericChange == true ) ) } override fun childrenChanged(event: PsiTreeChangeEvent) { handleEvent( RsPsiTreeChangeEvent.ChildrenChange.After( event.file, event.parent, (event as? PsiTreeChangeEventImpl)?.isGenericChange == true ) ) } } /** * It is not safe to call getText() on invalid PSI elements, but sometimes it works, * so we can try to use it for debug purposes */ private val PsiElement.safeText get() = try { text } catch (ignored: Exception) { "<exception>" }
src/main/kotlin/org/rust/lang/core/psi/RsPsiTreeChangeListener.kt
1810468875
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.commands import io.sentry.Sentry import moe.kyubey.akatsuki.entities.Command import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.utils.Http @Load class Birb : Command() { override val name = "birb" override val desc = "Get a random birb" override fun run(ctx: Context) { Http.get("https://random.birb.pw/tweet").thenAccept { res -> ctx.send("https://random.birb.pw/img/${res.body()!!.string()}") res.close() }.thenApply {}.exceptionally { ctx.logger.error("Error while trying to get random bird from birb.pw", it) ctx.sendError(it) Sentry.capture(it) } } }
src/main/kotlin/moe/kyubey/akatsuki/commands/Birb.kt
1663947297
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve2 import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.vfs.VirtualFileWithId import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.PsiTreeChangeEvent import com.intellij.util.containers.MultiMap import org.rust.RsTask.TaskType.* import org.rust.cargo.project.model.CargoProjectsService import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener import org.rust.lang.core.crate.Crate import org.rust.lang.core.crate.CratePersistentId import org.rust.lang.core.macros.MacroExpansionMode import org.rust.lang.core.macros.macroExpansionManager import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsPsiTreeChangeEvent.* import org.rust.openapiext.checkWriteAccessAllowed import org.rust.openapiext.pathAsPath import org.rust.stdext.mapToSet import java.lang.ref.WeakReference import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.locks.ReentrantLock /** Stores [CrateDefMap] and data needed to determine whether [defMap] is up-to-date. */ class DefMapHolder( val crateId: CratePersistentId, private val structureModificationTracker: ModificationTracker, ) { /** * Write access requires read action with [DefMapService.defMapsBuildLock] or write action. * Read access requires only read action (needed for fast path in [DefMapService.getOrUpdateIfNeeded]). */ @Volatile var defMap: CrateDefMap? = null private set /** * Value of [rustStructureModificationTracker] at the time when [defMap] started to built. * Write access requires read action with [DefMapService.defMapsBuildLock] or write action. * Read access requires only read action (needed for fast path in [DefMapService.getOrUpdateIfNeeded]). */ private val defMapStamp: AtomicLong = AtomicLong(-1) fun hasLatestStamp(): Boolean = defMapStamp.get() == structureModificationTracker.modificationCount private fun setLatestStamp() { defMapStamp.set(structureModificationTracker.modificationCount) } fun checkHasLatestStamp() { if (defMap != null && !hasLatestStamp()) { RESOLVE_LOG.error( "DefMapHolder must have latest stamp right after DefMap($defMap) was updated. " + "$defMapStamp vs ${structureModificationTracker.modificationCount}" ) } } val modificationCount: Long get() = defMapStamp.get() /** * If true then we should rebuild [defMap], regardless of [shouldRecheck] or [changedFiles] values. * Any access requires read action with [DefMapService.defMapsBuildLock] or write action. */ @Volatile var shouldRebuild: Boolean = true set(value) { field = value if (value) { defMapStamp.decrementAndGet() shouldRecheck = false changedFiles.clear() } } /** * If true then we should check for possible modification every file of the crate * (using [FileInfo.modificationStamp] or [HashCalculator]). * Any access requires read action with [DefMapService.defMapsBuildLock] or write action. */ @Volatile var shouldRecheck: Boolean = false set(value) { field = value if (value) { defMapStamp.decrementAndGet() } } /** Any access requires read action with [DefMapService.defMapsBuildLock] or write action. */ val changedFiles: MutableSet<RsFile> = hashSetOf() fun addChangedFile(file: RsFile) { changedFiles += file defMapStamp.decrementAndGet() } fun setDefMap(defMap: CrateDefMap?) { this.defMap = defMap shouldRebuild = false setLatestStamp() } fun updateShouldRebuild(crate: Crate): Boolean { val shouldRebuild = getShouldRebuild(crate) if (shouldRebuild) { this.shouldRebuild = true } else { setLatestStamp() } return shouldRebuild } override fun toString(): String = "DefMapHolder($defMap, stamp=$defMapStamp)" } @Service class DefMapService(val project: Project) : Disposable { /** Concurrent because [DefMapsBuilder] uses multiple threads. */ private val defMaps: ConcurrentMap<CratePersistentId, DefMapHolder> = ConcurrentHashMap() val defMapsBuildLock: ReentrantLock = ReentrantLock() private val fileIdToCrateId: MultiMap<FileId, CratePersistentId> = MultiMap.createConcurrent() /** Merged map of [CrateDefMap.missedFiles] for all crates */ private val missedFiles: ConcurrentHashMap<Path, CratePersistentId> = ConcurrentHashMap() /** Used as an optimization in [removeStaleDefMaps] */ private val lastCheckedTopSortedCrates: AtomicReference<WeakReference<List<Crate>>?> = AtomicReference(null) private val structureModificationTracker: ModificationTracker = project.rustPsiManager.rustStructureModificationTracker /** The last value of [structureModificationTracker] when *all* def maps has been updated */ @Volatile private var allDefMapsUpdatedStamp: Long = -1 init { setupListeners() } /** * Possible modifications: * - After IDE restart: full recheck (for each crate compare [CrateMetaData] and `modificationStamp` of each file). * Tasks [CARGO_SYNC] and [MACROS_UNPROCESSED] are executed. * - File changed: calculate hash and compare with hash stored in [CrateDefMap.fileInfos]. * Task [MACROS_FULL] is executed. * - File added: check whether [missedFiles] contains file path * - File deleted: check whether [fileIdToCrateId] contains this file * - Crate workspace changed: full recheck * Tasks [CARGO_SYNC] and [MACROS_UNPROCESSED] are executed. */ private fun setupListeners() { PsiManager.getInstance(project).addPsiTreeChangeListener(DefMapPsiTreeChangeListener(), this) val connection = project.messageBus.connect() project.rustPsiManager.subscribeRustPsiChange(connection, object : RustPsiChangeListener { override fun rustPsiChanged(file: PsiFile, element: PsiElement, isStructureModification: Boolean) { /** When macro expansion is enabled, file modification is handled in `ChangedMacroUpdater.rustPsiChanged` */ if (file is RsFile && project.macroExpansionManager.macroExpansionMode !is MacroExpansionMode.New) { onFileChanged(file) } } }) connection.subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ -> scheduleRecheckAllDefMaps() }) } fun getDefMapHolder(crate: CratePersistentId): DefMapHolder { return defMaps.computeIfAbsent(crate) { DefMapHolder(crate, structureModificationTracker) } } fun hasDefMapFor(crate: CratePersistentId): Boolean = defMaps[crate] != null fun setDefMap(crate: CratePersistentId, defMap: CrateDefMap?) { updateFilesMaps(crate, defMap) val holder = getDefMapHolder(crate) holder.setDefMap(defMap) } private fun updateFilesMaps(crate: CratePersistentId, defMap: CrateDefMap?) { fileIdToCrateId.values().removeIf { it == crate } missedFiles.values.removeIf { it == crate } if (defMap != null) { for (fileId in defMap.fileInfos.keys) { fileIdToCrateId.putValue(fileId, crate) } for (missedFile in defMap.missedFiles) { missedFiles[missedFile] = crate } } } private fun onFileAdded(file: RsFile) { checkWriteAccessAllowed() val path = file.virtualFile.pathAsPath val crate = missedFiles[path] ?: return getDefMapHolder(crate).shouldRebuild = true } private fun onFileRemoved(file: RsFile) { checkWriteAccessAllowed() for (crate in findCrates(file)) { getDefMapHolder(crate).shouldRebuild = true } } fun onFileChanged(file: RsFile) { checkWriteAccessAllowed() for (crate in findCrates(file)) { getDefMapHolder(crate).addChangedFile(file) } } /** Note: we can't use [RsFile.crate], because it can trigger resolve */ fun findCrates(file: RsFile): Collection<CratePersistentId> { /** Virtual file can be [VirtualFileWindow] if it is doctest injection */ val virtualFile = file.virtualFile as? VirtualFileWithId ?: return emptyList() return fileIdToCrateId[virtualFile.id] } fun scheduleRebuildAllDefMaps() { for (defMapHolder in defMaps.values) { defMapHolder.shouldRebuild = true } } fun scheduleRebuildDefMap(crateId: CratePersistentId) { val holder = getDefMapHolder(crateId) holder.shouldRebuild = true } private fun scheduleRecheckAllDefMaps() { checkWriteAccessAllowed() for (defMapHolder in defMaps.values) { defMapHolder.shouldRecheck = true } } /** Removes DefMaps for crates not in crate graph */ fun removeStaleDefMaps(allCrates: List<Crate>) { // Optimization: proceed only if the list of crates has been changed since a previous check. We can compare // the list by reference because the list is immutable (it refers to `CrateGraphService.topSortedCrates`) if (lastCheckedTopSortedCrates.getAndSet(WeakReference(allCrates))?.get() === allCrates) return val allCrateIds = allCrates.mapToSet { it.id } val staleCrates = hashSetOf<CratePersistentId>() defMaps.keys.removeIf { crate -> val isStale = crate !in allCrateIds if (isStale) staleCrates += crate isStale } fileIdToCrateId.values().removeIf { it in staleCrates } missedFiles.values.removeIf { it in staleCrates } } fun setAllDefMapsUpToDate() { allDefMapsUpdatedStamp = structureModificationTracker.modificationCount } fun areAllDefMapsUpToDate(): Boolean = allDefMapsUpdatedStamp == structureModificationTracker.modificationCount override fun dispose() {} private inner class DefMapPsiTreeChangeListener : RsPsiTreeChangeAdapter() { override fun handleEvent(event: RsPsiTreeChangeEvent) { // events for file addition/deletion have null `event.file` and not-null `event.child` if (event.file != null) return when (event) { is ChildAddition.After -> { val file = event.child as? RsFile ?: return onFileAdded(file) } is ChildRemoval.Before -> { val file = event.child as? RsFile ?: return onFileRemoved(file) } is PropertyChange.Before -> { // before rename if (event.propertyName == PsiTreeChangeEvent.PROP_FILE_NAME) { val file = event.child as? RsFile ?: return onFileRemoved(file) } } is PropertyChange.After -> { // after rename if (event.propertyName == PsiTreeChangeEvent.PROP_FILE_NAME) { val file = event.element as? RsFile ?: return onFileAdded(file) return } } else -> Unit } } } companion object { private val nextNonCargoCrateId: AtomicInteger = AtomicInteger(-1) fun getNextNonCargoCrateId(): Int = nextNonCargoCrateId.decrementAndGet() } } val Project.defMapService: DefMapService get() = service()
src/main/kotlin/org/rust/lang/core/resolve2/DefMapService.kt
1263637175
package com.vimeo.dummy.sample_kotlin import org.junit.Test /** * Unit tests for [BoolFields]. * * Created by anthonycr on 9/2/17. */ class BoolFieldsTest { @Test fun verifyTypeAdapterWasGenerated() { Utils.verifyTypeAdapterGeneration(BoolFields::class) } @Test fun verifyTypeAdapterCorrect() { Utils.verifyTypeAdapterCorrectness(BoolFields::class) } }
integration-test-kotlin/src/test/kotlin/com/vimeo/dummy/sample_kotlin/BoolFieldsTest.kt
3950280167
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.feature.tag import com.mvcoding.expensius.data.DataSource import com.mvcoding.expensius.data.DataWriter import com.mvcoding.expensius.model.AppUser import com.mvcoding.expensius.model.Tag import com.mvcoding.expensius.model.UserId class TagsWriter( private val appUserSource: DataSource<AppUser>, private val updateTags: (UserId, Set<Tag>) -> Unit) : DataWriter<Set<Tag>> { override fun write(data: Set<Tag>) { appUserSource.data().first().map { it.userId }.subscribe { updateTags(it, data) } } }
app-core/src/main/kotlin/com/mvcoding/expensius/feature/tag/TagsWriter.kt
1180847712
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.workprofile import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.workprofile", appContext.packageName) } }
Work-profile-codelab/app-starter/src/androidTest/java/com/example/workprofile/ExampleInstrumentedTest.kt
2587984763
/* * 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.lifecycle.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.produceState import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.repeatOnLifecycle import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext /** * Collects values from this [StateFlow] and represents its latest value via [State] in a * lifecycle-aware manner. * * The [StateFlow.value] is used as an initial value. Every time there would be new value posted * into the [StateFlow] the returned [State] will be updated causing recomposition of every * [State.value] usage whenever the [lifecycleOwner]'s lifecycle is at least [minActiveState]. * * This [StateFlow] is collected every time the [lifecycleOwner]'s lifecycle reaches the * [minActiveState] Lifecycle state. The collection stops when the [lifecycleOwner]'s lifecycle * falls below [minActiveState]. * * @sample androidx.lifecycle.compose.samples.StateFlowCollectAsStateWithLifecycle * * Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a * parameter will throw an [IllegalArgumentException]. * * @param lifecycleOwner [LifecycleOwner] whose `lifecycle` is used to restart collecting `this` * flow. * @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The * collection will stop if the lifecycle falls below that state, and will restart if it's in that * state again. * @param context [CoroutineContext] to use for collecting. */ @ExperimentalLifecycleComposeApi @Composable fun <T> StateFlow<T>.collectAsStateWithLifecycle( lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, minActiveState: Lifecycle.State = Lifecycle.State.STARTED, context: CoroutineContext = EmptyCoroutineContext ): State<T> = collectAsStateWithLifecycle( initialValue = this.value, lifecycle = lifecycleOwner.lifecycle, minActiveState = minActiveState, context = context ) /** * Collects values from this [StateFlow] and represents its latest value via [State] in a * lifecycle-aware manner. * * The [StateFlow.value] is used as an initial value. Every time there would be new value posted * into the [StateFlow] the returned [State] will be updated causing recomposition of every * [State.value] usage whenever the [lifecycle] is at least [minActiveState]. * * This [StateFlow] is collected every time [lifecycle] reaches the [minActiveState] Lifecycle * state. The collection stops when [lifecycle] falls below [minActiveState]. * * @sample androidx.lifecycle.compose.samples.StateFlowCollectAsStateWithLifecycle * * Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a * parameter will throw an [IllegalArgumentException]. * * @param lifecycle [Lifecycle] used to restart collecting `this` flow. * @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The * collection will stop if the lifecycle falls below that state, and will restart if it's in that * state again. * @param context [CoroutineContext] to use for collecting. */ @ExperimentalLifecycleComposeApi @Composable fun <T> StateFlow<T>.collectAsStateWithLifecycle( lifecycle: Lifecycle, minActiveState: Lifecycle.State = Lifecycle.State.STARTED, context: CoroutineContext = EmptyCoroutineContext ): State<T> = collectAsStateWithLifecycle( initialValue = this.value, lifecycle = lifecycle, minActiveState = minActiveState, context = context ) /** * Collects values from this [Flow] and represents its latest value via [State] in a * lifecycle-aware manner. * * Every time there would be new value posted into the [Flow] the returned [State] will be updated * causing recomposition of every [State.value] usage whenever the [lifecycleOwner]'s lifecycle is * at least [minActiveState]. * * This [Flow] is collected every time the [lifecycleOwner]'s lifecycle reaches the [minActiveState] * Lifecycle state. The collection stops when the [lifecycleOwner]'s lifecycle falls below * [minActiveState]. * * @sample androidx.lifecycle.compose.samples.FlowCollectAsStateWithLifecycle * * Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a * parameter will throw an [IllegalArgumentException]. * * @param initialValue The initial value given to the returned [State.value]. * @param lifecycleOwner [LifecycleOwner] whose `lifecycle` is used to restart collecting `this` * flow. * @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The * collection will stop if the lifecycle falls below that state, and will restart if it's in that * state again. * @param context [CoroutineContext] to use for collecting. */ @ExperimentalLifecycleComposeApi @Composable fun <T> Flow<T>.collectAsStateWithLifecycle( initialValue: T, lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, minActiveState: Lifecycle.State = Lifecycle.State.STARTED, context: CoroutineContext = EmptyCoroutineContext ): State<T> = collectAsStateWithLifecycle( initialValue = initialValue, lifecycle = lifecycleOwner.lifecycle, minActiveState = minActiveState, context = context ) /** * Collects values from this [Flow] and represents its latest value via [State] in a * lifecycle-aware manner. * * Every time there would be new value posted into the [Flow] the returned [State] will be updated * causing recomposition of every [State.value] usage whenever the [lifecycle] is at * least [minActiveState]. * * This [Flow] is collected every time [lifecycle] reaches the [minActiveState] Lifecycle * state. The collection stops when [lifecycle] falls below [minActiveState]. * * @sample androidx.lifecycle.compose.samples.FlowCollectAsStateWithLifecycle * * Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a * parameter will throw an [IllegalArgumentException]. * * @param initialValue The initial value given to the returned [State.value]. * @param lifecycle [Lifecycle] used to restart collecting `this` flow. * @param minActiveState [Lifecycle.State] in which the upstream flow gets collected. The * collection will stop if the lifecycle falls below that state, and will restart if it's in that * state again. * @param context [CoroutineContext] to use for collecting. */ @ExperimentalLifecycleComposeApi @Composable fun <T> Flow<T>.collectAsStateWithLifecycle( initialValue: T, lifecycle: Lifecycle, minActiveState: Lifecycle.State = Lifecycle.State.STARTED, context: CoroutineContext = EmptyCoroutineContext ): State<T> { return produceState(initialValue, this, lifecycle, minActiveState, context) { lifecycle.repeatOnLifecycle(minActiveState) { if (context == EmptyCoroutineContext) { [email protected] { [email protected] = it } } else withContext(context) { [email protected] { [email protected] = it } } } } }
lifecycle/lifecycle-runtime-compose/src/main/java/androidx/lifecycle/compose/FlowExt.kt
1030566431
package com.devbrackets.android.exomedia.nmp.manager.track import android.content.Context import android.util.ArrayMap import androidx.media3.common.C import androidx.media3.common.TrackGroup import com.devbrackets.android.exomedia.core.renderer.RendererType import androidx.media3.exoplayer.source.TrackGroupArray import androidx.media3.exoplayer.trackselection.AdaptiveTrackSelection import androidx.media3.exoplayer.trackselection.DefaultTrackSelector import androidx.media3.exoplayer.trackselection.MappingTrackSelector import java.util.ArrayList /** * Handles managing the tracks for the [CorePlayer] */ class TrackManager(context: Context) { private val selectionFactory: AdaptiveTrackSelection.Factory = AdaptiveTrackSelection.Factory() val selector: DefaultTrackSelector = DefaultTrackSelector(context, selectionFactory) /** * Retrieves a list of available tracks * * @return A list of available tracks associated with each type */ @Suppress("FoldInitializerAndIfToElvis") fun getAvailableTracks(): Map<RendererType, TrackGroupArray>? { val mappedTrackInfo = selector.currentMappedTrackInfo if (mappedTrackInfo == null) { return null } val trackMap = ArrayMap<RendererType, TrackGroupArray>() RendererType.values().forEach { type -> val trackGroups = ArrayList<TrackGroup>() for (exoPlayerTrackIndex in getExoPlayerTracksInfo(type, 0, mappedTrackInfo).indexes) { val trackGroupArray = mappedTrackInfo.getTrackGroups(exoPlayerTrackIndex) for (i in 0 until trackGroupArray.length) { trackGroups.add(trackGroupArray.get(i)) } } if (trackGroups.isNotEmpty()) { trackMap[type] = TrackGroupArray(*trackGroups.toTypedArray()) } } return trackMap } fun getExoPlayerTracksInfo(type: RendererType, groupIndex: Int, mappedTrackInfo: MappingTrackSelector.MappedTrackInfo?): RendererTrackInfo { if (mappedTrackInfo == null) { return RendererTrackInfo(emptyList(), C.INDEX_UNSET, C.INDEX_UNSET) } // holder for the all exo player renderer track indexes of the specified renderer type val rendererTrackIndexes = ArrayList<Int>() var rendererTrackIndex = C.INDEX_UNSET // the corrected exoplayer group index var rendererTrackGroupIndex = C.INDEX_UNSET var skippedRenderersGroupsCount = 0 for (rendererIndex in 0 until mappedTrackInfo.rendererCount) { if (type.exoPlayerTrackType != mappedTrackInfo.getRendererType(rendererIndex)) { continue } rendererTrackIndexes.add(rendererIndex) val trackGroups = mappedTrackInfo.getTrackGroups(rendererIndex) if (skippedRenderersGroupsCount + trackGroups.length <= groupIndex) { skippedRenderersGroupsCount += trackGroups.length continue } // if the groupIndex belongs to the current exo player renderer if (rendererTrackIndex == C.INDEX_UNSET) { rendererTrackIndex = rendererIndex rendererTrackGroupIndex = groupIndex - skippedRenderersGroupsCount } } return RendererTrackInfo(rendererTrackIndexes, rendererTrackIndex, rendererTrackGroupIndex) } @JvmOverloads fun getSelectedTrackIndex(type: RendererType, groupIndex: Int = 0): Int { // Retrieves the available tracks val mappedTrackInfo = selector.currentMappedTrackInfo val tracksInfo = getExoPlayerTracksInfo(type, groupIndex, mappedTrackInfo) if (tracksInfo.index == C.INDEX_UNSET) { return -1 } val trackGroupArray = mappedTrackInfo!!.getTrackGroups(tracksInfo.index) if (trackGroupArray.length == 0) { return -1 } // Verifies the track selection has been overridden val selectionOverride = selector.parameters.getSelectionOverride(tracksInfo.index, trackGroupArray) if (selectionOverride == null || selectionOverride.groupIndex != tracksInfo.groupIndex || selectionOverride.length <= 0) { return -1 } // In the current implementation only one track can be selected at a time so get the first one. return selectionOverride.tracks[0] } fun setSelectedTrack(type: RendererType, groupIndex: Int, trackIndex: Int) { // Retrieves the available tracks val mappedTrackInfo = selector.currentMappedTrackInfo val tracksInfo = getExoPlayerTracksInfo(type, groupIndex, mappedTrackInfo) if (tracksInfo.index == C.INDEX_UNSET || mappedTrackInfo == null) { return } val trackGroupArray = mappedTrackInfo.getTrackGroups(tracksInfo.index) if (trackGroupArray.length == 0 || trackGroupArray.length <= tracksInfo.groupIndex) { return } // Finds the requested group val group = trackGroupArray.get(tracksInfo.groupIndex) if (group.length <= trackIndex) { return } val parametersBuilder = selector.buildUponParameters() for (rendererTrackIndex in tracksInfo.indexes) { parametersBuilder.clearSelectionOverrides(rendererTrackIndex) // Disable renderers of the same type to prevent playback errors if (tracksInfo.index != rendererTrackIndex) { parametersBuilder.setRendererDisabled(rendererTrackIndex, true) continue } // Specifies the correct track to use parametersBuilder.setSelectionOverride(rendererTrackIndex, trackGroupArray, DefaultTrackSelector.SelectionOverride(tracksInfo.groupIndex, trackIndex)) // make sure renderer is enabled parametersBuilder.setRendererDisabled(rendererTrackIndex, false) } selector.setParameters(parametersBuilder) } /** * Clear all selected tracks for the specified renderer and re-enable all renderers so the player can select the default track. * * @param type The renderer type */ fun clearSelectedTracks(type: RendererType) { // Retrieves the available tracks val mappedTrackInfo = selector.currentMappedTrackInfo val tracksInfo = getExoPlayerTracksInfo(type, 0, mappedTrackInfo) val parametersBuilder = selector.buildUponParameters() for (rendererTrackIndex in tracksInfo.indexes) { // Reset all renderers re-enabling so the player can select the streams default track. parametersBuilder.setRendererDisabled(rendererTrackIndex, false) .clearSelectionOverrides(rendererTrackIndex) } selector.setParameters(parametersBuilder) } fun setRendererEnabled(type: RendererType, enabled: Boolean) { val mappedTrackInfo = selector.currentMappedTrackInfo val tracksInfo = getExoPlayerTracksInfo(type, 0, mappedTrackInfo) if (tracksInfo.indexes.isEmpty()) { return } var enabledSomething = false val parametersBuilder = selector.buildUponParameters() for (rendererTrackIndex in tracksInfo.indexes) { if (!enabled) { parametersBuilder.setRendererDisabled(rendererTrackIndex, true) continue } val selectionOverride = selector.parameters.getSelectionOverride(rendererTrackIndex, mappedTrackInfo!!.getTrackGroups(rendererTrackIndex)) // check whether the renderer has been selected before // other renderers should be kept disabled to avoid playback errors if (selectionOverride != null) { parametersBuilder.setRendererDisabled(rendererTrackIndex, false) enabledSomething = true } } if (enabled && !enabledSomething) { // if nothing has been enabled enable the first sequential renderer parametersBuilder.setRendererDisabled(tracksInfo.indexes[0], false) } selector.setParameters(parametersBuilder) } /** * Return true if at least one renderer for the given type is enabled * @param type The renderer type * @return true if at least one renderer for the given type is enabled */ fun isRendererEnabled(type: RendererType): Boolean { val mappedTrackInfo = selector.currentMappedTrackInfo val tracksInfo = getExoPlayerTracksInfo(type, 0, mappedTrackInfo) val parameters = selector.parameters return tracksInfo.indexes.any { !parameters.getRendererDisabled(it) } } }
library/src/main/kotlin/com/devbrackets/android/exomedia/nmp/manager/track/TrackManager.kt
4296185
/******************************************************************************* * 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.kotlin.ui.editors.navigation import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.eclipse.core.resources.IFile import org.eclipse.core.resources.IProject import org.eclipse.core.resources.ResourcesPlugin import org.eclipse.core.runtime.IPath import org.eclipse.core.runtime.Path import org.eclipse.jdt.core.IClassFile import org.eclipse.jdt.core.IJavaProject import org.eclipse.jdt.core.IPackageFragment import org.eclipse.jdt.core.dom.IBinding import org.eclipse.jdt.core.dom.IMethodBinding import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader import org.eclipse.jdt.internal.core.SourceMapper import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility import org.eclipse.jdt.ui.JavaUI import org.eclipse.jface.util.OpenStrategy import org.eclipse.ui.IEditorPart import org.eclipse.ui.IReusableEditor import org.eclipse.ui.IStorageEditorInput import org.eclipse.ui.PlatformUI import org.eclipse.ui.ide.IDE import org.eclipse.ui.texteditor.AbstractTextEditor import org.jetbrains.kotlin.core.KotlinClasspathContainer import org.jetbrains.kotlin.core.log.KotlinLogger import org.jetbrains.kotlin.core.model.KotlinNature import org.jetbrains.kotlin.core.resolve.EclipseDescriptorUtils import org.jetbrains.kotlin.core.resolve.KotlinSourceIndex import org.jetbrains.kotlin.core.resolve.lang.java.resolver.EclipseJavaSourceElement import org.jetbrains.kotlin.core.resolve.lang.java.structure.EclipseJavaElement import org.jetbrains.kotlin.core.utils.ProjectUtils import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.SourceElement import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil import org.jetbrains.kotlin.eclipse.ui.utils.LineEndUtil import org.jetbrains.kotlin.eclipse.ui.utils.getTextDocumentOffset import org.jetbrains.kotlin.load.java.sources.JavaSourceElement import org.jetbrains.kotlin.load.java.structure.JavaElement import org.jetbrains.kotlin.load.java.structure.impl.JavaElementImpl import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryPackageSourceElement import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClass import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor import org.jetbrains.kotlin.ui.editors.KotlinEditor import org.jetbrains.kotlin.ui.editors.KotlinExternalReadOnlyEditor import org.jetbrains.kotlin.ui.editors.KotlinScriptEditor import org.jetbrains.kotlin.ui.editors.getScriptDependencies import org.jetbrains.kotlin.ui.formatter.createKtFile import org.jetbrains.kotlin.ui.navigation.KotlinOpenEditor private val KOTLIN_SOURCE_PATH = Path(ProjectUtils.buildLibPath(KotlinClasspathContainer.LIB_RUNTIME_SRC_NAME)) private val RUNTIME_SOURCE_MAPPER = KOTLIN_SOURCE_PATH.createSourceMapperWithRoot() fun gotoElement(descriptor: DeclarationDescriptor, fromElement: KtElement, fromEditor: KotlinEditor, javaProject: IJavaProject) { val elementWithSource = getElementWithSource(descriptor, javaProject.project) if (elementWithSource != null) gotoElement(elementWithSource, descriptor, fromElement, fromEditor, javaProject) } fun getElementWithSource(descriptor: DeclarationDescriptor, project: IProject): SourceElement? { val sourceElements = EclipseDescriptorUtils.descriptorToDeclarations(descriptor, project) return sourceElements.find { element -> element != SourceElement.NO_SOURCE } } fun gotoElement( element: SourceElement, descriptor: DeclarationDescriptor, fromElement: KtElement, fromEditor: KotlinEditor, project: IJavaProject) { when (element) { is EclipseJavaSourceElement -> { val binding = (element.javaElement as EclipseJavaElement<*>).binding gotoJavaDeclaration(binding) } is KotlinSourceElement -> gotoKotlinDeclaration(element.psi, fromElement, fromEditor, project) is KotlinJvmBinarySourceElement -> gotoElementInBinaryClass(element.binaryClass, descriptor, fromElement, project) is KotlinJvmBinaryPackageSourceElement -> gotoClassByPackageSourceElement(element, fromElement, descriptor, project) is PsiSourceElement -> { if (element is JavaSourceElement) { gotoJavaDeclarationFromNonClassPath(element.javaElement, element.psi, fromEditor, project) } } } } private fun gotoJavaDeclarationFromNonClassPath( javaElement: JavaElement, psi: PsiElement?, fromEditor: KotlinEditor, javaProject: IJavaProject) { if (!fromEditor.isScript) return val javaPsi = (javaElement as JavaElementImpl<*>).psi val editorPart = tryToFindSourceInJavaProject(javaPsi, javaProject) if (editorPart != null) { revealJavaElementInEditor(editorPart, javaElement, EditorUtil.getSourceCode(editorPart)) return } val virtualFile = psi?.containingFile?.virtualFile ?: return val (sourceName, packagePath) = findSourceFilePath(virtualFile) val dependencies = getScriptDependencies(fromEditor as KotlinScriptEditor) ?: return val pathToSource = packagePath.append(sourceName) val source = dependencies.sources.asSequence() .map { Path(it.absolutePath).createSourceMapperWithRoot() } .mapNotNull { it.findSource(pathToSource.toOSString()) } .firstOrNull() ?: return val sourceString = String(source) val targetEditor = openJavaEditorForExternalFile(sourceString, sourceName, packagePath.toOSString()) ?: return revealJavaElementInEditor(targetEditor, javaElement, sourceString) return } private fun revealJavaElementInEditor(editor: IEditorPart, javaElement: JavaElement, source: String) { val offset = findDeclarationInJavaFile(javaElement, source) if (offset != null && editor is AbstractTextEditor) { editor.selectAndReveal(offset, 0) } } private fun getClassFile(binaryClass: VirtualFileKotlinClass, javaProject: IJavaProject): IClassFile? { val file = binaryClass.file val fragment = javaProject.findPackageFragment(pathFromUrlInArchive(file.parent.path)) return fragment?.getClassFile(file.name) } private fun findImplementingClassInClasspath( binaryClass: VirtualFileKotlinClass, descriptor: DeclarationDescriptor, javaProject: IJavaProject): IClassFile? { return if (KotlinClassHeader.Kind.MULTIFILE_CLASS == binaryClass.classHeader.kind) getImplementingFacadePart(binaryClass, descriptor, javaProject) else getClassFile(binaryClass, javaProject) } private fun getImplementingFacadePart( binaryClass: VirtualFileKotlinClass, descriptor: DeclarationDescriptor, javaProject: IJavaProject): IClassFile? { if (descriptor !is DeserializedCallableMemberDescriptor) return null val className = getImplClassName(descriptor) if (className == null) { KotlinLogger.logWarning("Class file with implementation of $descriptor is null") return null } val classFile = getClassFile(binaryClass, javaProject) if (classFile == null) { KotlinLogger.logWarning("Class file for $binaryClass is null") return null } val fragment = classFile.getParent() as IPackageFragment val file = fragment.getClassFile(className.asString() + ".class") return if (file.exists()) file else null } //implemented via Reflection because Eclipse has issues with ProGuard-shrunken compiler //in com.google.protobuf.GeneratedMessageLite.ExtendableMessage private fun getImplClassName(memberDescriptor: DeserializedCallableMemberDescriptor): Name? { val nameIndex: Int try { val getProtoMethod = DeserializedCallableMemberDescriptor::class.java.getMethod("getProto") val proto = getProtoMethod!!.invoke(memberDescriptor) val implClassNameField = Class.forName("org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf").getField("implClassName") val implClassName = implClassNameField!!.get(null) val protobufCallable = Class.forName("org.jetbrains.kotlin.serialization.ProtoBuf\$Callable") val getExtensionMethod = protobufCallable!!.getMethod("getExtension", implClassName!!.javaClass) val indexObj = getExtensionMethod!!.invoke(proto, implClassName) if (indexObj !is Int) return null nameIndex = indexObj.toInt() } catch (e: ReflectiveOperationException) { KotlinLogger.logAndThrow(e) return null } catch (e: IllegalArgumentException) { KotlinLogger.logAndThrow(e) return null } catch (e: SecurityException) { KotlinLogger.logAndThrow(e) return null } return memberDescriptor.nameResolver.getName(nameIndex) } private fun gotoClassByPackageSourceElement( sourceElement: KotlinJvmBinaryPackageSourceElement, fromElement: KtElement, descriptor: DeclarationDescriptor, javaProject: IJavaProject) { if (descriptor !is DeserializedCallableMemberDescriptor) return val binaryClass = sourceElement.getContainingBinaryClass(descriptor) if (binaryClass == null) { KotlinLogger.logWarning("Containing binary class for $sourceElement is null") return } gotoElementInBinaryClass(binaryClass, descriptor, fromElement, javaProject) } private fun gotoElementInBinaryClass( binaryClass: KotlinJvmBinaryClass, descriptor: DeclarationDescriptor, fromElement: KtElement, javaProject: IJavaProject) { if (binaryClass !is VirtualFileKotlinClass) return val classFile = findImplementingClassInClasspath(binaryClass, descriptor, javaProject) val targetEditor = if (classFile != null) { KotlinOpenEditor.openKotlinClassFileEditor(classFile, OpenStrategy.activateOnOpen()) } else { tryToFindExternalClassInStdlib(binaryClass, fromElement, javaProject) } if (targetEditor !is KotlinEditor) return val targetKtFile = targetEditor.parsedFile ?: return val offset = findDeclarationInParsedFile(descriptor, targetKtFile) val start = LineEndUtil.convertLfToDocumentOffset(targetKtFile.getText(), offset, targetEditor.document) targetEditor.javaEditor.selectAndReveal(start, 0) } private fun gotoKotlinDeclaration(element: PsiElement, fromElement: KtElement, fromEditor: KotlinEditor, javaProject: IJavaProject) { val targetEditor = findEditorForReferencedElement(element, fromElement, fromEditor, javaProject) if (targetEditor !is KotlinEditor) return val start = element.getTextDocumentOffset(targetEditor.document) targetEditor.selectAndReveal(start, 0) } private fun tryToFindExternalClassInStdlib( binaryClass: VirtualFileKotlinClass, fromElement: KtElement, javaProject: IJavaProject): IEditorPart? { if (KotlinNature.hasKotlinNature(javaProject.project)) { // If project has Kotlin nature, then search in stdlib should be done earlier by searching class in the classpath return null } val (name, pckg, source) = findSourceForElementInStdlib(binaryClass) ?: return null val content = String(source) val ktFile = createKtFile(content, KtPsiFactory(fromElement), "dummy.kt") return openKotlinEditorForExternalFile(content, name, pckg, ktFile) } private fun findSourceForElementInStdlib(binaryClass: VirtualFileKotlinClass): ExternalSourceFile? { val (sourceName, packagePath) = findSourceFilePath(binaryClass.file) val source = KotlinSourceIndex.getSource(RUNTIME_SOURCE_MAPPER, sourceName, packagePath, KOTLIN_SOURCE_PATH) return if (source != null) ExternalSourceFile(sourceName, packagePath.toPortableString(), source) else null } private data class ExternalSourceFile(val name: String, val packageFqName: String, val source: CharArray) private fun findEditorForReferencedElement( element: PsiElement, fromElement: KtElement, fromEditor: KotlinEditor, javaProject: IJavaProject): AbstractTextEditor? { // if element is in the same file if (fromElement.getContainingFile() == element.getContainingFile()) { return fromEditor.javaEditor } val virtualFile = element.getContainingFile().getVirtualFile() if (virtualFile == null) return null val filePath = virtualFile.path val targetFile = ResourcesPlugin.getWorkspace().root.getFileForLocation(Path(filePath)) ?: getAcrhivedFileFromPath(filePath) return findEditorPart(targetFile, element, javaProject) as? AbstractTextEditor } private fun gotoJavaDeclaration(binding: IBinding) { val javaElement = if (binding is IMethodBinding && binding.isConstructor()) binding.getDeclaringClass().getJavaElement() // because <init>() may correspond to null java element else binding.javaElement if (javaElement != null) { val editorPart = EditorUtility.openInEditor(javaElement, OpenStrategy.activateOnOpen()) JavaUI.revealInEditor(editorPart, javaElement) } } private fun findSourceFilePath(virtualFile: VirtualFile): Pair<String, IPath> { val reader = ClassFileReader(virtualFile.contentsToByteArray(), virtualFile.name.toCharArray()) val sourceName = String(reader.sourceFileName()) val fileNameWithPackage = Path(String(reader.getName())) val packagePath = fileNameWithPackage.removeLastSegments(1) return Pair(sourceName, packagePath) } private fun findEditorPart( targetFile: IFile, element: PsiElement, javaProject: IJavaProject): IEditorPart? { if (targetFile.exists()) return openInEditor(targetFile) val editor = tryToFindSourceInJavaProject(element, javaProject) if (editor != null) { return editor } //external jar if (targetFile.getFullPath().toOSString().contains("jar")) { val elementFile = element.getContainingFile() if (elementFile == null) return null val directory = elementFile.getContainingDirectory() return openKotlinEditorForExternalFile( elementFile.text, elementFile.name, getFqNameInsideArchive(directory.toString()), elementFile as KtFile) } return null } private fun tryToFindSourceInJavaProject(element: PsiElement, javaProject: IJavaProject): AbstractTextEditor? { val psiClass = PsiTreeUtil.getParentOfType(element, PsiClass::class.java, false) ?: return null val targetType = javaProject.findType(psiClass.getQualifiedName()) ?: return null return EditorUtility.openInEditor(targetType, true) as? AbstractTextEditor? } private fun openKotlinEditorForExternalFile( sourceText: String, sourceName: String, packageFqName: String, ktFile: KtFile): IEditorPart? { val storage = StringStorage(sourceText, sourceName, packageFqName) val input = KotlinExternalEditorInput(ktFile, storage) return openEditorForExternalFile(input, KotlinExternalReadOnlyEditor.EDITOR_ID) } private fun openJavaEditorForExternalFile( sourceText: String, sourceName: String, packageFqName: String): IEditorPart? { val storage = StringStorage(sourceText, sourceName, packageFqName) val input = StringInput(storage) return openEditorForExternalFile(input, JavaUI.ID_CU_EDITOR) } private fun openEditorForExternalFile(storageInput: IStorageEditorInput, editorId: String): IEditorPart? { val page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() if (page == null) return null val reusedEditor = page.findEditor(storageInput) if (reusedEditor != null) { page.reuseEditor(reusedEditor as IReusableEditor?, storageInput) } return page.openEditor(storageInput, editorId) } private fun openInEditor(file: IFile): IEditorPart { val page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() return IDE.openEditor(page, file, false) } private fun IPath.createSourceMapperWithRoot(): SourceMapper = SourceMapper(this, "", emptyMap<Any, Any>())
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/navigation/navigationUtils.kt
2371395872
package com.ppes.aurinkoapp.data.db /** * Created by ppes on 03/09/2017. */ object CityForecastTable { val NAME = "CityForecast" val ID = "_id" val CITY = "city" val COUNTRY = "country" } object DayForecastTable { val NAME = "DayForecast" val ID = "_id" val DATE = "date" val DESCRIPTION = "description" val HIGH = "high" val LOW = "low" val ICON_URL = "iconUrl" val CITY_ID = "cityId" }
app/src/main/java/com/ppes/aurinkoapp/data/db/Tables.kt
3367167453
package com.wealthfront.magellan.sample import android.content.Context import com.wealthfront.magellan.core.Journey import com.wealthfront.magellan.sample.App.Provider.appComponent import com.wealthfront.magellan.sample.databinding.SecondJourneyBinding import javax.inject.Inject class SecondJourney : Journey<SecondJourneyBinding>(SecondJourneyBinding::inflate, SecondJourneyBinding::container) { @Inject lateinit var toaster: Toaster override fun onCreate(context: Context) { appComponent.inject(this) navigator.goTo(DetailStep(::startSecondJourney)) } private fun startSecondJourney() { navigator.goTo(LearnMoreStep()) } }
magellan-sample/src/main/java/com/wealthfront/magellan/sample/SecondJourney.kt
4251003597
package net.torvald.terrarum.modulecomputers.virtualcomputer.tvd.finder import java.awt.BorderLayout import java.awt.GridLayout import javax.swing.* /** * Created by SKYHi14 on 2017-04-01. */ object Popups { val okCancel = arrayOf("OK", "Cancel") } class OptionDiskNameAndCap { val name = JTextField(11) val capacity = JSpinner(SpinnerNumberModel( 368640L.toJavaLong(), 0L.toJavaLong(), (1L shl 38).toJavaLong(), 1L.toJavaLong() )) // default 360 KiB, MAX 256 GiB val mainPanel = JPanel() val settingPanel = JPanel() init { mainPanel.layout = BorderLayout() settingPanel.layout = GridLayout(2, 2, 2, 0) //name.text = "Unnamed" settingPanel.add(JLabel("Name (max 32 bytes)")) settingPanel.add(name) settingPanel.add(JLabel("Capacity (bytes)")) settingPanel.add(capacity) mainPanel.add(settingPanel, BorderLayout.CENTER) mainPanel.add(JLabel("Set capacity to 0 to make the disk read-only"), BorderLayout.SOUTH) } /** * returns either JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION */ fun showDialog(title: String): Int { return JOptionPane.showConfirmDialog(null, mainPanel, title, JOptionPane.OK_CANCEL_OPTION) } } fun kotlin.Long.toJavaLong() = java.lang.Long(this) class OptionFileNameAndCap { val name = JTextField(11) val capacity = JSpinner(SpinnerNumberModel( 4096L.toJavaLong(), 0L.toJavaLong(), ((1L shl 48) - 1L).toJavaLong(), 1L.toJavaLong() )) // default 360 KiB, MAX 256 TiB val mainPanel = JPanel() val settingPanel = JPanel() init { mainPanel.layout = BorderLayout() settingPanel.layout = GridLayout(2, 2, 2, 0) //name.text = "Unnamed" settingPanel.add(JLabel("Name (max 32 bytes)")) settingPanel.add(name) settingPanel.add(JLabel("Capacity (bytes)")) settingPanel.add(capacity) mainPanel.add(settingPanel, BorderLayout.CENTER) } /** * returns either JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION */ fun showDialog(title: String): Int { return JOptionPane.showConfirmDialog(null, mainPanel, title, JOptionPane.OK_CANCEL_OPTION) } } class OptionSize { val capacity = JSpinner(SpinnerNumberModel( 368640L.toJavaLong(), 0L.toJavaLong(), (1L shl 38).toJavaLong(), 1L.toJavaLong() )) // default 360 KiB, MAX 256 GiB val settingPanel = JPanel() init { settingPanel.add(JLabel("Size (bytes)")) settingPanel.add(capacity) } /** * returns either JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION */ fun showDialog(title: String): Int { return JOptionPane.showConfirmDialog(null, settingPanel, title, JOptionPane.OK_CANCEL_OPTION) } }
src/net/torvald/terrarum/modulecomputers/virtualcomputer/tvd/finder/Popups.kt
1939141803
package org.jonnyzzz.kotlin.xml.bind.jdom.impl internal tailrec fun <T : Annotation, R> Class<R>.getAnnotationRec(ax: Class<T>): T? { val root = this.getAnnotation(ax) if (root != null) return root val sup = this.superclass ?: return null return sup.getAnnotationRec(ax) }
jdom/src/main/kotlin/org/jonnyzzz/kotlin/xml/bind/jdom/impl/Utils.kt
2360824078
import com.android.build.api.dsl.CommonExtension import com.android.build.gradle.BaseExtension import com.android.build.gradle.LibraryExtension import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.plugins.ExtensionAware import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.findByType import org.jetbrains.kotlin.gradle.dsl.KotlinJvmOptions fun Project.configureAndroidLibrary() { extensions.configure<LibraryExtension> { baseConfiguration(project) } } fun Project.configureAndroidTestingLibrary() { extensions.configure<LibraryExtension> { baseConfiguration(project) } overridePublishingGroupForTestFixtureProject() } // TODO: provide Project using the new multiple context receivers functionality. // this is prototyped in 1.6.20 and will probably reach beta in Kotlin 1.8 or 1.9 //context(Project) fun LibraryExtension.baseConfiguration(project: Project) { configureSdk() configureProguardRules(project) configureCompilerOptions() configureTestOptions() project.configureKotlinKover() project.configurePublishing() } private fun BaseExtension.configureSdk() { compileSdkVersion(33) defaultConfig { minSdk = 21 targetSdk = 33 } } private fun BaseExtension.configureProguardRules(project: Project) { defaultConfig.consumerProguardFiles(project.rootProject.file("proguard-consumer-jetbrains.pro")) } private fun BaseExtension.configureCompilerOptions() { compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } (this as ExtensionAware).extensions.findByType<KotlinJvmOptions>()?.apply { jvmTarget = JavaVersion.VERSION_1_8.toString() freeCompilerArgs += "-Xjvm-default=all" } } // TODO: provide Project using the new multiple context receivers functionality. // this is prototyped in 1.6.20 and will probably reach beta in Kotlin 1.8 or 1.9 //context(Project) fun CommonExtension<*, *, *, *>.configureCompose(project: Project) { buildFeatures.compose = true composeOptions.kotlinCompilerExtensionVersion = project.libs.findVersion("androidx-compose-compiler").get().requiredVersion project.dependencies.apply { // the runtime dependency is required to build a library when compose is enabled addProvider("implementation", project.libs.findLibrary("androidx-compose-runtime").get()) // these dependencies are required for tests of Composables addProvider("debugImplementation", project.libs.findBundle("androidx-compose-debug").get()) addProvider("testDebugImplementation", project.libs.findBundle("androidx-compose-testing").get()) } } private fun BaseExtension.configureTestOptions() { testOptions { unitTests { isIncludeAndroidResources = true all { // increase unit tests max heap size it.jvmArgs("-Xmx2g") } } } }
buildSrc/src/main/kotlin/AndroidConfiguration.kt
2462661337
package com.mycollab.community.vaadin.web.ui import com.mycollab.common.EntryUpdateNotification import com.mycollab.core.AbstractNotification import com.mycollab.vaadin.ui.ELabel import com.mycollab.vaadin.web.ui.AbstractNotificationComponent import com.mycollab.vaadin.web.ui.WebThemes import com.vaadin.ui.Component import com.vaadin.ui.CssLayout import org.slf4j.LoggerFactory import org.vaadin.viritin.button.MButton /** * @author MyCollab Ltd * @since 6.0.0 */ class NotificationComponent : AbstractNotificationComponent() { override fun buildComponentFromNotificationExclusive(item: AbstractNotification): Component? { return when (item) { is EntryUpdateNotification -> ProjectNotificationComponent(item) else -> { LOG.error("Do not support notification type $item") null } } } override fun displayTrayNotificationExclusive(item: AbstractNotification) { } inner class ProjectNotificationComponent(notification: EntryUpdateNotification) : CssLayout() { init { setWidth("100%") val noLabel = ELabel.html(notification.message).withStyleName(WebThemes.LABEL_WORD_WRAP) addComponent(noLabel) val readBtn = MButton("Read").withStyleName(WebThemes.BUTTON_ACTION).withListener { [email protected](notification) [email protected](this) } addComponent(readBtn) } } companion object { private val LOG = LoggerFactory.getLogger(NotificationComponent::class.java) } }
mycollab-web-community/src/main/java/com/mycollab/community/vaadin/web/ui/NotificationComponent.kt
818071263
package ru.fantlab.android.provider.glide import android.content.Context import android.graphics.drawable.PictureDrawable import com.bumptech.glide.Glide import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule import java.io.InputStream @GlideModule class AppGlideModule : AppGlideModule() { override fun registerComponents( context: Context, glide: Glide, registry: Registry ) { registry.register(GlideDecodedResource::class.java, PictureDrawable::class.java, GlideDrawableTranscoder()) .append(InputStream::class.java, GlideDecodedResource::class.java, GlideDecoder()) } override fun isManifestParsingEnabled(): Boolean = false }
app/src/main/kotlin/ru/fantlab/android/provider/glide/AppGlideModule.kt
2885402785
/* * Copyright 2018 Kislitsyn Ilya * * 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.github.snt.ui.javafx.lib import com.sun.javafx.scene.control.skin.TextAreaSkin import javafx.scene.Node import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.scene.layout.Background import javafx.scene.layout.GridPane import javafx.scene.layout.Priority import javafx.stage.Stage import org.github.snt.lib.err.SntException import org.github.snt.lib.err.SntResult.GENERAL_ERROR import org.github.snt.lib.util.extractStackTrace fun initWindow(stage: Stage, call: Stage.() -> Unit) { stage.call() } fun changeScene(scene: Scene, targetScene: StatefulScene) { val stage = scene.window as Stage stage.scene = targetScene.scene stage.sizeToScene() } fun closeScene(scene: Scene) { val stage = scene.window as Stage stage.close() } fun showError(error: Throwable) { val cause = error as? SntException ?: SntException(GENERAL_ERROR, error) val alert = Alert(Alert.AlertType.ERROR) alert.title = "Application error" alert.headerText = "Error - ${cause.result}" alert.contentText = cause.message alert.dialogPane.expandableContent = buildDialogInfoArea("Stacktrace:", cause.extractStackTrace()) alert.showAndWait() } fun requestConfirm(text: String): Boolean { val alert = Alert(Alert.AlertType.CONFIRMATION) alert.title = "Confirmation required" alert.headerText = text return alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK } fun buildDialogInfoArea(header: String, data: String): GridPane { val label = Label(header) val textArea = TextArea(data) textArea.isEditable = false textArea.isWrapText = true textArea.maxWidth = java.lang.Double.MAX_VALUE textArea.maxHeight = java.lang.Double.MAX_VALUE GridPane.setVgrow(textArea, Priority.ALWAYS) GridPane.setHgrow(textArea, Priority.ALWAYS) val content = GridPane() content.maxWidth = java.lang.Double.MAX_VALUE content.add(label, 0, 0) content.add(textArea, 0, 1) return content } fun newLabel(text: String = "", isUnderlined: Boolean = false): Label { val result = Label(text) result.isWrapText = true result.isUnderline = isUnderlined return result } fun newTextField(text: String = "", id: String? = null, isEditable: Boolean = true): Node { if (!isEditable) { return Label(text) } val result = TextField() result.text = text result.id = id return result } fun newPasswordField(text: String = "", id: String? = null, isEditable: Boolean = true): Node { if (!isEditable) { // TODO add context menu to copy value to the buffer return Label("******") } val result = PasswordField() result.text = text result.id = id return result } /** * Creates text area with correct behavior. * @param text Text to fill area with * @param id Area ID * @return Correct text area */ fun newTextArea(text: String = "", id: String? = null, isEditable: Boolean = true, background: Background? = null): Node { // if (!isEditable) { // return newLabel(text) // } val result = TextArea(text) result.id = id result.isWrapText = true if (background != null) { result.background = background } if (!isEditable) { result.isEditable = false } result.addEventHandler(KeyEvent.KEY_PRESSED) { event -> val source = event.source as TextArea val skin = source.skin as TextAreaSkin if (event.code == KeyCode.TAB && !event.isControlDown) { if (event.isShiftDown) { skin.behavior.traversePrevious() } else { skin.behavior.traverseNext() } event.consume() } } return result }
snt-ui-javafx/src/main/kotlin/org/github/snt/ui/javafx/lib/UIUtils.kt
793516271
/* * Copyright (c) 2017. tangzx([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.tang.intellij.lua.editor.formatter import com.intellij.application.options.CodeStyleAbstractPanel import com.intellij.application.options.IndentOptionsEditor import com.intellij.application.options.SmartIndentOptionsEditor import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable.SPACES_OTHER import com.intellij.psi.codeStyle.CommonCodeStyleSettings import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider import com.tang.intellij.lua.lang.LuaLanguage /** * Created by tangzx on 2017/2/22. */ class LuaLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() { override fun getLanguage(): LuaLanguage = LuaLanguage.INSTANCE override fun getCodeSample(settingsType: LanguageCodeStyleSettingsProvider.SettingsType): String { return CodeStyleAbstractPanel.readFromFile(this.javaClass, "preview.lua.template") } override fun getIndentOptionsEditor(): IndentOptionsEditor { return SmartIndentOptionsEditor() } override fun getDefaultCommonSettings(): CommonCodeStyleSettings { val commonSettings = CommonCodeStyleSettings(language) commonSettings.initIndentOptions() return commonSettings } override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: LanguageCodeStyleSettingsProvider.SettingsType) { when (settingsType) { LanguageCodeStyleSettingsProvider.SettingsType.SPACING_SETTINGS -> { consumer.showCustomOption(LuaCodeStyleSettings::class.java, "SPACE_AFTER_TABLE_FIELD_SEP", "After field sep", SPACES_OTHER) consumer.showCustomOption(LuaCodeStyleSettings::class.java, "SPACE_AROUND_BINARY_OPERATOR", "Around binary operator", SPACES_OTHER) consumer.showCustomOption(LuaCodeStyleSettings::class.java, "SPACE_INSIDE_INLINE_TABLE", "Inside inline table", SPACES_OTHER) consumer.showStandardOptions("SPACE_AROUND_ASSIGNMENT_OPERATORS", "SPACE_BEFORE_COMMA", "SPACE_AFTER_COMMA") } LanguageCodeStyleSettingsProvider.SettingsType.WRAPPING_AND_BRACES_SETTINGS -> { consumer.showStandardOptions( "METHOD_PARAMETERS_WRAP", "ALIGN_MULTILINE_PARAMETERS", "CALL_PARAMETERS_WRAP", "ALIGN_MULTILINE_PARAMETERS_IN_CALLS", // keep when reformatting "KEEP_SIMPLE_BLOCKS_IN_ONE_LINE", //align group declarations "ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS" ) consumer.showCustomOption(LuaCodeStyleSettings::class.java, "ALIGN_TABLE_FIELD_ASSIGN", "Align table field assign", "Table") } else -> { } } } }
src/main/java/com/tang/intellij/lua/editor/formatter/LuaLanguageCodeStyleSettingsProvider.kt
4112965351
package ru.fantlab.android.ui.modules.work.overview import android.os.Bundle import ru.fantlab.android.data.dao.model.* import ru.fantlab.android.ui.base.mvp.BaseMvp import ru.fantlab.android.ui.widgets.dialog.BookcasesDialogView import ru.fantlab.android.ui.widgets.dialog.ListDialogView import ru.fantlab.android.ui.widgets.dialog.RatingDialogView import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder interface WorkOverviewMvp { interface View : BaseMvp.View, ListDialogView.ListDialogViewActionCallback, BookcasesDialogView.BookcasesDialogViewActionCallback, RatingDialogView.RatingDialogViewActionCallback { fun onInitViews( work: Work, rootSagas: ArrayList<WorkRootSaga>, awards: ArrayList<Nomination>, authors: ArrayList<Work.Author> ) fun onSetClassification(classificatory: ArrayList<GenreGroup>) fun onSetEditions(editions: ArrayList<EditionsBlocks.EditionsBlock>) fun onSetBookcases(inclusions: ArrayList<BookcaseSelection>) fun onSetTranslations(translations: ArrayList<Translation>) fun onSetContent(children: ArrayList<ChildWork>) fun onItemClicked(item: Nomination) fun onSetMark(mark: Int, markCount: String, midMark: String) fun onGetMarks(marks: ArrayList<MarkMini>) fun onSetTitle(title: String) fun onShowErrorView(msgRes: String?) fun onBookcaseSelectionUpdated(bookcaseId: Int, include: Boolean) } interface Presenter : BaseMvp.Presenter, BaseViewHolder.OnItemClickListener<Nomination> { fun onFragmentCreated(bundle: Bundle) fun getMarks(userId: Int, workIds: ArrayList<Int>) fun getContent() fun getClassification() fun onSendMark(workId: Int, mark: Int) } }
app/src/main/kotlin/ru/fantlab/android/ui/modules/work/overview/WorkOverviewMvp.kt
3892550522
/* * Copyright (c) 2017. tangzx([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.tang.intellij.lua.codeInsight import com.intellij.codeInsight.hints.HintInfo import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.InlayParameterHintsProvider import com.intellij.codeInsight.hints.Option import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.tang.intellij.lua.psi.* import com.tang.intellij.lua.search.SearchContext import com.tang.intellij.lua.ty.* import java.util.* /** * Created by TangZX on 2016/12/14. */ class LuaParameterHintsProvider : InlayParameterHintsProvider { companion object { private val ARGS_HINT = Option("lua.hints.show_args_type", "Show argument name hints", true) private val LOCAL_VARIABLE_HINT = Option("lua.hints.show_local_var_type", "Show local variable type hints", false) private val PARAMETER_TYPE_HINT = Option("lua.hints.show_parameter_type", "Show parameter type hints", false) private val FUNCTION_HINT = Option("lua.hints.show_function_type", "Show function return type hints", false) private const val TYPE_INFO_PREFIX = "@TYPE@" private var EXPR_HINT = arrayOf(LuaLiteralExpr::class.java, LuaBinaryExpr::class.java, LuaUnaryExpr::class.java, LuaClosureExpr::class.java, LuaTableExpr::class.java) } override fun getParameterHints(psi: PsiElement): List<InlayInfo> { val list = ArrayList<InlayInfo>() if (psi is LuaCallExpr) { if (!ARGS_HINT.get()) return list @Suppress("UnnecessaryVariable") val callExpr = psi val args = callExpr.args as? LuaListArgs ?: return list val exprList = args.exprList val context = SearchContext.get(callExpr.getProject()) val type = callExpr.guessParentType(context) val ty = TyUnion.find(type, ITyFunction::class.java) ?: return list // 是否是 inst:method() 被用为 inst.method(self) 形式 val isInstanceMethodUsedAsStaticMethod = ty.isColonCall && callExpr.isMethodDotCall val sig = ty.findPerfectSignature(callExpr) sig.processArgs(null, callExpr.isMethodColonCall) { index, paramInfo -> val expr = exprList.getOrNull(index) ?: return@processArgs false val show = if (index == 0 && isInstanceMethodUsedAsStaticMethod) { true } else PsiTreeUtil.instanceOf(expr, *EXPR_HINT) if (show) list.add(InlayInfo(paramInfo.name, expr.node.startOffset)) true } } else if (psi is LuaParamNameDef) { if (PARAMETER_TYPE_HINT.get()) { val type = psi.guessType(SearchContext.get(psi.project)) if (!Ty.isInvalid(type)) { return listOf(InlayInfo("$TYPE_INFO_PREFIX${type.displayName}", psi.textOffset + psi.textLength)) } } } else if (psi is LuaNameDef) { if (LOCAL_VARIABLE_HINT.get()) { val type = psi.guessType(SearchContext.get(psi.project)) if (!Ty.isInvalid(type)) { return listOf(InlayInfo("$TYPE_INFO_PREFIX${type.displayName}", psi.textOffset + psi.textLength)) } } } else if (psi is LuaFuncBodyOwner) { val paren = psi.funcBody?.rparen if (FUNCTION_HINT.get() && paren != null) { val type = psi.guessReturnType(SearchContext.get(psi.project)) if (!Ty.isInvalid(type)) { return listOf(InlayInfo("$TYPE_INFO_PREFIX${type.displayName}", paren.textOffset + paren.textLength)) } } } return list } override fun getHintInfo(psiElement: PsiElement): HintInfo? = null override fun getDefaultBlackList(): Set<String> { return HashSet() } override fun isBlackListSupported() = false override fun getSupportedOptions(): List<Option> { return listOf(ARGS_HINT, LOCAL_VARIABLE_HINT, PARAMETER_TYPE_HINT, FUNCTION_HINT) } override fun getInlayPresentation(inlayText: String): String { if (inlayText.startsWith(TYPE_INFO_PREFIX)) { return " : ${inlayText.substring(TYPE_INFO_PREFIX.length)}" } return "$inlayText : " } }
src/main/java/com/tang/intellij/lua/codeInsight/LuaParameterHintsProvider.kt
459181256
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.domain.tabs import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import androidx.browser.customtabs.* import androidx.core.os.bundleOf import java.util.* /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class CustomTabsHelper( private val context: Context ) : CustomTabsServiceConnection() { private var bound: Boolean = false var session: CustomTabsSession? = null private set internal fun bind() { if (!bound) { val packageName = findPackageNameToUse(context) ?: return bound = CustomTabsClient.bindCustomTabsService(context, packageName, this) } } internal fun unbind() { if (bound) { context.unbindService(this) bound = false session = null } } fun mayLaunchUrl(url: String) { session?.mayLaunchUrl(Uri.parse(url), null, null) } fun mayLaunchUrl(urls: List<String>) { val session = session ?: return if (urls.isEmpty()) { return } try { if (urls.size == 1) { session.mayLaunchUrl(Uri.parse(urls[0]), null, null) return } val otherLikelyBundles = urls.subList(1, urls.size).map { bundleOf(CustomTabsService.KEY_URL to Uri.parse(it)) } session.mayLaunchUrl(Uri.parse(urls[0]), null, otherLikelyBundles) } catch (ignored: Exception) { unbind() } } override fun onCustomTabsServiceConnected( name: ComponentName, client: CustomTabsClient ) { try { client.warmup(0) session = client.newSession(CustomTabsCallback()) } catch (ignored: Exception) { unbind() } } override fun onServiceDisconnected(name: ComponentName) { session = null } companion object { private val PREFERRED_PACKAGES = listOf( "com.android.chrome", // Chrome "com.chrome.beta", // Chrome Beta "com.chrome.dev", // Chrome Dev "com.chrome.canary" // Chrome Canary ) private const val ACTION_CUSTOM_TABS_CONNECTION = "android.support.customtabs.action.CustomTabsService" private const val EXTRA_CUSTOM_TABS_KEEP_ALIVE = "android.support.customtabs.extra.KEEP_ALIVE" var packageNameToBind: String? = null private set fun addKeepAliveExtra( context: Context, intent: Intent ) { val keepAliveIntent = Intent().setClassName( context.packageName, KeepAliveService::class.java.canonicalName!! ) intent.putExtra(EXTRA_CUSTOM_TABS_KEEP_ALIVE, keepAliveIntent) } private fun findPackageNameToUse(context: Context): String? { packageNameToBind = findPackageNameToUseInner(context) return packageNameToBind } private fun findPackageNameToUseInner(context: Context): String? { val pm = context.packageManager val browsers = OpenUriUtils.getBrowserPackages(context) val services = pm.queryIntentServices(Intent(ACTION_CUSTOM_TABS_CONNECTION), 0) val candidate = ArrayList<String>() for (service in services) { if (service.serviceInfo == null) { continue } val packageName = service.serviceInfo.packageName if (browsers.contains(packageName)) { candidate.add(packageName) } } if (candidate.isEmpty()) { return null } if (candidate.size == 1) { return candidate[0] } val defaultBrowser = OpenUriUtils.getDefaultBrowserPackage(context) if (candidate.contains(defaultBrowser)) { return defaultBrowser } for (packageName in PREFERRED_PACKAGES) { if (candidate.contains(packageName)) { return packageName } } return null } } }
mobile/src/main/java/net/mm2d/dmsexplorer/domain/tabs/CustomTabsHelper.kt
809413501
package reagent.operator import reagent.Observable import reagent.Task fun <I> Observable<I>.any(predicate: (I) -> Boolean): Task<Boolean> = ObserableAny(this, predicate) internal class ObserableAny<out I>( private val upstream: Observable<I>, private val predicate: (I) -> Boolean ) : Task<Boolean>() { override suspend fun produce(): Boolean { var result = false upstream.subscribe { if (predicate(it)) { result = true return@subscribe false } return@subscribe true } return result } }
reagent/common/src/main/kotlin/reagent/operator/any.kt
1949493347
package com.squareup.anvil.sample import com.squareup.anvil.annotations.MergeSubcomponent import com.squareup.scopes.LoggedInScope import com.squareup.scopes.SingleIn @SingleIn(LoggedInScope::class) @MergeSubcomponent(LoggedInScope::class) interface LoggedInComponent
examples/anvil/app/src/main/java/com/squareup/anvil/sample/LoggedInComponent.kt
3000486234
package com.github.why168.kotlinlearn.api import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * * * @author Edwin.Wu * @version 2018/2/24 上午11:32 * @since JDK1.8 */ class IoMainScheduler <T> : BaseScheduler<T>(Schedulers.io(), AndroidSchedulers.mainThread())
KotlinLearning/app/src/main/java/com/github/why168/kotlinlearn/api/IoMainScheduler.kt
1985633514
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.settings /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ enum class SortKey { NONE, NAME, DATE, ; companion object { private val map = values().map { it.name to it }.toMap() fun of(name: String): SortKey = map.getOrElse(name) { NONE } } }
mobile/src/main/java/net/mm2d/dmsexplorer/settings/SortKey.kt
4018588302
package de.tum.`in`.tumcampusapp.utils import android.content.Context import android.net.NetworkCapabilities import android.net.NetworkCapabilities.* import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.M import org.jetbrains.anko.connectivityManager object NetUtils { @JvmStatic val internetCapability = if (SDK_INT < M) NET_CAPABILITY_INTERNET else NET_CAPABILITY_VALIDATED private fun NetworkCapabilities.hasConnectivity(): Boolean { return hasCapability(internetCapability) } private inline fun anyConnectedNetwork( context: Context, condition: (NetworkCapabilities) -> Boolean = { true } ): Boolean { val connectivityMgr = context.connectivityManager return connectivityMgr.allNetworks.asSequence().filter { connectivityMgr.getNetworkInfo(it)?.isConnected ?: false }.mapNotNull { connectivityMgr.getNetworkCapabilities(it) }.any { it.hasConnectivity() && condition(it) } } /** * Check if a network connection is available or can be available soon * * @return if any internet connectivity is available */ @JvmStatic fun isConnected(context: Context): Boolean { return anyConnectedNetwork(context) } /** * Check if a network connection is available or can be available soon * and if the available connection is a wifi internet connection * * @return if an unmetered connection (probably WiFi) is available */ @JvmStatic fun isConnectedWifi(context: Context): Boolean { return anyConnectedNetwork(context) { it.hasCapability(NET_CAPABILITY_NOT_METERED) } } }
app/src/main/java/de/tum/in/tumcampusapp/utils/NetUtils.kt
3364195742
package me.boger.geographic.core import android.app.Application import android.text.TextUtils import com.facebook.drawee.backends.pipeline.Fresco import com.tencent.bugly.Bugly import com.tencent.bugly.beta.Beta import com.tencent.bugly.crashreport.CrashReport import me.boger.geographic.BuildConfig import me.boger.geographic.R import me.boger.geographic.biz.common.MainActivity import me.boger.geographic.util.Timber /** * Created by BogerChan on 2017/6/25. */ class NGApplication : Application() { override fun onCreate() { super.onCreate() initLog() Fresco.initialize(this) AppConfiguration.init(this) NGRumtime.init(this) LocalizationWorker.prepare(this) initBugly() } private fun initBugly() { val appKeyBugly = getString(R.string.app_id_bugly) if (!TextUtils.isEmpty(appKeyBugly)) { Bugly.init(this, appKeyBugly, BuildConfig.LOGGABLE) } Beta.canShowUpgradeActs.add(MainActivity::class.java) Beta.autoDownloadOnWifi = true Beta.autoCheckUpgrade = true CrashReport.setIsDevelopmentDevice(this, BuildConfig.LOGGABLE) } private fun initLog() { if (BuildConfig.LOGGABLE) { Timber.plant(Timber.DebugTree()) } } }
app/src/main/java/me/boger/geographic/core/NGApplication.kt
4042168599
package org.jetbrains.pmdkotlin.lang.kotlin.rule.deadcode import com.intellij.psi.PsiElement import net.sourceforge.pmd.lang.ast.Node import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.pmdkotlin.lang.kotlin.ast.KotlinASTNodeAdapter public class UnusedVariableRule: AbstractUnusedVariableRule(Errors.UNUSED_VARIABLE){ override fun addViolation(element: PsiElement) { var outerNode = element.getCopyableUserData<Node>(KotlinASTNodeAdapter.OUTER_NODE_KEY) addViolation(savedData, outerNode) } }
src/main/kotlin/org/jetbrains/pmdkotlin/lang/kotlin/rule/deadcode/UnusedVariableRule.kt
1797579516
package com.naosim.rpgmodel.android.sirokuro import android.content.SharedPreferences import com.naosim.rpglib.model.value.ItemId import com.naosim.rpglib.model.value.ItemSet import com.naosim.rpglib.model.value.field.FieldNameImpl import com.naosim.rpglib.model.value.field.Position import com.naosim.rpglib.model.value.field.X import com.naosim.rpglib.model.value.field.Y import com.naosim.rpgmodel.sirokuro.charactor.GameItem import com.naosim.rpgmodel.sirokuro.charactor.getGameItem import com.naosim.rpgmodel.sirokuro.global.DataSaveContainer import com.naosim.rpgmodel.sirokuro.global.DataSaveRepository import com.naosim.rpgmodel.sirokuro.global.Status import com.naosim.rpgmodel.sirokuro.global.Turn import com.naosim.rpgmodel.sirokuro.map.YagiFieldName class DataSaveRepositoryAndroidImpl(val sharedPreferences: SharedPreferences): DataSaveRepository { override fun load(): DataSaveContainer { val itemSet = ItemSet<GameItem>() val itemCsv = sharedPreferences.getString("itemCsv", "${GameItem.やくそう.itemId.value}") itemCsv .split(",") .filter { it.trim().length > 0 } .map { getGameItem(ItemId(it)) } .forEach { itemSet.add(it) } val status = Status() val turnString = sharedPreferences.getString("turn", "kuro_eat") status.turnValue.setValue(Turn.valueOf(turnString)) val position = Position( FieldNameImpl(sharedPreferences.getString("fieldName", YagiFieldName.main.value)), X(sharedPreferences.getInt("x", 0)), Y(sharedPreferences.getInt("y", 0)) ) return DataSaveContainer(status, itemSet, position) } override fun save(dataSaveContainer: DataSaveContainer) { val editor = sharedPreferences.edit() editor.putString("turn", dataSaveContainer.status.turnValue.getValueString()) val itemCsv = dataSaveContainer .itemSet .list .map({ it.itemId.value }) .joinToString(",") editor.putString("itemCsv", itemCsv) editor.putString("fieldName", dataSaveContainer.position.fieldName.value) editor.putInt("x", dataSaveContainer.position.x.value) editor.putInt("y", dataSaveContainer.position.y.value) editor.commit() } }
app/src/main/kotlin/com/naosim/rpgmodel/android/sirokuro/DataSaveRepositoryAndroidImpl.kt
1508513764
/* * Copyright (C) 2020 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.marklogic.log class MarkLogicErrorLogMessage( date: String, time: String, logLevel: String, appServer: String?, continuation: Boolean, override val message: String ) : MarkLogicErrorLogLine(date, time, logLevel, appServer, continuation)
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/log/MarkLogicErrorLogMessage.kt
3013907171
/* * Copyright (C) 2019 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.saxon.query.s9api.binding.om import uk.co.reecedunn.intellij.plugin.core.reflection.getAnyMethod import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.QName class StructuredQName(`object`: Any, `class`: Class<*>) : QName(`object`, `class`) { override fun getNamespaceURI(): String { return saxonClass.getAnyMethod("getURI", "getNamespaceURI").invoke(`object`) as String } override fun getLocalName(): String { return saxonClass.getAnyMethod("getLocalPart", "getLocalName").invoke(`object`) as String } }
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/om/StructuredQName.kt
3212294973
/* * Copyright (C) 2020 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.xslt.ast.xslt import com.intellij.psi.PsiElement /** * An XSLT 1.0 `xsl:preserve-space` node in the XSLT AST. */ interface XsltPreserveSpace : PsiElement
src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/ast/xslt/XsltPreserveSpace.kt
159677465
package org.stepik.android.presentation.submission import ru.nobird.android.core.model.PagedList import org.stepik.android.domain.filter.model.SubmissionsFilterQuery import org.stepik.android.domain.submission.model.SubmissionItem interface SubmissionsView { sealed class State { data class Data( val submissionsFilterQuery: SubmissionsFilterQuery, val contentState: ContentState ) : State() } sealed class ContentState { object Idle : ContentState() object Loading : ContentState() object NetworkError : ContentState() object ContentEmpty : ContentState() class Content(val items: PagedList<SubmissionItem.Data>) : ContentState() class ContentLoading(val items: PagedList<SubmissionItem.Data>) : ContentState() } fun setState(state: State) fun showNetworkError() fun showSubmissionsFilterDialog(submissionsFilterQuery: SubmissionsFilterQuery) }
app/src/main/java/org/stepik/android/presentation/submission/SubmissionsView.kt
1158121489
package nl.shadowlink.tools.shadowlib.paths import nl.shadowlink.tools.io.ReadFunctions /** * @author Shadow-Link */ class Node(rf: ReadFunctions) { val memAdress = rf.readInt() val zero = rf.readInt() val areaID = rf.readShort() val nodeID = rf.readShort() val unknown = rf.readInt() val always7FFE = rf.readShort() val linkID = rf.readShort() val posX = rf.readShort() val posY = rf.readShort() val posZ = rf.readShort() val pathWidth = rf.readByte() val pathType = rf.readByte() val flags = rf.readInt() override fun toString(): String { return StringBuilder("--------------Node---------------") .append("Mem Adress: $memAdress") .append("Zero: $zero") .append("AreaID: $areaID") .append("NodeID: $nodeID") .append("unknown: $unknown") .append("Always7FFE: $always7FFE") .append("LinkID: $linkID") .append("PosX: " + (posX / 8).toFloat()) .append("PosY: " + (posY / 8).toFloat()) .append("PosZ: " + (posZ / 128).toFloat()) .append("PathWidth: $pathWidth") .append("PathType: $pathType") .append("Flags: $flags") .toString() } }
src/main/java/nl/shadowlink/tools/shadowlib/paths/Node.kt
897121513
package org.kesmarag.megaptera.kmeans import org.kesmarag.megaptera.data.DataSet import org.kesmarag.megaptera.data.Observation import org.kesmarag.megaptera.utils.Owner import java.io.Serializable class Kmeans(val dataSet: DataSet, val clusters: Int = 3, id: Int = 0) : Owner(id), Serializable { public var centroids: Array<DoubleArray> = Array(clusters, { DoubleArray(dataSet.observationLength) }) private set private var observationList: List<Observation> = dataSet.members .filter { isOwned(it) } .flatMap { it.data.toList() } private var changes = 0 init { adapt() //display() } public fun adapt() { observationList.forEach { it.redistribute(clusters, 0) } var step: Int = 0 do { step++ var sum = Array(clusters, { DoubleArray(dataSet.observationLength) }) var L = IntArray(clusters) changes = 0 observationList.forEach { L[it.ownerID]++ for (n in 0..dataSet.observationLength - 1) { centroids[it.ownerID][n] += it.data[n] } } centroids.forEachIndexed { i, it -> for (n in 0..dataSet.observationLength - 1) { centroids[i][n] /= (L[i].toDouble() + 1) } } for (i in 0..observationList.size - 1) { var pos: Int = 0 var min: Double = dist(observationList[i].data, centroids[0]) for (k in 1..clusters - 1) { if (dist(observationList[i].data, centroids[k]) < min) { min = dist(observationList[i].data, centroids[k]) pos = k } } if (observationList[i].ownerID != pos ) { changes++ observationList[i].forceSetOwner(pos) } for (n in 0..dataSet.observationLength - 1) { sum[pos][n] += observationList[i].data[n] } L[pos]++ } } while (changes > 0 && step <= 100) } public fun dist(a1: DoubleArray, a2: DoubleArray): Double { var s: Double = 0.0 for (n in 0..a1.size - 1) { s += (a1[n] - a2[n]) * (a1[n] - a2[n]) } return s } public fun display(): Unit { println("==> centroids <==") centroids.forEach { for (n in 0..dataSet.observationLength - 1) { print(it[n]) print(" ") } println() } } }
src/main/org/kesmarag/megaptera/kmeans/Kmeans.kt
2239707949
@file:Suppress("NOTHING_TO_INLINE") package su.jfdev.anci.geography import su.jfdev.anci.geography.exceptions.* inline fun <R> Collection<Vec3i>.checkedAccess(location: Vec3i, using: (Vec3i) -> R): R { checkAccess(location) return using(location) } fun Collection<Vec3i>.checkAccess(location: Vec3i) { if (location !in this) throw CoverageAccessDeniedException(this, location) }
geography/src/main/kotlin/su/jfdev/anci/geography/CoverageUtil.kt
2294304362