content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package net.nekobako.twidere.extension.aniuta
import android.content.*
import android.os.Bundle
import org.mariotaku.twidere.constant.IntentConstants
class NowPlaying {
companion object {
private val TWIDERE_PACKAGE_NAME = "org.mariotaku.twidere"
}
fun fetchMusicMetadata(context: Context, callback: (MusicMetadata?) -> Unit) {
context.sendOrderedBroadcast(Intent(MusicPlayerListenerService.ACTION_FETCH_MUSIC_METADATA), null, object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
callback.invoke(this.getResultExtras(false)?.getParcelable("music_metadata"))
}
}, null, 0, null, null)
}
fun createTweetIntent(context: Context, musicMetadata: MusicMetadata): Intent {
val intent = Intent()
val extras = Bundle()
val uri = musicMetadata.getArtworkUri(context)
extras.putString(IntentConstants.EXTRA_APPEND_TEXT, context.resources.getString(R.string.tweet, musicMetadata.title, musicMetadata.artist))
extras.putParcelable(IntentConstants.EXTRA_IMAGE_URI, uri)
intent.putExtras(extras)
context.grantUriPermission(TWIDERE_PACKAGE_NAME, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
return intent
}
}
| app/src/main/java/net/nekobako/twidere/extension/aniuta/NowPlaying.kt | 3156019638 |
package app.cash.sqldelight.intellij.inspections
import app.cash.sqldelight.core.lang.validation.OptimisticLockValidator
import app.cash.sqldelight.intellij.intentions.AddOptimisticLockIntention
import com.alecstrong.sql.psi.core.psi.mixins.ColumnDefMixin
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
class OptimisticLockAnnotator : OptimisticLockValidator() {
override fun quickFix(element: PsiElement, lock: ColumnDefMixin): IntentionAction {
return AddOptimisticLockIntention(element, lock)
}
}
| sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/inspections/OptimisticLockAnnotator.kt | 2597619227 |
package com.benoitquenaudon.tvfoot.red.app.mvi
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class RedViewModelFactory @Inject constructor(
private val creators: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class $modelClass")
}
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException()
}
}
} | app/src/main/java/com/benoitquenaudon/tvfoot/red/app/mvi/RedViewModelFactory.kt | 3457759041 |
package net.numa08.gochisou.presentation.view.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_edit_navigation_identifier.*
import net.numa08.gochisou.R
class EditNavigationIdentifierActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_navigation_identifier)
setSupportActionBar(toolbar)
}
} | app/src/main/java/net/numa08/gochisou/presentation/view/activity/EditNavigationIdentifierActivity.kt | 3420809624 |
package ws.osiris.integration
import com.google.gson.Gson
import org.testng.annotations.Test
import ws.osiris.core.ContentType
import ws.osiris.core.HttpHeaders
import ws.osiris.core.InMemoryTestClient
import ws.osiris.core.JSON_CONTENT_TYPE
import ws.osiris.core.MimeTypes
import ws.osiris.core.TestClient
import ws.osiris.localserver.LocalHttpTestClient
import java.nio.file.Paths
import kotlin.test.assertEquals
import kotlin.test.assertTrue
private val components: TestComponents = TestComponentsImpl("Bob", 42)
private const val STATIC_DIR = "src/test/static"
@Test
class InMemoryIntegrationTest {
fun testApiInMemory() {
val client = InMemoryTestClient.create(components, api, Paths.get(STATIC_DIR))
assertApi(client)
}
}
@Test
class LocalHttpIntegrationTest {
fun testApiLocalHttpServer() {
LocalHttpTestClient.create(api, components, STATIC_DIR).use { assertApi(it) }
}
}
internal fun assertApi(client: TestClient) {
val gson = Gson()
fun Any?.parseJson(): Map<*, *> {
val json = this as? String ?: throw IllegalArgumentException("Value is not a string: $this")
return gson.fromJson(json, Map::class.java)
}
val rootResponse = client.get("/")
assertEquals(mapOf("message" to "hello, root!"), rootResponse.body.parseJson())
assertEquals(JSON_CONTENT_TYPE, ContentType.parse(rootResponse.headers[HttpHeaders.CONTENT_TYPE]!!))
assertEquals(200, rootResponse.status)
val response1 = client.get("/helloworld")
assertEquals(mapOf("message" to "hello, world!"), response1.body.parseJson())
assertEquals(JSON_CONTENT_TYPE, ContentType.parse(rootResponse.headers[HttpHeaders.CONTENT_TYPE]!!))
assertEquals(200, response1.status)
val response2 = client.get("/helloplain")
assertEquals("hello, world!", response2.body)
assertEquals(MimeTypes.TEXT_PLAIN, response2.headers[HttpHeaders.CONTENT_TYPE])
assertEquals(mapOf("message" to "hello, world!"), client.get("/hello/queryparam1").body.parseJson())
assertEquals(mapOf("message" to "hello, Alice!"), client.get("/hello/queryparam1?name=Alice").body.parseJson())
assertEquals(mapOf("message" to "hello, Tom!"), client.get("/hello/queryparam2?name=Tom").body.parseJson())
assertEquals(mapOf("message" to "hello, Peter!"), client.get("/hello/Peter").body.parseJson())
assertEquals(mapOf("message" to "hello, Bob!"), client.get("/hello/env").body.parseJson())
assertEquals(mapOf("message" to "hello, Max!"), client.post("/foo", "{\"name\":\"Max\"}").body.parseJson())
val response3 = client.get("/hello/queryparam2")
assertEquals(400, response3.status)
assertEquals("No value named 'name'", response3.body)
assertEquals(mapOf("message" to "foo 123 found"), client.get("/foo/123").body.parseJson())
val response5 = client.get("/foo/234")
assertEquals(404, response5.status)
assertEquals("No foo found with ID 234", response5.body)
val response6 = client.get("/servererror")
assertEquals(500, response6.status)
assertEquals("Server Error", response6.body)
val response7 = client.get("/public")
assertEquals(200, response7.status)
val body7 = response7.body
assertTrue(body7 is String && body7.contains("hello, world!"))
val response8 = client.get("/public/")
assertEquals(200, response8.status)
val body8 = response8.body
assertTrue(body8 is String && body8.contains("hello, world!"))
val response9 = client.get("/public/index.html")
assertEquals(200, response9.status)
val body9 = response9.body
assertTrue(body9 is String && body9.contains("hello, world!"))
val response10 = client.get("/public/baz/bar.html")
assertEquals(200, response10.status)
val body10 = response10.body
assertTrue(body10 is String && body10.contains("hello, bar!"))
}
| integration/src/test/kotlin/ws/osiris/integration/IntegrationTests.kt | 2578099150 |
package net.semlang.languageserver
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.eclipse.lsp4j.services.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CopyOnWriteArrayList
interface LanguageClientProvider {
fun getLanguageClient(): LanguageClient
}
class SemlangLanguageServer: LanguageServer, LanguageClientAware, LanguageClientProvider {
private val languageClientHolder = CopyOnWriteArrayList<LanguageClient>()
private val textDocumentService = SemlangTextDocumentService(this)
private val workspaceService = SemlangWorkspaceService(this)
override fun getTextDocumentService(): TextDocumentService {
return textDocumentService
}
override fun exit() {
System.exit(0)
}
override fun initialize(params: InitializeParams?): CompletableFuture<InitializeResult> {
// TODO: Configure capabilities
val capabilities = ServerCapabilities()
val textDocumentSyncOptions = TextDocumentSyncOptions()
textDocumentSyncOptions.openClose = true
textDocumentSyncOptions.change = TextDocumentSyncKind.Full // TODO: Incremental would be better
capabilities.setTextDocumentSync(textDocumentSyncOptions)
val result = InitializeResult(capabilities)
return CompletableFuture.completedFuture(result)
}
override fun getWorkspaceService(): WorkspaceService {
return workspaceService
}
override fun shutdown(): CompletableFuture<Any> {
// TODO: Release unused resources
return CompletableFuture.completedFuture(null)
}
override fun connect(client: LanguageClient) {
if (!languageClientHolder.isEmpty()) {
error("Expected empty languageClientHolder")
}
languageClientHolder.add(client)
}
override fun getLanguageClient(): LanguageClient {
return languageClientHolder[0]
}
}
class SemlangWorkspaceService(private val languageClientProvider: LanguageClientProvider): WorkspaceService {
override fun didChangeWatchedFiles(params: DidChangeWatchedFilesParams?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didChangeConfiguration(params: DidChangeConfigurationParams?) {
// TODO: If we ever have settings, update them here.
}
override fun symbol(params: WorkspaceSymbolParams?): CompletableFuture<MutableList<out SymbolInformation>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
class SemlangTextDocumentService(private val languageClientProvider: LanguageClientProvider): TextDocumentService {
val model = AllModulesModel(languageClientProvider)
override fun resolveCompletionItem(unresolved: CompletionItem?): CompletableFuture<CompletionItem> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun codeAction(params: CodeActionParams?): CompletableFuture<MutableList<out Command>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hover(position: TextDocumentPositionParams?): CompletableFuture<Hover> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun documentHighlight(position: TextDocumentPositionParams?): CompletableFuture<MutableList<out DocumentHighlight>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onTypeFormatting(params: DocumentOnTypeFormattingParams?): CompletableFuture<MutableList<out TextEdit>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun definition(position: TextDocumentPositionParams?): CompletableFuture<MutableList<out Location>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rangeFormatting(params: DocumentRangeFormattingParams?): CompletableFuture<MutableList<out TextEdit>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun codeLens(params: CodeLensParams?): CompletableFuture<MutableList<out CodeLens>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rename(params: RenameParams?): CompletableFuture<WorkspaceEdit> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun completion(position: TextDocumentPositionParams?): CompletableFuture<Either<MutableList<CompletionItem>, CompletionList>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun documentSymbol(params: DocumentSymbolParams?): CompletableFuture<MutableList<out SymbolInformation>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didOpen(params: DidOpenTextDocumentParams) {
val document = params.textDocument
model.documentWasOpened(document.uri, document.text)
}
override fun didSave(params: DidSaveTextDocumentParams?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun signatureHelp(position: TextDocumentPositionParams?): CompletableFuture<SignatureHelp> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didClose(params: DidCloseTextDocumentParams) {
val document = params.textDocument
model.documentWasClosed(document.uri)
}
override fun formatting(params: DocumentFormattingParams?): CompletableFuture<MutableList<out TextEdit>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun didChange(params: DidChangeTextDocumentParams) {
val document = params.textDocument
model.documentWasUpdated(document.uri, params.contentChanges[0].text)
}
override fun references(params: ReferenceParams?): CompletableFuture<MutableList<out Location>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun resolveCodeLens(unresolved: CodeLens?): CompletableFuture<CodeLens> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| kotlin/semlang-language-server/src/main/kotlin/server.kt | 599054787 |
package kotlinx.html
public abstract class Attribute<T>(val name: String) {
public fun get(tag: HtmlTag, property: PropertyMetadata): T {
return decode(tag[name]);
}
public fun set(tag: HtmlTag, property: PropertyMetadata, value: T) {
tag[name] = encode(value);
}
public abstract fun encode(t: T): String
public abstract fun decode(s: String): T
}
public open class StringAttribute(name: String) : Attribute<String>(name) {
public override fun encode(t: String): String {
return t // TODO: it actually might need HTML escaping
}
public override fun decode(s: String): String {
return s // TODO: it actually might need decode
}
}
public class TextAttribute(name: String) : StringAttribute(name)
public class RegexpAttribute(name: String) : StringAttribute(name)
public class IdAttribute(name: String) : StringAttribute(name)
public class MimeAttribute(name: String) : StringAttribute(name)
public class IntAttribute(name: String) : Attribute<Int>(name) {
public override fun encode(t: Int): String {
return t.toString()
}
public override fun decode(s: String): Int {
return s.toInt()
}
}
public open class BooleanAttribute(name: String, val trueValue: String = "true", val falseValue: String = "false") : Attribute<Boolean>(name) {
public override fun encode(t: Boolean): String {
return if (t) trueValue else falseValue
}
public override fun decode(s: String): Boolean {
return when (s) {
trueValue -> true
falseValue -> false
else -> throw RuntimeException("Unknown value for $name=$s")
}
}
}
public class TickerAttribute(name: String) : BooleanAttribute(name, name, "")
public class LinkAttribute(name: String) : Attribute<Link>(name) {
public override fun encode(t: Link): String {
return t.href()
}
public override fun decode(s: String): Link {
return DirectLink(s)
}
}
public interface StringEnum<T : Enum<T>> : Enum<T> {
public val value: String get() = name()
}
public class EnumAttribute<T : StringEnum<T>>(name: String, val klass: Class<T>) : Attribute<T>(name) {
public override fun encode(t: T): String {
return t.value
}
public override fun decode(s: String): T {
for (c in klass.getEnumConstants()) {
if (encode(c) == s) return c
}
throw RuntimeException("Can't decode '$s' as value of '${klass.getName()}'")
}
}
public class MimeTypesAttribute(name: String) : Attribute<List<String>>(name) {
public override fun encode(t: List<String>): String {
return t.join(",")
}
public override fun decode(s: String): List<String> {
return s.split(',').map { it.trim() }
}
}
| inspector/src/main/kotlin/kotlinx/html/AttributeTypes.kt | 3078858886 |
package com.stripe.android.test.core
import androidx.test.runner.screenshot.BasicScreenCaptureProcessor
import androidx.test.runner.screenshot.ScreenCapture
import com.google.common.truth.Truth.assertThat
import java.io.ByteArrayOutputStream
class ByteScreenCaptureProcessor : BasicScreenCaptureProcessor() {
val byteArrayOutputStream = ByteArrayOutputStream()
override fun process(capture: ScreenCapture): String {
capture.bitmap.compress(capture.format, 100, byteArrayOutputStream)
return ""
}
fun getBytes(): ByteArray {
return byteArrayOutputStream.toByteArray()
}
fun compare(screenCaptureProcessor: ByteScreenCaptureProcessor){
assertThat(getBytes()).isEqualTo(screenCaptureProcessor.getBytes())
}
}
| paymentsheet-example/src/androidTestDebug/java/com/stripe/android/test/core/ByteScreenCaptureProcessor.kt | 3024701048 |
package dwallet.core.infrastructure
/**
* Created by unsignedint8 on 8/18/17.
*/
open class Event {
private val observers = mutableMapOf<String, MutableList<EventCallback>>()
protected fun register(event: String, callback: EventCallback) {
var list = observers[event]
if (list == null) {
list = mutableListOf()
observers[event] = list
}
list.add(callback)
}
protected fun trigger(event: String, sender: Any, params: Any) = observers[event]?.forEach { it.invoke(sender, params) }
} | android/lib/src/main/java/dWallet/core/infrastructure/Event.kt | 309516149 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.appsearch.ktx
import android.content.Context
import androidx.appsearch.annotation.Document
import androidx.appsearch.app.AppSearchSchema
import androidx.appsearch.app.AppSearchSession
import androidx.appsearch.app.GenericDocument
import androidx.appsearch.app.PutDocumentsRequest
import androidx.appsearch.app.SearchSpec
import androidx.appsearch.app.SetSchemaRequest
import androidx.appsearch.localstorage.LocalStorage
import androidx.appsearch.testutil.AppSearchTestUtils.checkIsBatchResultSuccess
import androidx.appsearch.testutil.AppSearchTestUtils.convertSearchResultsToDocuments
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
public class AnnotationProcessorKtTest {
private companion object {
private const val DB_NAME = ""
}
private lateinit var session: AppSearchSession
@Before
public fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
session = LocalStorage.createSearchSessionAsync(
LocalStorage.SearchContext.Builder(context, DB_NAME).build()
).get()
// Cleanup whatever documents may still exist in these databases. This is needed in
// addition to tearDown in case a test exited without completing properly.
cleanup()
}
@After
public fun tearDown() {
// Cleanup whatever documents may still exist in these databases.
cleanup()
}
private fun cleanup() {
session.setSchemaAsync(SetSchemaRequest.Builder().setForceOverride(true).build()).get()
}
@Document
internal data class Card(
@Document.Namespace
val namespace: String,
@Document.Id
val id: String,
@Document.CreationTimestampMillis
val creationTimestampMillis: Long = 0L,
@Document.StringProperty(
indexingType = AppSearchSchema.StringPropertyConfig.INDEXING_TYPE_PREFIXES,
tokenizerType = AppSearchSchema.StringPropertyConfig.TOKENIZER_TYPE_PLAIN
)
val string: String? = null,
)
@Document
internal data class Gift(
@Document.Namespace
val namespace: String,
@Document.Id
val id: String,
@Document.CreationTimestampMillis
val creationTimestampMillis: Long = 0L,
// Collections
@Document.LongProperty
val collectLong: Collection<Long>,
@Document.LongProperty
val collectInteger: Collection<Int>,
@Document.DoubleProperty
val collectDouble: Collection<Double>,
@Document.DoubleProperty
val collectFloat: Collection<Float>,
@Document.BooleanProperty
val collectBoolean: Collection<Boolean>,
@Document.BytesProperty
val collectByteArr: Collection<ByteArray>,
@Document.StringProperty
val collectString: Collection<String>,
@Document.DocumentProperty
val collectCard: Collection<Card>,
// Arrays
@Document.LongProperty
val arrBoxLong: Array<Long>,
@Document.LongProperty
val arrUnboxLong: LongArray,
@Document.LongProperty
val arrBoxInteger: Array<Int>,
@Document.LongProperty
val arrUnboxInt: IntArray,
@Document.DoubleProperty
val arrBoxDouble: Array<Double>,
@Document.DoubleProperty
val arrUnboxDouble: DoubleArray,
@Document.DoubleProperty
val arrBoxFloat: Array<Float>,
@Document.DoubleProperty
val arrUnboxFloat: FloatArray,
@Document.BooleanProperty
val arrBoxBoolean: Array<Boolean>,
@Document.BooleanProperty
val arrUnboxBoolean: BooleanArray,
@Document.BytesProperty
val arrUnboxByteArr: Array<ByteArray>,
@Document.BytesProperty
val boxByteArr: Array<Byte>,
@Document.StringProperty
val arrString: Array<String>,
@Document.DocumentProperty
val arrCard: Array<Card>,
// Single values
@Document.StringProperty
val string: String,
@Document.LongProperty
val boxLong: Long,
@Document.LongProperty
val unboxLong: Long = 0,
@Document.LongProperty
val boxInteger: Int,
@Document.LongProperty
val unboxInt: Int = 0,
@Document.DoubleProperty
val boxDouble: Double,
@Document.DoubleProperty
val unboxDouble: Double = 0.0,
@Document.DoubleProperty
val boxFloat: Float,
@Document.DoubleProperty
val unboxFloat: Float = 0f,
@Document.BooleanProperty
val boxBoolean: Boolean,
@Document.BooleanProperty
val unboxBoolean: Boolean = false,
@Document.BytesProperty
val unboxByteArr: ByteArray,
@Document.DocumentProperty
val card: Card
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Gift
if (namespace != other.namespace) return false
if (id != other.id) return false
if (collectLong != other.collectLong) return false
if (collectInteger != other.collectInteger) return false
if (collectDouble != other.collectDouble) return false
if (collectFloat != other.collectFloat) return false
if (collectBoolean != other.collectBoolean) return false
// It's complicated to do a deep comparison of this, so we skip it
// if (collectByteArr != other.collectByteArr) return false
if (collectString != other.collectString) return false
if (collectCard != other.collectCard) return false
if (!arrBoxLong.contentEquals(other.arrBoxLong)) return false
if (!arrUnboxLong.contentEquals(other.arrUnboxLong)) return false
if (!arrBoxInteger.contentEquals(other.arrBoxInteger)) return false
if (!arrUnboxInt.contentEquals(other.arrUnboxInt)) return false
if (!arrBoxDouble.contentEquals(other.arrBoxDouble)) return false
if (!arrUnboxDouble.contentEquals(other.arrUnboxDouble)) return false
if (!arrBoxFloat.contentEquals(other.arrBoxFloat)) return false
if (!arrUnboxFloat.contentEquals(other.arrUnboxFloat)) return false
if (!arrBoxBoolean.contentEquals(other.arrBoxBoolean)) return false
if (!arrUnboxBoolean.contentEquals(other.arrUnboxBoolean)) return false
if (!arrUnboxByteArr.contentDeepEquals(other.arrUnboxByteArr)) return false
if (!boxByteArr.contentEquals(other.boxByteArr)) return false
if (!arrString.contentEquals(other.arrString)) return false
if (!arrCard.contentEquals(other.arrCard)) return false
if (string != other.string) return false
if (boxLong != other.boxLong) return false
if (unboxLong != other.unboxLong) return false
if (boxInteger != other.boxInteger) return false
if (unboxInt != other.unboxInt) return false
if (boxDouble != other.boxDouble) return false
if (unboxDouble != other.unboxDouble) return false
if (boxFloat != other.boxFloat) return false
if (unboxFloat != other.unboxFloat) return false
if (boxBoolean != other.boxBoolean) return false
if (unboxBoolean != other.unboxBoolean) return false
if (!unboxByteArr.contentEquals(other.unboxByteArr)) return false
if (card != other.card) return false
return true
}
}
@Test
fun testAnnotationProcessor() {
session.setSchemaAsync(
SetSchemaRequest.Builder()
.addDocumentClasses(Card::class.java, Gift::class.java).build()
).get()
// Create a Gift object and assign values.
val inputDocument = createPopulatedGift()
// Index the Gift document and query it.
checkIsBatchResultSuccess(
session.putAsync(
PutDocumentsRequest.Builder().addDocuments(inputDocument).build()
)
)
val searchResults = session.search("", SearchSpec.Builder().build())
val documents = convertSearchResultsToDocuments(searchResults)
assertThat(documents).hasSize(1)
// Convert GenericDocument to Gift and check values.
val outputDocument = documents[0].toDocumentClass(Gift::class.java)
assertThat(outputDocument).isEqualTo(inputDocument)
}
@Test
fun testGenericDocumentConversion() {
val inGift = createPopulatedGift()
val genericDocument1 = GenericDocument.fromDocumentClass(inGift)
val genericDocument2 = GenericDocument.fromDocumentClass(inGift)
val outGift = genericDocument2.toDocumentClass(Gift::class.java)
assertThat(inGift).isNotSameInstanceAs(outGift)
assertThat(inGift).isEqualTo(outGift)
assertThat(genericDocument1).isNotSameInstanceAs(genericDocument2)
assertThat(genericDocument1).isEqualTo(genericDocument2)
}
private fun createPopulatedGift(): Gift {
val card1 = Card("card.namespace", "card.id1")
val card2 = Card("card.namespace", "card.id2")
return Gift(
namespace = "gift.namespace",
id = "gift.id",
arrBoxBoolean = arrayOf(true, false),
arrBoxDouble = arrayOf(0.0, 1.0),
arrBoxFloat = arrayOf(2.0f, 3.0f),
arrBoxInteger = arrayOf(4, 5),
arrBoxLong = arrayOf(6L, 7L),
arrString = arrayOf("cat", "dog"),
boxByteArr = arrayOf(8, 9),
arrUnboxBoolean = booleanArrayOf(false, true),
arrUnboxByteArr = arrayOf(byteArrayOf(0, 1), byteArrayOf(2, 3)),
arrUnboxDouble = doubleArrayOf(1.0, 0.0),
arrUnboxFloat = floatArrayOf(3.0f, 2.0f),
arrUnboxInt = intArrayOf(5, 4),
arrUnboxLong = longArrayOf(7, 6),
arrCard = arrayOf(card2, card2),
collectLong = listOf(6L, 7L),
collectInteger = listOf(4, 5),
collectBoolean = listOf(false, true),
collectString = listOf("cat", "dog"),
collectDouble = listOf(0.0, 1.0),
collectFloat = listOf(2.0f, 3.0f),
collectByteArr = listOf(byteArrayOf(0, 1), byteArrayOf(2, 3)),
collectCard = listOf(card2, card2),
string = "String",
boxLong = 1L,
unboxLong = 2L,
boxInteger = 3,
unboxInt = 4,
boxDouble = 5.0,
unboxDouble = 6.0,
boxFloat = 7.0f,
unboxFloat = 8.0f,
boxBoolean = true,
unboxBoolean = false,
unboxByteArr = byteArrayOf(1, 2, 3),
card = card1
)
}
}
| appsearch/appsearch-ktx/src/androidTest/java/AnnotationProcessorKtTest.kt | 567655495 |
/*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.model.sudoku
/**
* A two dimensional cartesian Coordinate.
* Implemented as Flyweight (not quite, but Position.get(x,y) gives memoized objects)
*
* @property x the x coordinate
* @property y the y coordinate
*
*/
class Position(var x: Int, var y: Int) {
/**
* Instanziiert ein neues Position-Objekt mit den spezifizierten x- und y-Koordinaten. Ist eine der Koordinaten
* kleiner als 0, so wird eine IllegalArgumentException geworfen.
*
* @throws IllegalArgumentException
* Wird geworfen, falls eine der Koordinaten kleiner als 0 ist
*/
/** Identifies, if this Position is a Flyweight and thus may not be changed. */
private var fixed = true
/**
* Tests for equality with other [Position].
*
* @return true if obj is of same type and coordinates match
*/
override fun equals(obj: Any?): Boolean {
return if (obj == null || obj !is Position) {
false
} else {
x == obj.x
&& y == obj.y
}
}
/**
* Generates a unique hashcode for coordinates `< 65519`
*/
override fun hashCode(): Int {
val p = 65519
val q = 65521
return x * p + y * q
}
/**
* returns a distance vector by subtracting the parameter. (both objects remain unchanged)
* @param p a position to substract from this position
* @return distance between this and other as position(this-p)
*/
fun distance(p: Position): Position {
return Position(x - p.x, y - p.y)
}
/**
* Returns a String Representation of this Position.
*/
override fun toString(): String {
return "$x, $y"
}
companion object {
/**
* Das statische Position-Array
*/
private var positions: Array<Array<Position>>? = null
/**
* Returns a [Position] with the specified coordinates
*
* @param x the desired x-coordinate
* @param y the desired y-coordinate
* @return Position Object with the coordinates
* @throws IllegalArgumentException if either coordinate is > 0
*/
@JvmStatic
operator fun get(x: Int, y: Int): Position {
require(x >= 0 && y >= 0) { "a parameter is less than zero" }
if (positions == null) {
initializePositions()
}
return if (x < 25 && y < 25) {
positions!![x][y]
} else {
val pos = Position(x, y)
pos.fixed = false
pos
}
}
/**
* Initialises the Position Array for efficient Position storage.
*/
private fun initializePositions() {
positions = Array(25) { Array(25) { Position(0, 0) } }
for (x in 0..24) {
for (y in 0..24) {
positions!![x][y] = Position(x, y)
}
}
}
}
} | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/Position.kt | 2384590128 |
package org.jetbrains.fortran.lang.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import org.jetbrains.fortran.lang.FortranTypes
import org.jetbrains.fortran.lang.psi.impl.FortranCompositeElementImpl
abstract class FortranNamedElementImpl(node: ASTNode) : FortranCompositeElementImpl(node), FortranNamedElement, PsiNameIdentifierOwner {
override fun getNameIdentifier(): PsiElement? = findChildByType(FortranTypes.IDENTIFIER)
override fun getName(): String? = nameIdentifier?.text
override fun getNavigationElement(): PsiElement = nameIdentifier ?: this
override fun getTextOffset(): Int = nameIdentifier?.textOffset ?: super.getTextOffset()
} | src/main/java/org/jetbrains/fortran/lang/psi/ext/FortranNamedElementImpl.kt | 1838213677 |
package com.riaektiv.loop
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.CountDownLatch
/**
* Coding With Passion Since 1991
* Created: 4/1/2017, 2:59 PM Eastern Time
* @author Sergey Chuykov
*/
class LongEventHandler(var eventsToConsume: Int, var latch: CountDownLatch) : EventHandler<LongEvent> {
val l: Logger = LoggerFactory.getLogger(javaClass)
constructor() : this(0, CountDownLatch(1)) {
}
var checkSequence = false
var consumed = 0
override fun consumed(): Int {
return consumed
}
override fun onEvent(event: LongEvent) {
if (consumed < eventsToConsume) {
if(checkSequence && consumed.toLong() != event.value) {
l.debug("consumed={} {}", consumed, event)
l.debug("Failed")
latch.countDown()
}
if (++consumed >= eventsToConsume) {
l.debug("Done")
latch.countDown()
}
}
}
} | incubator-events/src/main/java/com/riaektiv/loop/LongEventHandler.kt | 2844137228 |
/*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.cli.options
abstract class OptionDefinition(
val group: OptionGroup,
val longName: String,
val description: String,
val acceptsValue: Boolean,
val shortName: Char? = null,
val allowMultiple: Boolean = false
) {
private var alreadySeen: Boolean = false
abstract val valueSource: OptionValueSource
val longOption = "--$longName"
val shortOption = if (shortName != null) "-$shortName" else null
init {
if (longName == "") {
throw IllegalArgumentException("Option long name must not be empty.")
}
if (longName.startsWith("-")) {
throw IllegalArgumentException("Option long name must not start with a dash.")
}
if (longName.length < 2) {
throw IllegalArgumentException("Option long name must be at least two characters long.")
}
if (description == "") {
throw IllegalArgumentException("Option description must not be empty.")
}
if (shortName != null && !shortName.isLetterOrDigit()) {
throw IllegalArgumentException("Option short name must be alphanumeric.")
}
}
fun parse(args: Iterable<String>): OptionParsingResult {
if (args.none()) {
throw IllegalArgumentException("List of arguments cannot be empty.")
}
if (alreadySeen && !allowMultiple) {
return specifiedMultipleTimesError()
}
val arg = args.first()
val argName = arg.substringBefore("=")
if (!nameMatches(argName)) {
throw IllegalArgumentException("Next argument in list of arguments is not for this option.")
}
alreadySeen = true
return parseValue(args)
}
private fun specifiedMultipleTimesError(): OptionParsingResult {
val shortOptionHint = if (shortName != null) " (or '$shortOption')" else ""
return OptionParsingResult.InvalidOption("Option '$longOption'$shortOptionHint cannot be specified multiple times.")
}
private fun nameMatches(nameFromArgument: String): Boolean {
return nameFromArgument == longOption || nameFromArgument == shortOption
}
internal abstract fun parseValue(args: Iterable<String>): OptionParsingResult
internal abstract fun checkDefaultValue(): DefaultApplicationResult
open val descriptionForHelp: String = description
open val valueFormatForHelp: String = "value"
}
sealed class DefaultApplicationResult {
object Succeeded : DefaultApplicationResult()
data class Failed(val message: String) : DefaultApplicationResult()
}
| app/src/main/kotlin/batect/cli/options/OptionDefinition.kt | 1407021266 |
package com.applivery.data.response
import com.applivery.base.domain.model.UserProfile
import com.applivery.base.domain.model.UserType
import java.text.SimpleDateFormat
import java.util.Locale
fun UserEntity.toDomain(): UserProfile = UserProfile(
id = id.orEmpty(),
email = email,
firstName = firstName,
fullName = fullName,
lastName = lastName,
type = type?.toDomain(),
createdAt = createdAt?.let {
runCatching {
SimpleDateFormat(
ServerResponse.ApiDateFormat,
Locale.getDefault()
).parse(it)
}.getOrNull()
}
)
fun ApiUserType.toDomain(): UserType = when (this) {
ApiUserType.User -> UserType.User
ApiUserType.Employee -> UserType.Employee
}
| applivery-data/src/main/java/com/applivery/data/response/Mappers.kt | 3490762695 |
package taiwan.no1.app.ssfm.models.usecases
import io.reactivex.Observable
import taiwan.no1.app.ssfm.models.data.IDataStore
import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistTopAlbumEntity
import taiwan.no1.app.ssfm.models.usecases.GetArtistTopAlbumsUsecase.RequestValue
/**
* @author jieyi
* @since 10/11/17
*/
class GetArtistTopAlbumsUsecase(repository: IDataStore) : BaseUsecase<ArtistTopAlbumEntity, RequestValue>(repository) {
override fun fetchUsecase(): Observable<ArtistTopAlbumEntity> =
(parameters ?: RequestValue()).let { repository.getArtistTopAlbum(it.name) }
data class RequestValue(val name: String = "") : RequestValues
} | app/src/main/kotlin/taiwan/no1/app/ssfm/models/usecases/GetArtistTopAlbumsUsecase.kt | 2645446176 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.inspection.util
import java.util.IdentityHashMap
const val NO_ANCHOR_ID = 0
/**
* A map of anchors with a unique id generator.
*/
class AnchorMap {
private val anchorLookup = mutableMapOf<Int, Any>()
private val idLookup = IdentityHashMap<Any, Int>()
/**
* Return a unique id for the specified [anchor] instance.
*/
operator fun get(anchor: Any?): Int =
anchor?.let { idLookup.getOrPut(it) { generateUniqueId(it) } } ?: NO_ANCHOR_ID
/**
* Return the anchor associated with a given unique anchor [id].
*/
operator fun get(id: Int): Any? = anchorLookup[id]
private fun generateUniqueId(anchor: Any): Int {
var id = anchor.hashCode()
while (id == NO_ANCHOR_ID || anchorLookup.containsKey(id)) {
id++
}
anchorLookup[id] = anchor
return id
}
}
| compose/ui/ui-inspection/src/main/java/androidx/compose/ui/inspection/util/AnchorMap.kt | 3614174687 |
package org.elm.ide.intentions
import org.elm.lang.core.imports.ImportAdder.Import
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmFunctionDeclarationLeft
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.moduleName
import org.elm.lang.core.resolve.scope.ModuleScope
import org.elm.lang.core.types.*
abstract class TyFunctionGenerator(
protected val file: ElmFile,
protected val root: Ty
) {
data class GeneratedFunction(
val name: String,
val paramTy: Ty,
val paramName: String,
val body: String,
val qualifier: String
)
data class Ref(val module: String, val name: String)
fun TyUnion.toRef() = Ref(module, name)
fun AliasInfo.toRef() = Ref(module, name)
fun DeclarationInTy.toRef() = Ref(module, name)
/** All types and aliases referenced in the root ty */
protected val declarations by lazy { root.allDeclarations().toList() }
/** Additional encoder functions to generate */
protected val funcsByTy = mutableMapOf<Ty, GeneratedFunction>()
/** Cache of already existing callable expressions that aren't in [funcsByTy] */
private val callablesByTy = mutableMapOf<Ty, String>()
/** Unions that need their variants exposed. */
protected val unionsToExpose = mutableSetOf<Ref>()
/** The name of the module in the current file */
protected val moduleName by lazy { file.getModuleDecl()?.name ?: "" }
/** The name to use for the encoder function for each type (does not include the "encoder" prefix) */
// There might be multiple types with the same name in different modules, so add the module
// name the function for any type with a conflict that isn't defined in this module
protected val funcNames by lazy {
declarations.groupBy { it.name }
.map { (_, decls) ->
decls.map {
it.toRef() to when {
decls.size == 1 -> it.name
else -> it.module.replace(".", "") + it.name
}
}
}.flatten().toMap()
}
/** Qualified names of all imported modules */
private val importedModules: Set<String> by lazy {
file.findChildrenByClass(ElmImportClause::class.java).mapTo(mutableSetOf()) { it.referenceName }
}
/** Generate the code and imports for this function */
fun run(): Pair<String, List<Import>> = generateCode() to generateImports()
/** The code to insert for this function */
protected abstract fun generateCode(): String
/** The list of imports needed by generated code. */
protected open fun generateImports(): List<Import> {
val visibleTypes = ModuleScope.getVisibleTypes(file).all
.mapNotNullTo(mutableSetOf()) { it.name?.let { n -> Ref(it.moduleName, n) } }
// Hack in List since GlobalScope.getVisibleTypes can't return it
val visibleModules = importedModules + "List"
return declarations
.filter {
it.module != moduleName &&
(it.toRef() in unionsToExpose || it.module !in visibleModules && it.toRef() !in visibleTypes)
}
.map {
Import(
moduleName = it.module,
moduleAlias = null,
nameToBeExposed = if (it.isUnion) "${it.name}(..)" else ""
)
}
}
/** Get the module qualifier prefix to add to a name */
protected fun qualifierFor(ref: Ref): String {
return when (ref.module) {
moduleName -> ""
// We always fully qualify references to modules that we add imports for
!in importedModules -> "${ref.module}."
else -> ModuleScope.getQualifierForName(file, ref.module, ref.name) ?: ""
}
}
/** Prefix [name], defined in [module], with the necessary qualifier */
protected fun qual(module: String, name: String) = "${qualifierFor(Ref(module, name))}$name"
/** Return the callable for a user-supplied function to process [ty] if there is one */
protected fun existing(ty: Ty): String? {
if (ty in callablesByTy) return callablesByTy[ty]!!
ModuleScope.getReferencableValues(file).all
.filterIsInstance<ElmFunctionDeclarationLeft>()
.forEach {
val t = it.findTy()
if (t != null && isExistingFunction(ty, t)) {
val code = qual(it.moduleName, it.name)
callablesByTy[ty] = code
return code
}
}
return null
}
protected abstract fun isExistingFunction(needle: Ty, function: Ty): Boolean
}
| src/main/kotlin/org/elm/ide/intentions/TyFunctionGenerator.kt | 1928817108 |
package com.icytown.course.experimentfive.webapi.ui.issue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.icytown.course.experimentfive.webapi.R
import com.icytown.course.experimentfive.webapi.data.model.Issue
import com.icytown.course.experimentfive.webapi.databinding.IssueItemBinding
class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.BindingHolder>() {
var items: List<Issue> = ArrayList()
fun reset(list: List<Issue>) {
items = list
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder {
val binding = DataBindingUtil.inflate<IssueItemBinding>(
LayoutInflater.from(parent.context),
R.layout.issue_item,
parent,
false
)
val holder = BindingHolder(binding.root)
holder.binding = binding
return holder
}
override fun onBindViewHolder(holder: BindingHolder, position: Int) {
holder.binding.model = items[position]
holder.binding.executePendingBindings()
}
override fun getItemCount(): Int {
return items.size
}
class BindingHolder(view: View) : RecyclerView.ViewHolder(view) {
lateinit var binding: IssueItemBinding
}
}
| Homework/Mobile Phone Application Development/Lab5 WebAPI/app/src/main/java/com/icytown/course/experimentfive/webapi/ui/issue/RecyclerViewAdapter.kt | 4238679370 |
package ru.fantlab.android.data.dao.model
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize
data class ChildWork(
val authors: ArrayList<Author>,
val deep: Int,
val plus: Int?,
@SerializedName("publish_status") val publishStatus: String,
@SerializedName("val_midmark_by_weight") val rating: Float?,
@SerializedName("val_voters") val votersCount: Int?,
@SerializedName("val_responsecount") val responses: Int?,
@SerializedName("work_description") val description: String?,
@SerializedName("work_id") val id: Int?,
@SerializedName("work_lp") val hasLinguaProfile: Int?,
@SerializedName("work_name") val name: String,
@SerializedName("work_name_alt") val nameAlt: String,
@SerializedName("work_name_bonus") val nameBonus: String?,
@SerializedName("work_name_orig") val nameOrig: String,
@SerializedName("work_notes") val notes: String,
@SerializedName("work_notfinished") val notFinished: Int,
@SerializedName("work_parent") val parentId: Int,
@SerializedName("work_preparing") val preparing: Int,
@SerializedName("work_published") val published: Int,
@SerializedName("work_root_saga") val rootSagas: ArrayList<WorkRootSaga>,
@SerializedName("work_type") val type: String?,
@SerializedName("work_type_id") val typeId: Int,
@SerializedName("work_type_name") val typeName: String?,
@SerializedName("work_year") val year: Int?,
@SerializedName("work_year_of_write") val yearOfWrite: Int?
) : Parcelable {
@Keep
@Parcelize
data class Author(
val id: Int,
val name: String,
val type: String
) : Parcelable
} | app/src/main/kotlin/ru/fantlab/android/data/dao/model/ChildWork.kt | 1302410595 |
package builds.apiReferences.kotlinx.datetime
import builds.apiReferences.dependsOnDokkaPagesJson
import builds.apiReferences.templates.BuildApiReferenceSearchIndex
import jetbrains.buildServer.configs.kotlin.BuildType
object KotlinxDatetimeBuildSearchIndex: BuildType({
name = "Build search index for kotlinx-datetime"
templates(BuildApiReferenceSearchIndex)
params {
param("env.ALGOLIA_INDEX_NAME", "kotlinx-datetime")
param("env.API_REFERENCE_URL", "/api/kotlinx-datetime")
}
dependencies {
dependsOnDokkaPagesJson(KotlinxDatetimeBuildApiReference)
}
})
| .teamcity/builds/apiReferences/kotlinx/datetime/KotlinxDatetimeBuildSearchIndex.kt | 3113736243 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.reporting
import net.sf.dynamicreports.jasper.builder.export.JasperCsvExporterBuilder
import net.sf.dynamicreports.report.exception.DRException
import java.io.OutputStream
import java.util.Locale
import net.sf.dynamicreports.report.builder.DynamicReports.cmp
import net.sf.dynamicreports.report.builder.DynamicReports.export
/**
* @author MyCollab Ltd
* @since 5.4.7
*/
class CsvReportBuilder internal constructor(locale: Locale, fieldBuilder: RpFieldsBuilder, classType: Class<*>, parameters: Map<String, Any>) : AbstractReportBuilder(locale, fieldBuilder, classType, parameters) {
override fun initReport() {}
override fun setTitle(title: String) {
reportBuilder.title(cmp.horizontalList())
}
@Throws(DRException::class)
override fun toStream(outputStream: OutputStream) {
reportBuilder.ignorePageWidth()
reportBuilder.ignorePagination()
val csvExporter = export.csvExporter(outputStream)
reportBuilder.toCsv(csvExporter)
}
}
| mycollab-reporting/src/main/java/com/mycollab/reporting/CsvReportBuilder.kt | 4023463174 |
package org.ligi.scr
import android.content.Intent
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.text.method.LinkMovementMethod
import android.view.ViewGroup
import android.widget.FrameLayout
import info.metadude.java.library.halfnarp.model.GetTalksResponse
import kotlinx.android.synthetic.main.item_event.view.*
import org.joda.time.format.DateTimeFormat
import org.ligi.compat.HtmlCompat
import org.ligi.scr.model.Event
import org.ligi.scr.model.decorated.EventDecorator
class EventViewHolder(private val root: CardView) : RecyclerView.ViewHolder(root) {
fun apply(response: Event) {
val eventDecorator = EventDecorator(response)
itemView.titleTV.text = response.title + response.room
itemView.speaker.text = response.duration
itemView.abstractTV.text = eventDecorator.start.toString(DateTimeFormat.shortTime()) + " " + eventDecorator.end.toString(DateTimeFormat.shortTime()) + " " + response.abstractText
val main = 5 * eventDecorator.duration.standardMinutes
root.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, main.toInt())
root.requestLayout()
}
fun apply(response: GetTalksResponse, moveMethod: (Int, Int) -> Unit) {
itemView.titleTV.text = response.title
itemView.abstractTV.text = HtmlCompat.fromHtml(response.abstract)
itemView.abstractTV.movementMethod = LinkMovementMethod.getInstance()
itemView.speaker.text = response.speakers
itemView.yesButton.setOnClickListener {
moveMethod.invoke(1, adapterPosition)
}
itemView.noButton.setOnClickListener {
moveMethod.invoke(-1, adapterPosition)
}
itemView.shareView.setOnClickListener {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_SUBJECT, response.title)
intent.putExtra(Intent.EXTRA_TEXT, response.abstract)
intent.type = "text/plain"
root.context.startActivity(intent)
}
}
}
| android/src/main/java/org/ligi/scr/EventViewHolder.kt | 3846892087 |
package eu.kanade.tachiyomi.extension.en.manytoonme
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.multisrc.madara.Madara
@Nsfw
class ManyToonMe : Madara("ManyToon.me", "https://manytoon.me", "en") {
override fun getGenreList() = listOf(
Genre("Action", "action"),
Genre("Adult", "adult"),
Genre("Adventure", "adventure"),
Genre("Comedy", "comedy"),
Genre("Complete", "complete"),
Genre("Cooking", "cooking"),
Genre("Doujinshi", "doujinshi"),
Genre("Drama", "drama"),
Genre("Ecchi", "ecchi"),
Genre("Fanstasy", "fantasy"),
Genre("Gender bender", "gender-bender"),
Genre("Gossip", "gossip"),
Genre("Harem", "harem"),
Genre("Hentai", "hentai"),
Genre("Historical", "historical"),
Genre("Horror", "horror"),
Genre("Isekai", "isekai"),
Genre("Josei", "josei"),
Genre("Manga", "manga"),
Genre("Manga hentai", "manga-hentai"),
Genre("Manhua", "manhua"),
Genre("Manhwa", "manhwa"),
Genre("Martial arts", "martial-arts"),
Genre("Mature", "mature"),
Genre("Mecha", "mecha"),
Genre("Medical", "medical"),
Genre("Mystery", "mystery"),
Genre("One shot", "one-shot"),
Genre("Psychological", "psychological"),
Genre("Romance", "romance"),
Genre("School Life", "school-life"),
Genre("Sci-fi", "sci-fi"),
Genre("Seinen", "seinen"),
Genre("Shoujo", "shoujo"),
Genre("Shoujo ai", "shoujo-ai"),
Genre("Shounen", "shounen"),
Genre("Shounen ai", "shounen-ai"),
Genre("Slice of Life", "slice-of-life"),
Genre("Smut", "smut"),
Genre("Sports", "sports"),
Genre("Supernatural", "supernatural"),
Genre("Thriller", "thriller"),
Genre("Tragedy", "tragedy"),
Genre("Webtoon", "webtoon"),
Genre("Webtoons", "webtoons"),
Genre("Yaoi", "yaoi"),
Genre("Yuri", "yuri"),
)
}
| multisrc/overrides/madara/manytoonme/src/ManyToonMe.kt | 483786501 |
// Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.repository.infosource
import dk.etiktak.backend.model.infosource.InfoSourceDomain
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.stereotype.Repository
@Repository
interface InfoSourceDomainRepository : PagingAndSortingRepository<InfoSourceDomain, Long> {
fun findByUuid(uuid: String): InfoSourceDomain?
fun findByDomain(domain: String): InfoSourceDomain?
} | src/main/kotlin/dk/etiktak/backend/repository/infosource/InfoSourceDomainRepository.kt | 2902184099 |
package de.tum.`in`.tumcampusapp.component.ui.ticket.model
import de.tum.`in`.tumcampusapp.R
enum class EventType(val placeholderTextId: Int, val placeholderImageId: Int) {
ALL(R.string.no_events_found, R.drawable.popcorn_placeholder),
BOOKED(R.string.no_bookings_found, R.drawable.tickets_placeholder)
} | app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/model/EventType.kt | 3431618966 |
package org.jetbrains.kotlinx.jupyter.testkit.test
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.string.shouldContain
import org.jetbrains.kotlinx.jupyter.exceptions.ReplCompilerException
import org.jetbrains.kotlinx.jupyter.exceptions.ReplPreprocessingException
import org.jetbrains.kotlinx.jupyter.testkit.JupyterReplTestCase
import org.jetbrains.kotlinx.jupyter.testkit.ReplProvider
import org.junit.jupiter.api.Test
class JupyterReplWithResolverTest : JupyterReplTestCase(
ReplProvider.withDefaultClasspathResolution(
shouldResolve = { it != "lets-plot" },
shouldResolveToEmpty = { it == "multik" }
)
) {
@Test
fun dataframe() {
val dfHtml = execHtml(
"""
%use dataframe
val name by column<String>()
val height by column<Int>()
dataFrameOf(name, height)(
"Bill", 135,
"Mark", 160
)
""".trimIndent()
)
dfHtml shouldContain "Bill"
}
@Test
fun `lets-plot is not resolved as it is an exception`() {
val exception = shouldThrow<ReplPreprocessingException> {
exec("%use lets-plot")
}
exception.message shouldContain "Unknown library"
}
@Test
fun `multik resolves to empty`() {
exec("%use multik")
val exception = shouldThrow<ReplCompilerException> {
exec("import org.jetbrains.kotlinx.multik.api.*")
}
exception.message shouldContain "Unresolved reference: multik"
}
}
| jupyter-lib/test-kit/src/test/kotlin/org/jetbrains/kotlinx/jupyter/testkit/test/JupyterReplWithResolverTest.kt | 1847107723 |
package com.ifabijanovic.kotlinstatemachine
import io.reactivex.Observable
/**
* Created by Ivan Fabijanovic on 06/05/2017.
*/
fun <Element, State, Emit> scanAndMaybeEmit(
observable: Observable<Element>,
state: State,
accumulator: (Pair<State, Element>
) -> Pair<State, Emit?>): Observable<Emit> {
return observable
.scan(Pair<State, Emit?>(state, null), { stateEmitPair, element ->
accumulator(Pair(stateEmitPair.first, element))
})
.flatMap { stateEmitPair ->
stateEmitPair.second?.let { Observable.just(it) } ?: Observable.empty()
}
}
| app/src/main/java/com/ifabijanovic/kotlinstatemachine/ScanAndMaybeEmitOperator.kt | 1917838734 |
package de.westnordost.streetcomplete.quests
import de.westnordost.streetcomplete.data.quest.QuestGroup
interface IsShowingQuestDetails {
val questId: Long
val questGroup: QuestGroup
}
| app/src/main/java/de/westnordost/streetcomplete/quests/IsShowingQuestDetails.kt | 681813258 |
package com.themovielist.model.view
import android.os.Parcel
import android.os.Parcelable
import com.themovielist.model.MovieCastModel
import com.themovielist.model.MovieSizeModel
import com.themovielist.util.readNullableInt
import com.themovielist.util.writeNullableInt
data class MovieCastViewModel constructor(var movieId: Int? = null, var movieCastList: List<MovieCastModel>? = null, var profileSizeList: List<MovieSizeModel>? = null) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readNullableInt(),
parcel.createTypedArrayList(MovieCastModel),
parcel.createTypedArrayList(MovieSizeModel))
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeNullableInt(movieId)
parcel.writeTypedList(movieCastList)
parcel.writeTypedList(profileSizeList)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<MovieCastViewModel> {
override fun createFromParcel(parcel: Parcel): MovieCastViewModel {
return MovieCastViewModel(parcel)
}
override fun newArray(size: Int): Array<MovieCastViewModel?> {
return arrayOfNulls(size)
}
}
} | app/src/main/java/com/themovielist/model/view/MovieCastViewModel.kt | 2341020190 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.coretransforms.map.mapelements
import org.apache.beam.learning.katas.coretransforms.map.mapelements.Task.applyTransform
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.transforms.Create
import org.junit.Rule
import org.junit.Test
class TaskTest {
@get:Rule
@Transient
val testPipeline: TestPipeline = TestPipeline.create()
@Test
fun core_transforms_map_mapelements() {
val values = Create.of(10, 20, 30, 40, 50)
val numbers = testPipeline.apply(values)
val results = applyTransform(numbers)
PAssert.that(results).containsInAnyOrder(50, 100, 150, 200, 250)
testPipeline.run().waitUntilFinish()
}
} | learning/katas/kotlin/Core Transforms/Map/MapElements/test/org/apache/beam/learning/katas/coretransforms/map/mapelements/TaskTest.kt | 4089099888 |
/*
* Copyright (C) 2018 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.processor.query.http
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import uk.co.reecedunn.intellij.plugin.processor.query.MissingHostNameException
import uk.co.reecedunn.intellij.plugin.processor.query.connection.InstanceDetails
import java.io.Closeable
class HttpConnection(val settings: InstanceDetails) : Closeable {
init {
if (settings.hostname.isEmpty())
throw MissingHostNameException()
}
private var client: CloseableHttpClient? = null
private val httpClient: CloseableHttpClient
get() {
if (client == null) {
client = if (settings.username == null || settings.password == null) {
HttpClients.createDefault()
} else {
val credentials = BasicCredentialsProvider()
credentials.setCredentials(
AuthScope(settings.hostname, settings.databasePort),
UsernamePasswordCredentials(settings.username, settings.password)
)
HttpClients.custom().setDefaultCredentialsProvider(credentials).build()
}
}
return client!!
}
fun execute(request: HttpUriRequest): CloseableHttpResponse = httpClient.execute(request)
override fun close() {
if (client != null) {
client!!.close()
client = null
}
}
}
| src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/http/HttpConnection.kt | 602413076 |
package de.westnordost.streetcomplete.quests.note_discussion
data class NoteAnswer(val text:String, val imagePaths:List<String>?)
| app/src/main/java/de/westnordost/streetcomplete/quests/note_discussion/NoteAnswer.kt | 569491285 |
package org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model
import org.worldcubeassociation.tnoodle.server.serial.SingletonStringEncoder
data class AssignmentCode(val wcaString: String) {
val isStaff
get() = this.wcaString.startsWith(PREFIX_STAFF)
val isCompetitor
get() = this.wcaString == COMPETITOR
val isStaffJudge
get() = this.wcaString == STAFF_JUDGE
val isStaffScrambler
get() = this.wcaString == STAFF_SCRAMBLER
val isStaffRunner
get() = this.wcaString == STAFF_RUNNER
val isStaffDataEntry
get() = this.wcaString == STAFF_DATAENTRY
val isStaffAnnouncer
get() = this.wcaString == STAFF_ANNOUNCER
companion object : SingletonStringEncoder<AssignmentCode>("AssignmentCode") {
const val PREFIX_STAFF = "staff"
const val COMPETITOR = "competitor"
const val STAFF_JUDGE = "$PREFIX_STAFF-judge"
const val STAFF_SCRAMBLER = "$PREFIX_STAFF-scrambler"
const val STAFF_RUNNER = "$PREFIX_STAFF-runner"
const val STAFF_DATAENTRY = "$PREFIX_STAFF-dataentry"
const val STAFF_ANNOUNCER = "$PREFIX_STAFF-announcer"
override fun encodeInstance(instance: AssignmentCode) = instance.wcaString
override fun makeInstance(deserialized: String) = AssignmentCode(deserialized)
}
}
| webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/wcif/model/AssignmentCode.kt | 412432562 |
/*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jetbrains.plugins.ideavim.action.motion.updown
import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.helper.StringHelper.parseKeys
import org.jetbrains.plugins.ideavim.VimTestCase
/**
* @author Alex Plate
*/
class MotionPercentOrMatchActionTest : VimTestCase() {
fun `test percent match simple`() {
typeTextInFile(parseKeys("%"),
"foo(b${c}ar)\n")
assertOffset(3)
}
fun `test percent match multi line`() {
typeTextInFile(parseKeys("%"),
"""foo(bar,
|baz,
|${c}quux)
""".trimMargin())
assertOffset(3)
}
fun `test percent visual mode match multi line end of line`() {
typeTextInFile(parseKeys("v$%"),
"""${c}foo(
|bar)""".trimMargin())
assertOffset(8)
}
fun `test percent visual mode match from start multi line end of line`() {
typeTextInFile(parseKeys("v$%"),
"""$c(
|bar)""".trimMargin())
assertOffset(5)
}
fun `test percent visual mode find brackets on the end of line`() {
typeTextInFile(parseKeys("v$%"),
"""foo(${c}bar)""")
assertOffset(3)
}
fun `test percent twice visual mode find brackets on the end of line`() {
typeTextInFile(parseKeys("v$%%"),
"""foo(${c}bar)""")
assertOffset(7)
}
fun `test percent match parens in string`() {
typeTextInFile(parseKeys("%"),
"""foo(bar, "foo(bar", ${c}baz)
""")
assertOffset(3)
}
fun `test percent match xml comment start`() {
configureByXmlText("$c<!-- foo -->")
typeText(parseKeys("%"))
myFixture.checkResult("<!-- foo --$c>")
}
fun `test percent doesnt match partial xml comment`() {
configureByXmlText("<!$c-- ")
typeText(parseKeys("%"))
myFixture.checkResult("<!$c-- ")
}
fun `test percent match xml comment end`() {
configureByXmlText("<!-- foo --$c>")
typeText(parseKeys("%"))
myFixture.checkResult("$c<!-- foo -->")
}
fun `test percent match java comment start`() {
configureByJavaText("/$c* foo */")
typeText(parseKeys("%"))
myFixture.checkResult("/* foo *$c/")
}
fun `test percent doesnt match partial java comment`() {
configureByJavaText("$c/* ")
typeText(parseKeys("%"))
myFixture.checkResult("$c/* ")
}
fun `test percent match java comment end`() {
configureByJavaText("/* foo $c*/")
typeText(parseKeys("%"))
myFixture.checkResult("$c/* foo */")
}
fun `test percent match java doc comment start`() {
configureByJavaText("/*$c* foo */")
typeText(parseKeys("%"))
myFixture.checkResult("/** foo *$c/")
}
fun `test percent match java doc comment end`() {
configureByJavaText("/** foo *$c/")
typeText(parseKeys("%"))
myFixture.checkResult("$c/** foo */")
}
fun `test percent doesnt match after comment start`() {
configureByJavaText("/*$c foo */")
typeText(parseKeys("%"))
myFixture.checkResult("/*$c foo */")
}
fun `test percent doesnt match before comment end`() {
configureByJavaText("/* foo $c */")
typeText(parseKeys("%"))
myFixture.checkResult("/* foo $c */")
}
fun `test motion with quote on the way`() {
doTest(parseKeys("%"), """
for (; c!= cj;c = it.next()) ${c}{
if (dsa) {
if (c == '\\') {
dsadsakkk
}
}
}
""".trimIndent(),
"""
for (; c!= cj;c = it.next()) {
if (dsa) {
if (c == '\\') {
dsadsakkk
}
}
${c}}
""".trimIndent(), CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion outside text`() {
doTest(parseKeys("%"), """
(
""${'"'}
""${'"'} + ${c}title("Display")
""${'"'}
""${'"'}
)
""".trimIndent(),
"""
(
""${'"'}
""${'"'} + title("Display"${c})
""${'"'}
""${'"'}
)
""".trimIndent(), CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text`() {
doTest(parseKeys("%"), """ "I found ${c}it in a (legendary) land" """,
""" "I found it in a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text with quotes`() {
doTest(parseKeys("%"), """ "I found ${c}it in \"a (legendary) land" """,
""" "I found it in \"a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text with quotes start before quote`() {
doTest(parseKeys("%"), """ ${c} "I found it in \"a (legendary) land" """,
""" "I found it in \"a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
fun `test motion in text with quotes and double escape`() {
doTest(parseKeys("%"), """ "I found ${c}it in \\\"a (legendary) land" """,
""" "I found it in \\\"a (legendary${c}) land" """, CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
}
} | test/org/jetbrains/plugins/ideavim/action/motion/updown/MotionPercentOrMatchActionTest.kt | 2551610810 |
package siosio.searcher
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.completion.impl.*
import com.intellij.codeInsight.lookup.*
import siosio.*
import java.awt.SystemColor.*
class DefaultSearcher(override val dependencyText: DependencyText) : CentralSearcher {
override fun find(resultSet: CompletionResultSet) {
val result = Client.get("https://search.maven.org/solrsearch/select?q=${dependencyText.text}&rows=100&wt=json")
resultSet.withRelevanceSorter(
CompletionSorter.emptySorter().weigh(PreferStartMatching())
).addAllElements(ID_PATTERN.findAll(result)
.mapNotNull {
it.groups[1]?.value
}
.map {
LookupElementBuilder.create(it)
}
.toList()
)
}
companion object {
private val ID_PATTERN = Regex("\\{\"id\":\"([^\"]+)\"")
}
} | src/main/java/siosio/searcher/DefaultSearcher.kt | 3885678647 |
package exnihilocreatio.api.registries
import exnihilocreatio.registries.types.FluidItemFluid
import exnihilocreatio.util.StackInfo
import net.minecraft.item.ItemStack
import net.minecraftforge.fluids.Fluid
interface IFluidItemFluidRegistry : IRegistryList<FluidItemFluid> {
fun register(inputFluid: String, reactant: StackInfo, outputFluid: String)
fun register(inputFluid: Fluid, reactant: StackInfo, outputFluid: Fluid)
fun getFLuidForTransformation(fluid: Fluid, stack: ItemStack): String?
}
| src/main/java/exnihilocreatio/api/registries/IFluidItemFluidRegistry.kt | 3221021988 |
/*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.koin.core.error
class ClosedScopeException(msg : String) : Exception(msg) | core/koin-core/src/commonMain/kotlin/org/koin/core/error/ClosedScopeException.kt | 1177131371 |
package org.stepic.droid.code.highlight
import org.stepic.droid.code.highlight.prettify.PrettifyParser
import org.stepic.droid.concurrency.MainHandler
import org.stepic.droid.di.AppSingleton
import java.util.concurrent.ThreadPoolExecutor
import javax.inject.Inject
@AppSingleton
class ParserContainer
@Inject
constructor(threadPoolExecutor: ThreadPoolExecutor,
mainHandler: MainHandler) {
var prettifyParser: PrettifyParser? = null
private set
init {
threadPoolExecutor.execute {
val parser = PrettifyParser()
mainHandler.post {
prettifyParser = parser
}
}
}
}
| app/src/main/java/org/stepic/droid/code/highlight/ParserContainer.kt | 1774101187 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
@ExportTypeInfo("theStringTypeInfo")
public final class String : Comparable<String>, CharSequence {
public companion object {
}
@SymbolName("Kotlin_String_hashCode")
external public override fun hashCode(): Int
public operator fun plus(other: Any?): String {
return plusImpl(other.toString())
}
override public fun toString(): String {
return this
}
public override val length: Int
get() = getStringLength()
@SymbolName("Kotlin_String_get")
external override public fun get(index: Int): Char
@SymbolName("Kotlin_String_subSequence")
external override public fun subSequence(startIndex: Int, endIndex: Int): CharSequence
@SymbolName("Kotlin_String_compareTo")
override external public fun compareTo(other: String): Int
@SymbolName("Kotlin_String_getStringLength")
external private fun getStringLength(): Int
@SymbolName("Kotlin_String_plusImpl")
external private fun plusImpl(other: Any): String
@SymbolName("Kotlin_String_equals")
external public override fun equals(other: Any?): Boolean
}
// TODO: in big Kotlin this operations are in kotlin.kotlin_builtins.
private val kNullString = "null"
public operator fun kotlin.String?.plus(other: kotlin.Any?): kotlin.String =
(this?.toString() ?: kNullString).plus(other?.toString() ?: kNullString)
public fun Any?.toString() = this?.toString() ?: kNullString | runtime/src/main/kotlin/kotlin/String.kt | 1124314345 |
package exnihilocreatio.json
import com.google.gson.*
import exnihilocreatio.util.ItemInfo
import exnihilocreatio.util.LogUtil
import net.minecraft.item.Item
import net.minecraft.nbt.JsonToNBT
import net.minecraft.nbt.NBTException
import net.minecraft.nbt.NBTTagCompound
import java.lang.reflect.Type
object CustomItemInfoJson : JsonDeserializer<ItemInfo>, JsonSerializer<ItemInfo> {
override fun serialize(src: ItemInfo, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
val nbt = src.nbt
if (nbt == null || nbt.isEmpty)
return JsonPrimitive(src.item.registryName!!.toString() + ":" + src.meta)
return JsonObject().apply {
add("name", context.serialize(src.item.registryName!!.toString()))
add("meta", context.serialize(src.meta))
add("nbt", context.serialize(src.nbt.toString()))
}
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ItemInfo {
if (json.isJsonPrimitive && json.asJsonPrimitive.isString) {
val name = json.asString
return ItemInfo(name)
} else {
val helper = JsonHelper(json)
val name = helper.getString("name")
val meta = helper.getNullableInteger("meta", 0)
val item = Item.getByNameOrId(name)
var nbt: NBTTagCompound? = null
if (json.asJsonObject.has("nbt")) {
try {
nbt = JsonToNBT.getTagFromJson(json.asJsonObject.get("nbt").asString)
} catch (e: NBTException) {
LogUtil.error("Could not convert JSON to NBT: " + json.asJsonObject.get("nbt").asString, e)
e.printStackTrace()
}
}
if (item == null) {
LogUtil.error("Error parsing JSON: Invalid Item: $json")
LogUtil.error("This may result in crashing or other undefined behavior")
return ItemInfo.EMPTY
}
return ItemInfo(item, meta, nbt)
}
}
}
| src/main/java/exnihilocreatio/json/CustomItemInfoJson.kt | 3362886234 |
/*
* 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 com.example.macrobenchmark.target.util
import android.content.Context
import android.util.TypedValue
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
const val TAG = "Perf Sample"
val KEY_USER = stringPreferencesKey("user")
val KEY_PASSWORD = stringPreferencesKey("password")
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
fun Int.dp(context: Context): Float =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this.toFloat(),
context.resources.displayMetrics
)
| MacrobenchmarkSample/app/src/main/java/com/example/macrobenchmark/target/util/Utils.kt | 2481699025 |
package com.vmenon.mpo.login.framework.di
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class LoginFrameworkScope | login_framework/src/main/java/com/vmenon/mpo/login/framework/di/LoginFrameworkScope.kt | 280493180 |
package org.walleth.security
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
fun isDappNodeReachable() = try {
val sockaddr = InetSocketAddress("172.33.1.9", 80)
val sock = Socket()
val timeoutMs = 2000 // 2 seconds
sock.connect(sockaddr, timeoutMs)
true
} catch (e: IOException) {
false
} | app/src/main/java/org/walleth/security/DappNodeUtil.kt | 2954643448 |
package com.vmenon.mpo.login.presentation.fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.vmenon.mpo.common.framework.livedata.observeUnhandled
import com.vmenon.mpo.login.presentation.databinding.FragmentLoginBinding
import com.vmenon.mpo.login.presentation.di.dagger.toLoginComponent
import com.vmenon.mpo.login.presentation.di.dagger.LoginComponent
import com.vmenon.mpo.login.presentation.model.LoadingState
import com.vmenon.mpo.login.presentation.model.LoggedInState
import com.vmenon.mpo.login.presentation.viewmodel.LoginViewModel
import com.vmenon.mpo.navigation.domain.login.LoginNavigationLocation
import com.vmenon.mpo.navigation.domain.NavigationOrigin
import com.vmenon.mpo.navigation.domain.NoNavigationParams
import com.vmenon.mpo.view.BaseViewBindingFragment
import com.vmenon.mpo.view.LoadingStateHelper
import com.vmenon.mpo.view.R
import com.vmenon.mpo.view.activity.BaseActivity
class LoginFragment : BaseViewBindingFragment<LoginComponent, FragmentLoginBinding>(),
NavigationOrigin<NoNavigationParams> by NavigationOrigin.from(LoginNavigationLocation) {
private val viewModel: LoginViewModel by viewModel()
override fun bind(inflater: LayoutInflater, container: ViewGroup?) =
FragmentLoginBinding.inflate(inflater, container, false)
override fun setupComponent(context: Context): LoginComponent = context.toLoginComponent()
override fun inject(component: LoginComponent) {
component.inject(this)
component.inject(viewModel)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val activity = (requireActivity() as BaseActivity<*>)
val loadingStateHelper = LoadingStateHelper.overlayContent(activity.requireLoadingView())
navigationController.setupWith(
this,
binding.toolbar,
drawerLayout(),
navigationView()
)
viewModel.loginState().observeUnhandled(viewLifecycleOwner, { state ->
when (state) {
LoadingState -> {
loadingStateHelper.showLoadingState()
}
is LoggedInState -> {
loadingStateHelper.showContentState()
if (state.promptToEnrollInBiometrics) {
promptToSetupBiometrics()
}
}
else -> {
loadingStateHelper.showContentState()
}
}
binding.state = state
})
binding.registrationValid = viewModel.registrationValid()
binding.registration = viewModel.registration
binding.lifecycleOwner = viewLifecycleOwner
binding.loginForm.registerLink.setOnClickListener {
viewModel.registerClicked()
}
binding.loginForm.loginLink.setOnClickListener {
viewModel.loginClicked(this)
}
binding.loginForm.useBiometrics.setOnClickListener {
viewModel.loginWithBiometrics(this)
}
binding.registerForm.registerUser.setOnClickListener {
viewModel.performRegistration(this)
}
binding.accountView.logoutLink.setOnClickListener {
viewModel.logoutClicked(this)
}
}
private fun promptToSetupBiometrics() {
val builder = AlertDialog.Builder(requireContext())
builder.apply {
setPositiveButton(getString(R.string.yes)) { _, _ ->
viewModel.userWantsToEnrollInBiometrics(this@LoginFragment)
}
setNegativeButton(R.string.no) { _, _ ->
viewModel.userDoesNotWantBiometrics()
}
setTitle(getString(com.vmenon.mpo.login.presentation.R.string.use_biometrics))
setMessage(getString(com.vmenon.mpo.login.presentation.R.string.use_biometrics_for_login))
}
builder.create().show()
}
} | login_presentation/src/main/java/com/vmenon/mpo/login/presentation/fragment/LoginFragment.kt | 1308862130 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.divinespear.plugin.test.helper
import io.github.divinespear.plugin.test.FunctionalSpec
import io.kotest.matchers.and
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.contain
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome
internal fun FunctionalSpec.runEclipseTask(script: String, resultCallback: (BuildResult) -> Unit) {
buildFile.appendText(script);
val result = runGenerateSchemaTask()
result.task(":generateSchema") should {
it?.outcome shouldBe TaskOutcome.SUCCESS
}
resultFileText("build/generated-schema/h2-create.sql") should
(contain("CREATE TABLE KEY_VALUE_STORE") and contain("CREATE TABLE MANY_COLUMN_TABLE"))
resultFileText("build/generated-schema/h2-drop.sql") should
(contain("DROP TABLE KEY_VALUE_STORE") and contain("DROP TABLE MANY_COLUMN_TABLE"))
resultCallback(result)
}
| src/functionalTest/kotlin/io/github/divinespear/plugin/test/helper/eclipselink.kt | 3456652556 |
/*
* Copyright (C) 2020 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.people
import android.net.Uri
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
/**
* Common interface between [MainActivity] and [BubbleActivity].
*/
interface NavigationController {
fun openChat(id: Long, prepopulateText: String?)
fun openPhoto(photo: Uri)
/**
* Updates the appearance and functionality of the app bar.
*
* @param showContact Whether to show contact information instead the screen title.
* @param hidden Whether to hide the app bar.
* @param body Provide this function to update the content of the app bar.
*/
fun updateAppBar(
showContact: Boolean = true,
hidden: Boolean = false,
body: (name: TextView, icon: ImageView) -> Unit = { _, _ -> }
)
}
fun Fragment.getNavigationController() = requireActivity() as NavigationController
| app/src/main/java/com/example/android/people/NavigationController.kt | 2740677190 |
package com.dss.sdatabase.model
import java.lang.reflect.Field
/**
* Created by gustavo.vieira on 04/05/2015.
*/
class BDInsert {
var field: Field? = null
var fieldName = String()
var fieldValue = Any()
constructor(field: Field, fieldName: String, fieldValue: Any) {
this.field = field
this.fieldName = fieldName
this.fieldValue = fieldValue
}
constructor()
}
| library/src/main/java/com/dss/sdatabase/model/BDInsert.kt | 4294222328 |
package com.apollographql.apollo3.network.http
import platform.Foundation.NSURL
import platform.Foundation.NSURLComponents
import platform.Foundation.NSURLQueryItem
actual fun buildUrl(baseUrl: String, queryParameters: Map<String, String>): String {
val urlComponents = NSURLComponents(uRL = NSURL(string = baseUrl), resolvingAgainstBaseURL = false)
urlComponents.queryItems = queryParameters.map {
NSURLQueryItem(name = it.key, value = it.value)
}
return urlComponents.URL!!.absoluteString!!
}
| apollo-runtime-kotlin/src/appleMain/kotlin/com/apollographql/apollo3/network/http/HttpUrlBuilder.kt | 2737916751 |
// Copyright 2000-2017 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.index
import com.google.common.hash.HashCode
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.stubs.FileContentHashing
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.io.PersistentHashMap
import junit.framework.TestCase
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* @author traff
*/
abstract class IndexGenerator<Value>(private val indexStorageFilePath: String) {
companion object {
val CHECK_HASH_COLLISIONS: Boolean = System.getenv("INDEX_GENERATOR_CHECK_HASH_COLLISIONS")?.toBoolean() ?: false
}
open val fileFilter
get() = VirtualFileFilter { f -> !f.isDirectory }
data class Stats(val indexed: AtomicInteger, val skipped: AtomicInteger) {
constructor() : this(AtomicInteger(0), AtomicInteger(0))
}
protected fun buildIndexForRoots(roots: List<VirtualFile>) {
val hashing = FileContentHashing()
val storage = createStorage(indexStorageFilePath)
println("Writing indices to ${storage.baseFile.absolutePath}")
try {
val map = HashMap<HashCode, Pair<String, Value>>()
for (file in roots) {
println("Processing files in root ${file.path}")
val stats = Stats()
VfsUtilCore.visitChildrenRecursively(file,
object : VirtualFileVisitor<Boolean>() {
override fun visitFile(file: VirtualFile): Boolean {
return indexFile(file, hashing, map, storage, stats)
}
})
println("${stats.indexed.get()} entries written, ${stats.skipped.get()} skipped")
}
}
finally {
storage.close()
}
}
private fun indexFile(file: VirtualFile,
hashing: FileContentHashing,
map: HashMap<HashCode, Pair<String, Value>>,
storage: PersistentHashMap<HashCode, Value>,
stats: Stats): Boolean {
try {
if (fileFilter.accept(file)) {
val fileContent = FileContentImpl(
file, file.contentsToByteArray())
val hashCode = hashing.hashString(fileContent)
val value = getIndexValue(fileContent)
if (value != null) {
val item = map[hashCode]
if (item == null) {
storage.put(hashCode, value)
stats.indexed.incrementAndGet()
if (CHECK_HASH_COLLISIONS) {
map.put(hashCode,
Pair(fileContent.contentAsText.toString(), value))
}
}
else {
TestCase.assertEquals(item.first,
fileContent.contentAsText.toString())
TestCase.assertTrue(value == item.second)
}
}
else {
stats.skipped.incrementAndGet()
}
}
}
catch (e: NoSuchElementException) {
return false
}
return true
}
protected abstract fun getIndexValue(fileContent: FileContentImpl): Value?
protected abstract fun createStorage(stubsStorageFilePath: String): PersistentHashMap<HashCode, Value>
} | tools/index-tools/src/org/jetbrains/index/IndexGenerator.kt | 482310740 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag
import android.content.Context
import android.content.Intent
import android.os.Bundle
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.createNewEntry
import io.github.feelfreelinux.wykopmobilny.utils.api.getTag
import kotlinx.android.synthetic.main.activity_feed.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
fun Context.launchTagActivity(tag : String) {
val intent = Intent(this, TagActivity::class.java)
intent.putExtra(TagActivity.EXTRA_TAG, tag)
startActivity(intent)
}
class TagActivity : BaseActivity(), TagView {
private lateinit var entryTag : String
lateinit var tagDataFragment : DataFragment<PagedDataModel<List<Entry>>>
@Inject lateinit var presenter : TagPresenter
companion object {
val EXTRA_TAG = "EXTRA_TAG"
val EXTRA_TAG_DATA_FRAGMENT = "DATA_FRAGMENT_#"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feed)
setSupportActionBar(toolbar)
entryTag = intent.data?.getTag() ?: intent.getStringExtra(EXTRA_TAG)
tagDataFragment = supportFragmentManager.getDataFragmentInstance(EXTRA_TAG_DATA_FRAGMENT + entryTag)
tagDataFragment.data?.apply {
presenter.page = page
}
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
title = "#" + entryTag
}
WykopApp.uiInjector.inject(this)
presenter.tag = entryTag
presenter.subscribe(this)
feedRecyclerView.apply {
presenter = [email protected]
initAdapter(tagDataFragment.data?.model)
onFabClickedListener = {
context.createNewEntry(null)
}
}
setSupportActionBar(toolbar)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
tagDataFragment.data = PagedDataModel(presenter.page, feedRecyclerView.entries)
}
override fun onPause() {
super.onPause()
if (isFinishing) supportFragmentManager.removeDataFragment(tagDataFragment)
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
override fun addDataToAdapter(entryList: List<Entry>, shouldClearAdapter: Boolean) =
feedRecyclerView.addDataToAdapter(entryList, shouldClearAdapter)
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/feed/tag/TagActivity.kt | 1787571648 |
package venus.simulator
import kotlin.test.Test
import kotlin.test.assertEquals
import venus.assembler.Assembler
import venus.linker.Linker
import venus.riscv.MemorySegments
class StaticDataTest {
@Test fun easyManualLoad() {
val (prog, _) = Assembler.assemble("""
.data
.byte 1 2 3 4
.text
nop
""")
val linked = Linker.link(listOf(prog))
val sim = Simulator(linked)
assertEquals(1, sim.loadByte(MemorySegments.STATIC_BEGIN))
assertEquals(2, sim.loadByte(MemorySegments.STATIC_BEGIN + 1))
assertEquals(3, sim.loadByte(MemorySegments.STATIC_BEGIN + 2))
assertEquals(4, sim.loadByte(MemorySegments.STATIC_BEGIN + 3))
}
@Test fun asciizNulTerminated() {
val (prog, _) = Assembler.assemble("""
.data
.asciiz "a"
.asciiz "b"
""")
val linked = Linker.link(listOf(prog))
val sim = Simulator(linked)
val offset = MemorySegments.STATIC_BEGIN
assertEquals('a'.toInt(), sim.loadByte(offset))
assertEquals(0, sim.loadByte(offset + 1))
assertEquals('b'.toInt(), sim.loadByte(offset + 2))
assertEquals(0, sim.loadByte(offset + 3))
}
@Test fun linkedStaticBytes() {
val (prog1, _) = Assembler.assemble("""
.data
.byte 1
""")
val (prog2, _) = Assembler.assemble("""
.data
.byte 2
""")
val linked = Linker.link(listOf(prog1, prog2))
val sim = Simulator(linked)
val offset = MemorySegments.STATIC_BEGIN
assertEquals(1, sim.loadByte(offset))
assertEquals(2, sim.loadByte(offset + 1))
}
@Test fun wordManualLoad() {
val (prog, _) = Assembler.assemble("""
.data
.word -21231234
.text
nop
""")
val linked = Linker.link(listOf(prog))
val sim = Simulator(linked)
assertEquals(-21231234, sim.loadWord(MemorySegments.STATIC_BEGIN))
}
}
| src/test/kotlin/simulator/StaticDataTest.kt | 3019706753 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.models.dataclass.TagMeta
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.createNewEntry
import io.github.feelfreelinux.wykopmobilny.utils.api.getTag
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.linkparser.TagLinkParser
import kotlinx.android.synthetic.main.activity_feed.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
fun Context.getTagActivityIntent(tag : String) : Intent {
val intent = Intent(this, TagActivity::class.java)
intent.putExtra(TagActivity.EXTRA_TAG, tag)
return intent
}
class TagActivity : BaseActivity(), TagView {
private lateinit var entryTag : String
lateinit var tagDataFragment : DataFragment<PagedDataModel<List<Entry>>>
@Inject lateinit var userManager : UserManagerApi
@Inject lateinit var presenter : TagPresenter
private var tagMeta : TagMeta? = null
companion object {
val EXTRA_TAG = "EXTRA_TAG"
val EXTRA_TAG_DATA_FRAGMENT = "DATA_FRAGMENT_#"
fun createIntent(context : Context, tag : String): Intent {
val intent = Intent(context, TagActivity::class.java)
intent.putExtra(TagActivity.EXTRA_TAG, tag)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feed)
setSupportActionBar(toolbar)
WykopApp.uiInjector.inject(this)
entryTag = intent.getStringExtra(EXTRA_TAG)?: TagLinkParser.getTag(intent.data.toString())
tagDataFragment = supportFragmentManager.getDataFragmentInstance(EXTRA_TAG_DATA_FRAGMENT + entryTag)
tagDataFragment.data?.apply {
presenter.page = page
}
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
title = "#" + entryTag
}
presenter.tag = entryTag
presenter.subscribe(this)
feedRecyclerView.apply {
presenter = [email protected]
fab = [email protected]
initAdapter(tagDataFragment.data?.model)
onFabClickedListener = {
context.createNewEntry(null)
}
}
setSupportActionBar(toolbar)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.tag_menu, menu)
if (userManager.isUserAuthorized()) {
tagMeta?.apply {
menu.apply {
if (isObserved) {
findItem(R.id.action_unobserve).isVisible = true
} else if (!isBlocked) {
findItem(R.id.action_observe).isVisible = true
findItem(R.id.action_block).isVisible = true
} else if (isBlocked) {
findItem(R.id.action_unblock).isVisible = true
}
}
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_observe -> presenter.observeTag()
R.id.action_unobserve -> presenter.unobserveTag()
R.id.action_block -> presenter.blockTag()
R.id.action_unblock -> presenter.unblockTag()
}
return super.onOptionsItemSelected(item)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
tagDataFragment.data = PagedDataModel(presenter.page, feedRecyclerView.entries)
}
override fun setMeta(tagMeta: TagMeta) {
this.tagMeta = tagMeta
invalidateOptionsMenu()
}
override fun onPause() {
super.onPause()
if (isFinishing) supportFragmentManager.removeDataFragment(tagDataFragment)
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
override fun addDataToAdapter(entryList: List<Entry>, shouldClearAdapter: Boolean) =
feedRecyclerView.addDataToAdapter(entryList, shouldClearAdapter)
override fun disableLoading() {
feedRecyclerView.disableLoading()
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mikroblog/feed/tag/TagActivity.kt | 1137116606 |
package com.prateekj.snooper.networksnooper.presenter
import com.prateekj.snooper.infra.BackgroundTask
import com.prateekj.snooper.infra.BackgroundTaskExecutor
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.ERROR
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.HEADERS
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.REQUEST
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.RESPONSE
import com.prateekj.snooper.networksnooper.helper.DataCopyHelper
import com.prateekj.snooper.networksnooper.model.HttpCallRecord
import com.prateekj.snooper.networksnooper.views.HttpCallView
import com.prateekj.snooper.utils.FileUtil
import com.prateekj.snooper.utils.TestUtils.getDate
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Before
import org.junit.Test
class HttpCallPresenterTest {
private lateinit var view: HttpCallView
private lateinit var httpCall: HttpCallRecord
private lateinit var dataCopyHelper: DataCopyHelper
private lateinit var fileUtil: FileUtil
private lateinit var backgroundTaskExecutor: BackgroundTaskExecutor
private lateinit var httpCallPresenter: HttpCallPresenter
@Before
@Throws(Exception::class)
fun setUp() {
view = mockk(relaxed = true)
httpCall = mockk(relaxed = true)
dataCopyHelper = mockk(relaxed = true)
fileUtil = mockk(relaxed = true)
backgroundTaskExecutor = mockk(relaxed = true)
httpCallPresenter = HttpCallPresenter(
dataCopyHelper,
httpCall,
view,
fileUtil,
backgroundTaskExecutor
)
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheResponseData() {
val responseBody = "response body"
every { dataCopyHelper.getResponseDataForCopy() } returns responseBody
httpCallPresenter.copyHttpCallBody(RESPONSE)
verify { view.copyToClipboard(responseBody) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheRequestData() {
val formatRequestBody = "format Request body"
every { dataCopyHelper.getRequestDataForCopy() } returns formatRequestBody
httpCallPresenter.copyHttpCallBody(REQUEST)
verify { view.copyToClipboard(formatRequestBody) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheHeaders() {
val headers = "headers"
every { dataCopyHelper.getHeadersForCopy() } returns headers
httpCallPresenter.copyHttpCallBody(HEADERS)
verify { view.copyToClipboard(headers) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheError() {
val error = "error"
every { dataCopyHelper.getErrorsForCopy() } returns error
httpCallPresenter.copyHttpCallBody(ERROR)
verify { view.copyToClipboard(error) }
}
@Test
@Throws(Exception::class)
fun shouldAskViewToCopyTheEmptyStringIfErrorNotCaptured() {
every { dataCopyHelper.getErrorsForCopy() } returns null
httpCallPresenter.copyHttpCallBody(ERROR)
verify { view.copyToClipboard("") }
}
@Test
@Throws(Exception::class)
fun shouldShareRequestResponseData() {
every { httpCall.date } returns getDate(2017, 4, 12, 1, 2, 3)
val stringBuilder = StringBuilder()
every { dataCopyHelper.getHttpCallData() } returns stringBuilder
every {
fileUtil.createLogFile(
eq(stringBuilder),
eq("2017_05_12_01_02_03.txt")
)
} returns "filePath"
resolveBackgroundTask()
httpCallPresenter.shareHttpCallBody()
verify { view.shareData("filePath") }
}
@Test
@Throws(Exception::class)
fun shouldNotShareDataIfFileNotCreated() {
every { httpCall.date } returns getDate(2017, 4, 12, 1, 2, 3)
val stringBuilder = StringBuilder()
every { dataCopyHelper.getHttpCallData() } returns stringBuilder
every {
fileUtil.createLogFile(
eq(stringBuilder),
eq("2017_05_12_01_02_03.txt")
)
} returns ""
resolveBackgroundTask()
httpCallPresenter.shareHttpCallBody()
verify(exactly = 0) { view.shareData("filePath") }
}
@Test
@Throws(Exception::class)
fun shouldShowShareNotAvailableDialogWhenPermissionIsDenied() {
httpCallPresenter.onPermissionDenied()
verify { view.showMessageShareNotAvailable() }
}
private fun resolveBackgroundTask() {
every { backgroundTaskExecutor.execute(any<BackgroundTask<String>>()) } answers {
val backgroundTask = this.firstArg<BackgroundTask<String>>()
backgroundTask.onResult(backgroundTask.onExecute())
}
}
} | Snooper/src/test/java/com/prateekj/snooper/networksnooper/presenter/HttpCallPresenterTest.kt | 2404795311 |
package radar.kudos.api.service.kudos
import radar.kudos.api.service.twitter.TwitterClient
import radar.kudos.domain.model.persistent.entities.pojo.Kudos
import radar.kudos.repositories.api.KudosRepository
import org.springframework.stereotype.Service
@Service
class KudosService(val kudosRepository: KudosRepository, val twitterClient: TwitterClient) {
fun getRandom() =
kudosRepository.getRandom()?.let { enrich(it) } ?: throw IllegalArgumentException("No random kudos available.")
fun getByScreenName(id: String)
= kudosRepository.getByTwitterId(id)?.let { enrich(it) } ?: throw IllegalArgumentException("No kudos for id $id")
/**
* Add missing biography details
*/
private fun enrich(kudos: Kudos) =
kudos.copy(communityMember = twitterClient.load(kudos.communityMember.screenName))
}
| backend/src/main/java/radar/kudos/api/service/kudos/KudosService.kt | 1676490089 |
package org.sirix.rest.crud
import io.vertx.core.http.HttpHeaders
import io.vertx.ext.web.Route
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.withContext
import org.sirix.access.DatabaseType
import org.sirix.access.Databases.*
import org.sirix.api.Database
import org.sirix.service.json.serialize.StringValue
import java.nio.charset.StandardCharsets
import java.nio.file.Path
class HistoryHandler(private val location: Path) {
suspend fun handle(ctx: RoutingContext): Route {
val databaseName = ctx.pathParam("database")
val resourceName = ctx.pathParam("resource")
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") val database: Database<*> =
when (getDatabaseType(location.resolve(databaseName).toAbsolutePath())) {
DatabaseType.JSON -> openJsonDatabase(location.resolve(databaseName))
DatabaseType.XML -> openXmlDatabase(location.resolve(databaseName))
}
withContext(ctx.vertx().dispatcher()) {
val buffer = StringBuilder()
database.use {
val manager = database.beginResourceSession(resourceName)
manager.use {
val numberOfRevisions = ctx.queryParam("revisions")
val startRevision = ctx.queryParam("startRevision")
val endRevision = ctx.queryParam("endRevision")
val historyList = if (numberOfRevisions.isEmpty()) {
if (startRevision.isEmpty() && endRevision.isEmpty()) {
manager.history
} else {
val startRevisionAsInt = startRevision[0].toInt()
val endRevisionAsInt = endRevision[0].toInt()
manager.getHistory(startRevisionAsInt, endRevisionAsInt)
}
} else {
val revisions = numberOfRevisions[0].toInt()
manager.getHistory(revisions)
}
buffer.append("{\"history\":[")
historyList.forEachIndexed { index, revisionTuple ->
buffer.append("{\"revision\":")
buffer.append(revisionTuple.revision)
buffer.append(",")
buffer.append("\"revisionTimestamp\":\"")
buffer.append(revisionTuple.revisionTimestamp)
buffer.append("\",")
buffer.append("\"author\":\"")
buffer.append(StringValue.escape(revisionTuple.user.name))
buffer.append("\",")
buffer.append("\"commitMessage\":\"")
buffer.append(StringValue.escape(revisionTuple.commitMessage.orElse("")))
buffer.append("\"}")
if (index != historyList.size - 1)
buffer.append(",")
}
buffer.append("]}")
}
}
val content = buffer.toString()
val res = ctx.response().setStatusCode(200)
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, content.toByteArray(StandardCharsets.UTF_8).size.toString())
res.write(content)
res.end()
}
return ctx.currentRoute()
}
} | bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/HistoryHandler.kt | 2817464197 |
package com.auth0.android.util
/**
* The clock used for verification purposes.
*
* @see com.auth0.android.authentication.storage.SecureCredentialsManager
*
* @see com.auth0.android.authentication.storage.CredentialsManager
*/
public interface Clock {
/**
* Returns the current time in milliseconds (epoch).
*
* @return the current time in milliseconds.
*/
public fun getCurrentTimeMillis(): Long
} | auth0/src/main/java/com/auth0/android/util/Clock.kt | 3292212979 |
package com.maximebertheau.emoji
internal class Node(private val char: Char? = null) {
private val children = mutableMapOf<Char, Node>()
var emoji: Emoji? = null
fun hasChild(child: Char): Boolean = children.containsKey(child)
fun addChild(child: Char) {
children[child] = Node(child)
}
fun getChild(child: Char): Node? = children[child]
override fun toString(): String {
return """(${emoji?.unicode}) | $char -> [${children.map { it.key.toInt().toString(16).toUpperCase() }}]"""
}
}
| src/main/java/com/maximebertheau/emoji/Node.kt | 1353404564 |
/*
* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import java.io.File
import java.io.FileNotFoundException
class AlbumArtContentProvider : ContentProvider() {
override fun onCreate() = true
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
val context = this.context ?: return null
val file = File(uri.path)
if (!file.exists()) {
throw FileNotFoundException(uri.path)
}
// Only allow access to files under cache path
val cachePath = context.cacheDir.path
if (!file.path.startsWith(cachePath)) {
throw FileNotFoundException()
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
}
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? = null
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
) = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = 0
override fun getType(uri: Uri): String? = null
}
| common/src/main/java/com/example/android/uamp/media/library/AlbumArtContentProvider.kt | 3960609341 |
/*
* Copyright 2020 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.common.rx
import com.diffplug.common.base.Box
import com.diffplug.common.base.Converter
import com.diffplug.common.rx.Rx.subscribe
import java.util.function.Consumer
import java.util.function.Function
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
/** [RxGetter] and [Box] combined in one: a value you can set, get, and subscribe to. */
interface RxBox<T> : RxGetter<T>, Box<T> {
/** Returns a read-only version of this `RxBox`. */
fun readOnly(): RxGetter<T> {
return this
}
/** Maps one `RxBox` to another `RxBox`. */
override fun <R> map(converter: Converter<T, R>): RxBox<R> {
return RxBoxImp.Mapped(this, converter)
}
/**
* Provides a mechanism for enforcing an invariant on an existing `RxBox`.
*
* The returned `RxBox` and its observable will **always** satisfy the given invariant. If the
* underlying `RxBox` changes in a way which does not satisfy the invariant, it will be set so
* that it does match the invariant.
*
* During this process, the underlying `RxBox` will momentarily fail to meet the invariant, and
* its `Observable` will emit values which fail the invariant. The returned `RxBox`, however, will
* always meet the invariant, so downstream consumers can rely on the invariant holding true at
* all times.
*
* The returned `RxBox` can be mapped, and has the same atomicity guarantees as the underlying
* `RxBox` (e.g. an enforced [RxLockBox] can still be modified atomically).
*
* Conflicting calls to `enforce` can cause an infinite loop, see [Breaker] for a possible
* solution.
*
* ```java
* // this will not end well...
* RxBox.of(1).enforce(Math::abs).enforce(i -> -Math.abs(i));
* ```
*/
fun enforce(enforcer: Function<in T, out T>): RxBox<T> {
// this must be a plain-old observable, because it needs to fire
// every time an invariant is violated, not only when a violation
// of the invariant causes a change in the output
val mapped = asObservable().map { t: T -> enforcer.apply(t) }
subscribe(mapped) { value: T -> this.set(value) }
// now we can return the RxBox
return map(Converter.from(enforcer, enforcer))
}
companion object {
/** Creates an `RxBox` with the given initial value. */
@JvmStatic
fun <T> of(initial: T): RxBox<T> {
return RxBoxImp(initial)
}
/**
* Creates an `RxBox` which implements the "getter" part with `RxGetter`, and the setter part
* with `Consumer`.
*/
@JvmStatic
fun <T> from(getter: RxGetter<T>, setter: Consumer<T>): RxBox<T> {
return object : RxBox<T> {
override fun asObservable(): Flow<T> {
return getter.asObservable()
}
override fun get(): T {
return getter.get()
}
override fun set(value: T) {
setter.accept(value)
}
}
}
}
}
| src/main/java/com/diffplug/common/rx/RxBox.kt | 2025382210 |
package io.github.ksmirenko.toeflcards.adapters
import android.content.Context
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import io.github.ksmirenko.toeflcards.R
import io.github.ksmirenko.toeflcards.layout.DictionaryFragment
import io.github.ksmirenko.toeflcards.layout.ModuleListFragment
/**
* Adapter for pages of the main screen (list of modules and dictionary).
*/
class MainScreenPagerAdapter(fm: FragmentManager, private val context: Context)
: FragmentPagerAdapter(fm) {
override fun getCount() = 2
override fun getItem(position: Int) =
when (position) {
0 -> ModuleListFragment()
1 -> DictionaryFragment()
else -> Fragment()
}
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> context.getString(R.string.practice)
1 -> context.getString(R.string.dictionary)
else -> ""
}
}
} | app/src/main/java/io/github/ksmirenko/toeflcards/adapters/MainScreenPagerAdapter.kt | 295160893 |
package com.bajdcc.LALR1.interpret.os.user.routine
import com.bajdcc.LALR1.interpret.os.IOSCodePage
import com.bajdcc.util.ResourceLoader
/**
* 【用户态】脚本解释器
*
* @author bajdcc
*/
class URShell : IOSCodePage {
override val name: String
get() = "/usr/p/sh"
override val code: String
get() = ResourceLoader.load(javaClass)
}
| src/main/kotlin/com/bajdcc/LALR1/interpret/os/user/routine/URShell.kt | 1037160908 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling
import org.jetbrains.kotlin.idea.projectModel.*
import org.jetbrains.plugins.gradle.model.ExternalDependency
import org.jetbrains.plugins.gradle.model.ModelFactory
import java.io.Serializable
typealias KotlinDependency = ExternalDependency
class KotlinDependencyMapper {
private var currentIndex: KotlinDependencyId = 0
private val idToDependency = HashMap<KotlinDependencyId, KotlinDependency>()
private val dependencyToId = HashMap<KotlinDependency, KotlinDependencyId>()
fun getDependency(id: KotlinDependencyId) = idToDependency[id]
fun getId(dependency: KotlinDependency): KotlinDependencyId {
return dependencyToId[dependency] ?: let {
currentIndex++
dependencyToId[dependency] = currentIndex
idToDependency[currentIndex] = dependency
return currentIndex
}
}
fun toDependencyMap(): Map<KotlinDependencyId, KotlinDependency> = idToDependency
}
fun KotlinDependency.deepCopy(cache: MutableMap<Any, Any>): KotlinDependency {
val cachedValue = cache[this] as? KotlinDependency
return if (cachedValue != null) {
cachedValue
} else {
val result = ModelFactory.createCopy(this)
cache[this] = result
result
}
}
interface KotlinMPPGradleModel : KotlinSourceSetContainer, Serializable {
val dependencyMap: Map<KotlinDependencyId, KotlinDependency>
val targets: Collection<KotlinTarget>
val extraFeatures: ExtraFeatures
val kotlinNativeHome: String
val cacheAware: CompilerArgumentsCacheAware
@Deprecated(level = DeprecationLevel.WARNING, message = "Use KotlinMPPGradleModel#cacheAware instead")
val partialCacheAware: CompilerArgumentsCacheAware
val kotlinImportingDiagnostics: KotlinImportingDiagnosticsContainer
@Deprecated("Use 'sourceSetsByName' instead", ReplaceWith("sourceSetsByName"), DeprecationLevel.ERROR)
val sourceSets: Map<String, KotlinSourceSet>
get() = sourceSetsByName
override val sourceSetsByName: Map<String, KotlinSourceSet>
companion object {
const val NO_KOTLIN_NATIVE_HOME = ""
}
} | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModel.kt | 3211444298 |
package org.hexworks.zircon.internal.tileset.transformer
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.transformer.Java2DTextureTransformer
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import java.awt.geom.AffineTransform
import java.awt.image.AffineTransformOp
import java.awt.image.BufferedImage
class Java2DHorizontalFlipper : Java2DTextureTransformer() {
override fun transform(texture: TileTexture<BufferedImage>, tile: Tile): TileTexture<BufferedImage> {
val backend = texture.texture
val tx = AffineTransform.getScaleInstance(-1.0, 1.0)
tx.translate(-backend.width.toDouble(), 0.0)
return DefaultTileTexture(
width = texture.width,
height = texture.height,
texture = AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(backend, null),
cacheKey = tile.cacheKey
)
}
}
| zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DHorizontalFlipper.kt | 2903131110 |
package com.github.k0zka.finder4j.backtrack.examples.lab
import com.github.k0zka.finder4j.backtrack.Backtrack
import com.github.k0zka.finder4j.backtrack.termination.FirstSolutionTerminationStrategy
import org.slf4j.LoggerFactory
import java.util.Arrays
object Main {
private val logger = LoggerFactory.getLogger(Main::class.java)
@JvmStatic
fun main(args: Array<String>) {
val terminationStrategy = FirstSolutionTerminationStrategy<LabState>()
Backtrack.backtrack(
LabState(arrayOf(arrayOf(LabObject.Floor, LabObject.Floor, LabObject.Floor, LabObject.Wall),
arrayOf(LabObject.Wall, LabObject.Floor, LabObject.Floor, LabObject.Wall),
arrayOf(LabObject.Wall, LabObject.Floor, LabObject.Wall, LabObject.Wall),
arrayOf(LabObject.Floor, LabObject.Monster, LabObject.Floor, LabObject.Exit)), Arrays
.asList(Position(0, 0))), LabStepFactory(),
terminationStrategy, terminationStrategy)
logger.info("Solution: ", terminationStrategy.solution)
}
}
| finder4j-backtrack-examples/src/main/kotlin/com/github/k0zka/finder4j/backtrack/examples/lab/Main.kt | 1750881136 |
package org.ligi.passandroid
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.ligi.passandroid.functions.checkThatHelpIsThere
import org.ligi.passandroid.ui.HelpActivity
import org.ligi.trulesk.TruleskActivityRule
class TheHelpActivity {
@get:Rule
val rule = TruleskActivityRule(HelpActivity::class.java)
@Test
fun testHelpIsThere() {
checkThatHelpIsThere()
rule.screenShot("help")
}
@Test
fun test_that_help_finishes_on_home() {
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click())
assertThat(rule.activity.isFinishing).isTrue
}
@Test
fun test_that_version_is_shown() {
onView(withText("v" + BuildConfig.VERSION_NAME)).check(matches(isDisplayed()))
}
}
| android/src/androidTest/java/org/ligi/passandroid/TheHelpActivity.kt | 3647524207 |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.configurationcache.serialization.codecs
import org.gradle.api.artifacts.component.BuildIdentifier
import org.gradle.api.file.Directory
import org.gradle.api.file.RegularFile
import org.gradle.api.internal.file.DefaultFilePropertyFactory.DefaultDirectoryVar
import org.gradle.api.internal.file.DefaultFilePropertyFactory.DefaultRegularFileVar
import org.gradle.api.internal.file.FilePropertyFactory
import org.gradle.api.internal.provider.DefaultListProperty
import org.gradle.api.internal.provider.DefaultMapProperty
import org.gradle.api.internal.provider.DefaultProperty
import org.gradle.api.internal.provider.DefaultProvider
import org.gradle.api.internal.provider.DefaultSetProperty
import org.gradle.api.internal.provider.DefaultValueSourceProviderFactory.ValueSourceProvider
import org.gradle.api.internal.provider.PropertyFactory
import org.gradle.api.internal.provider.ProviderInternal
import org.gradle.api.internal.provider.ValueSourceProviderFactory
import org.gradle.api.internal.provider.ValueSupplier
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ValueSourceParameters
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
import org.gradle.api.services.internal.BuildServiceProvider
import org.gradle.api.services.internal.BuildServiceRegistryInternal
import org.gradle.configurationcache.extensions.serviceOf
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingSharedIdentity
import org.gradle.configurationcache.serialization.encodePreservingSharedIdentityOf
import org.gradle.configurationcache.serialization.logPropertyProblem
import org.gradle.configurationcache.serialization.readClassOf
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.internal.build.BuildStateRegistry
/**
* This is not used directly when encoding or decoding the object graph. This codec takes care of substituting a provider whose
* value is known at configuration time with a fixed value.
*/
internal
class FixedValueReplacingProviderCodec(
valueSourceProviderFactory: ValueSourceProviderFactory,
buildStateRegistry: BuildStateRegistry
) {
private
val providerWithChangingValueCodec = Bindings.of {
bind(ValueSourceProviderCodec(valueSourceProviderFactory))
bind(BuildServiceProviderCodec(buildStateRegistry))
bind(BeanCodec)
}.build()
suspend fun WriteContext.encodeProvider(value: ProviderInternal<*>) {
val state = try {
value.calculateExecutionTimeValue()
} catch (e: Exception) {
logPropertyProblem("serialize", e) {
text("value ")
reference(value.toString())
text(" failed to unpack provider")
}
writeByte(0)
write(BrokenValue(e))
return
}
encodeValue(state)
}
suspend fun WriteContext.encodeValue(value: ValueSupplier.ExecutionTimeValue<*>) {
when {
value.isMissing -> {
// Can serialize a fixed value and discard the provider
// TODO - should preserve information about the source, for diagnostics at execution time
writeByte(1)
}
value.isFixedValue -> {
// Can serialize a fixed value and discard the provider
// TODO - should preserve information about the source, for diagnostics at execution time
writeByte(2)
write(value.fixedValue)
}
else -> {
// Cannot write a fixed value, so write the provider itself
writeByte(3)
providerWithChangingValueCodec.run { encode(value.changingValue) }
}
}
}
suspend fun ReadContext.decodeProvider(): ProviderInternal<*> {
return decodeValue().toProvider()
}
suspend fun ReadContext.decodeValue(): ValueSupplier.ExecutionTimeValue<*> =
when (readByte()) {
0.toByte() -> {
val value = read() as BrokenValue
ValueSupplier.ExecutionTimeValue.changingValue(DefaultProvider { value.rethrow() })
}
1.toByte() -> ValueSupplier.ExecutionTimeValue.missing<Any>()
2.toByte() -> ValueSupplier.ExecutionTimeValue.ofNullable(read()) // nullable because serialization may replace value with null, eg when using provider of Task
3.toByte() -> ValueSupplier.ExecutionTimeValue.changingValue<Any>(providerWithChangingValueCodec.run { decode() }!!.uncheckedCast())
else -> throw IllegalStateException("Unexpected provider value")
}
}
/**
* Handles Provider instances seen in the object graph, and delegates to another codec that handles the value.
*/
internal
class ProviderCodec(
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<ProviderInternal<*>> {
override suspend fun WriteContext.encode(value: ProviderInternal<*>) {
// TODO - should write the provider value type
providerCodec.run { encodeProvider(value) }
}
override suspend fun ReadContext.decode() =
providerCodec.run { decodeProvider() }
}
internal
class BuildServiceProviderCodec(
private val buildStateRegistry: BuildStateRegistry
) : Codec<BuildServiceProvider<*, *>> {
override suspend fun WriteContext.encode(value: BuildServiceProvider<*, *>) {
encodePreservingSharedIdentityOf(value) {
val buildIdentifier = value.buildIdentifier
write(buildIdentifier)
writeString(value.name)
writeClass(value.implementationType)
write(value.parameters)
writeInt(
buildServiceRegistryOf(buildIdentifier).forService(value).maxUsages
)
}
}
override suspend fun ReadContext.decode(): BuildServiceProvider<*, *>? =
decodePreservingSharedIdentity {
val buildIdentifier = readNonNull<BuildIdentifier>()
val name = readString()
val implementationType = readClassOf<BuildService<*>>()
val parameters = read() as BuildServiceParameters?
val maxUsages = readInt()
buildServiceRegistryOf(buildIdentifier).register(name, implementationType, parameters, maxUsages)
}
private
fun buildServiceRegistryOf(buildIdentifier: BuildIdentifier) =
buildStateRegistry.getBuild(buildIdentifier).mutableModel.serviceOf<BuildServiceRegistryInternal>()
}
internal
class ValueSourceProviderCodec(
private val valueSourceProviderFactory: ValueSourceProviderFactory
) : Codec<ValueSourceProvider<*, *>> {
override suspend fun WriteContext.encode(value: ValueSourceProvider<*, *>) {
when (value.obtainedValueOrNull) {
null -> {
// source has **NOT** been used as build logic input:
// serialize the source
writeBoolean(true)
encodeValueSource(value)
}
else -> {
// source has been used as build logic input:
// serialize the value directly as it will be part of the
// cached state fingerprint.
// Currently not necessary due to the unpacking that happens
// to the TypeSanitizingProvider put around the ValueSourceProvider.
throw IllegalStateException("build logic input")
}
}
}
override suspend fun ReadContext.decode(): ValueSourceProvider<*, *>? =
when (readBoolean()) {
true -> decodeValueSource()
false -> throw IllegalStateException()
}
private
suspend fun WriteContext.encodeValueSource(value: ValueSourceProvider<*, *>) {
encodePreservingSharedIdentityOf(value) {
value.run {
writeClass(valueSourceType)
writeClass(parametersType as Class<*>)
write(parameters)
}
}
}
private
suspend fun ReadContext.decodeValueSource(): ValueSourceProvider<*, *> =
decodePreservingSharedIdentity {
val valueSourceType = readClass()
val parametersType = readClass()
val parameters = read()!!
val provider =
valueSourceProviderFactory.instantiateValueSourceProvider<Any, ValueSourceParameters>(
valueSourceType.uncheckedCast(),
parametersType.uncheckedCast(),
parameters.uncheckedCast()
)
provider.uncheckedCast()
}
}
internal
class PropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultProperty<*>> {
override suspend fun WriteContext.encode(value: DefaultProperty<*>) {
writeClass(value.type as Class<*>)
providerCodec.run { encodeProvider(value.provider) }
}
override suspend fun ReadContext.decode(): DefaultProperty<*> {
val type: Class<Any> = readClass().uncheckedCast()
val provider = providerCodec.run { decodeProvider() }
return propertyFactory.property(type).provider(provider)
}
}
internal
class DirectoryPropertyCodec(
private val filePropertyFactory: FilePropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultDirectoryVar> {
override suspend fun WriteContext.encode(value: DefaultDirectoryVar) {
providerCodec.run { encodeProvider(value.provider) }
}
override suspend fun ReadContext.decode(): DefaultDirectoryVar {
val provider: Provider<Directory> = providerCodec.run { decodeProvider() }.uncheckedCast()
return filePropertyFactory.newDirectoryProperty().value(provider) as DefaultDirectoryVar
}
}
internal
class RegularFilePropertyCodec(
private val filePropertyFactory: FilePropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultRegularFileVar> {
override suspend fun WriteContext.encode(value: DefaultRegularFileVar) {
providerCodec.run { encodeProvider(value.provider) }
}
override suspend fun ReadContext.decode(): DefaultRegularFileVar {
val provider: Provider<RegularFile> = providerCodec.run { decodeProvider() }.uncheckedCast()
return filePropertyFactory.newFileProperty().value(provider) as DefaultRegularFileVar
}
}
internal
class ListPropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultListProperty<*>> {
override suspend fun WriteContext.encode(value: DefaultListProperty<*>) {
writeClass(value.elementType)
providerCodec.run { encodeValue(value.calculateExecutionTimeValue()) }
}
override suspend fun ReadContext.decode(): DefaultListProperty<*> {
val type: Class<Any> = readClass().uncheckedCast()
val value: ValueSupplier.ExecutionTimeValue<List<Any>> = providerCodec.run { decodeValue() }.uncheckedCast()
return propertyFactory.listProperty(type).apply {
fromState(value)
}
}
}
internal
class SetPropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultSetProperty<*>> {
override suspend fun WriteContext.encode(value: DefaultSetProperty<*>) {
writeClass(value.elementType)
providerCodec.run { encodeValue(value.calculateExecutionTimeValue()) }
}
override suspend fun ReadContext.decode(): DefaultSetProperty<*> {
val type: Class<Any> = readClass().uncheckedCast()
val value: ValueSupplier.ExecutionTimeValue<Set<Any>> = providerCodec.run { decodeValue() }.uncheckedCast()
return propertyFactory.setProperty(type).apply {
fromState(value)
}
}
}
internal
class MapPropertyCodec(
private val propertyFactory: PropertyFactory,
private val providerCodec: FixedValueReplacingProviderCodec
) : Codec<DefaultMapProperty<*, *>> {
override suspend fun WriteContext.encode(value: DefaultMapProperty<*, *>) {
writeClass(value.keyType)
writeClass(value.valueType)
providerCodec.run { encodeValue(value.calculateExecutionTimeValue()) }
}
override suspend fun ReadContext.decode(): DefaultMapProperty<*, *> {
val keyType: Class<Any> = readClass().uncheckedCast()
val valueType: Class<Any> = readClass().uncheckedCast()
val state: ValueSupplier.ExecutionTimeValue<Map<Any, Any>> = providerCodec.run { decodeValue() }.uncheckedCast()
return propertyFactory.mapProperty(keyType, valueType).apply {
fromState(state)
}
}
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/ProviderCodecs.kt | 3451705880 |
package com.subakstudio.wol
/**
* Created by jinwoomin on 5/4/16.
*/
interface IWolTrigger {
fun trigger()
} | src/main/kotlin/com/subakstudio/wol/IWolTrigger.kt | 247370110 |
package com.edwardharker.aircraftrecognition.ui.search
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.edwardharker.aircraftrecognition.android.diffutils.AircraftDiffCallback
import com.edwardharker.aircraftrecognition.model.Aircraft
import com.edwardharker.aircraftsearch.R
class SearchAdapter(
private val aircraftClickListener: (Aircraft) -> Unit,
private val feedbackClickListener: () -> Unit
) : ListAdapter<Aircraft, SearchAdapter.ViewHolder>(AircraftDiffCallback) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position < super.getItemCount()) {
bindAircraft(position, holder)
} else {
bindFeedback(holder)
}
}
private fun bindFeedback(holder: ViewHolder) {
holder.label.text = holder.itemView.context.getString(R.string.suggest_aircraft)
holder.itemView.setOnClickListener { feedbackClickListener() }
}
private fun bindAircraft(
position: Int,
holder: ViewHolder
) {
val aircraft = getItem(position)
holder.label.text = aircraft.name
holder.itemView.setOnClickListener { aircraftClickListener(aircraft) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.view_search_result, parent, false)
)
}
override fun getItemCount(): Int = super.getItemCount() + 1
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val label = view as TextView
}
}
| aircraftsearch/src/main/java/com/edwardharker/aircraftrecognition/ui/search/SearchAdapter.kt | 2101351855 |
package pack1
fun ConcurrentHashMap(){} | plugins/kotlin/idea/tests/testData/addImport/ImportClassWhenFunctionImported.dependency.kt | 3866607852 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.asJava
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.TestRoot
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.test.TestMetadata
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
// see KtFileLightClassTest
@TestRoot("idea/tests")
@TestMetadata("testData/asJava/fileLightClass")
@RunWith(JUnit38ClassRunner::class)
class LightClassFromTextTest8 : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
fun testSimple() {
myFixture.configureByText("Dummy.kt", "") as KtFile
val classes = classesFromText("class C {}\nobject O {}")
assertEquals(2, classes.size)
assertEquals("C", classes[0].qualifiedName)
assertEquals("O", classes[1].qualifiedName)
}
fun testLightClassImplementation() {
myFixture.configureByText("Dummy.kt", "") as KtFile
val classes = classesFromText("import something\nclass C;")
assertEquals(1, classes.size)
val classC = classes[0]
assertEquals("C", classC.qualifiedName)
assertEquals("class C", classC.text)
assertEquals(TextRange(17, 24), classC.textRange)
assertEquals(23, classC.textOffset)
assertEquals(17, classC.startOffsetInParent)
assertTrue(classC.isWritable)
}
fun testFileClass() {
myFixture.configureByText("A.kt", "fun f() {}") as KtFile
val classes = classesFromText("fun g() {}", fileName = "A.kt")
assertEquals(1, classes.size)
val facadeClass = classes.single()
assertEquals("AKt", facadeClass.qualifiedName)
val gMethods = facadeClass.findMethodsByName("g", false)
assertEquals(1, gMethods.size)
assertEquals(PsiType.VOID, gMethods.single().returnType)
val fMethods = facadeClass.findMethodsByName("f", false)
assertEquals(0, fMethods.size)
}
fun testMultifileClass() {
myFixture.configureByFiles("multifile1.kt", "multifile2.kt")
val facadeClass = classesFromText(
"""
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("Foo")
fun jar() {
}
fun boo() {
}
"""
).single()
assertEquals(1, facadeClass.findMethodsByName("jar", false).size)
assertEquals(1, facadeClass.findMethodsByName("boo", false).size)
assertEquals(0, facadeClass.findMethodsByName("bar", false).size)
assertEquals(0, facadeClass.findMethodsByName("foo", false).size)
}
fun testReferenceToOuterContext() {
val contextFile = myFixture.configureByText("Example.kt", "package foo\n class Example") as KtFile
val syntheticClass = classesFromText(
"""
package bar
import foo.Example
class Usage {
fun f(): Example = Example()
}
"""
).single()
val exampleClass = contextFile.classes.single()
assertEquals("Example", exampleClass.name)
val f = syntheticClass.findMethodsByName("f", false).single()
assertEquals(exampleClass, (f.returnType as PsiClassType).resolve())
}
fun testHeaderDeclarations() {
val contextFile = myFixture.configureByText("Header.kt", "header class Foo\n\nheader fun foo()\n") as KtFile
val headerClass = contextFile.declarations.single { it is KtClassOrObject }
assertEquals(0, headerClass.toLightElements().size)
val headerFunction = contextFile.declarations.single { it is KtNamedFunction }
assertEquals(0, headerFunction.toLightElements().size)
}
private fun classesFromText(text: String, fileName: String = "A.kt"): Array<out PsiClass> {
val file = KtPsiFactory(project).createFileWithLightClassSupport(fileName, text, myFixture.file)
return file.classes
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/asJava/LightClassFromTextTest.kt | 3757822642 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class KeyParentImpl : KeyParent, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(KeyParent::class.java, KeyChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField
var _keyField: String? = null
override val keyField: String
get() = _keyField!!
@JvmField
var _notKeyField: String? = null
override val notKeyField: String
get() = _notKeyField!!
override val children: List<KeyChild>
get() = snapshot.extractOneToManyChildren<KeyChild>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: KeyParentData?) : ModifiableWorkspaceEntityBase<KeyParent>(), KeyParent.Builder {
constructor() : this(KeyParentData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity KeyParent is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isKeyFieldInitialized()) {
error("Field KeyParent#keyField should be initialized")
}
if (!getEntityData().isNotKeyFieldInitialized()) {
error("Field KeyParent#notKeyField should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field KeyParent#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field KeyParent#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as KeyParent
this.entitySource = dataSource.entitySource
this.keyField = dataSource.keyField
this.notKeyField = dataSource.notKeyField
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var keyField: String
get() = getEntityData().keyField
set(value) {
checkModificationAllowed()
getEntityData().keyField = value
changedProperty.add("keyField")
}
override var notKeyField: String
get() = getEntityData().notKeyField
set(value) {
checkModificationAllowed()
getEntityData().notKeyField = value
changedProperty.add("notKeyField")
}
// List of non-abstract referenced types
var _children: List<KeyChild>? = emptyList()
override var children: List<KeyChild>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<KeyChild>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<KeyChild>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<KeyChild> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): KeyParentData = result ?: super.getEntityData() as KeyParentData
override fun getEntityClass(): Class<KeyParent> = KeyParent::class.java
}
}
class KeyParentData : WorkspaceEntityData<KeyParent>() {
lateinit var keyField: String
lateinit var notKeyField: String
fun isKeyFieldInitialized(): Boolean = ::keyField.isInitialized
fun isNotKeyFieldInitialized(): Boolean = ::notKeyField.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<KeyParent> {
val modifiable = KeyParentImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): KeyParent {
val entity = KeyParentImpl()
entity._keyField = keyField
entity._notKeyField = notKeyField
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return KeyParent::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return KeyParent(keyField, notKeyField, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.entitySource != other.entitySource) return false
if (this.keyField != other.keyField) return false
if (this.notKeyField != other.notKeyField) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.keyField != other.keyField) return false
if (this.notKeyField != other.notKeyField) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + keyField.hashCode()
result = 31 * result + notKeyField.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + keyField.hashCode()
result = 31 * result + notKeyField.hashCode()
return result
}
override fun equalsByKey(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as KeyParentData
if (this.keyField != other.keyField) return false
return true
}
override fun hashCodeByKey(): Int {
var result = javaClass.hashCode()
result = 31 * result + keyField.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/KeyParentImpl.kt | 2446284521 |
/*
* NfcSettingsPreference.kt
*
* Copyright 2019 Michael Farrell <[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 au.id.micolous.metrodroid.ui
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.util.AttributeSet
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.preference.Preference
import au.id.micolous.metrodroid.util.Utils
class NfcSettingsPreference : Preference {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) :
super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) :
super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onClick() {
showNfcSettings(context)
}
companion object {
private const val TAG = "NfcSettingsPreference"
private const val ADVANCED_CONNECTED_DEVICE_SETTINGS =
"com.android.settings.ADVANCED_CONNECTED_DEVICE_SETTINGS"
fun showNfcSettings(context: Context) {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
// Workaround for https://issuetracker.google.com/135970325
// Only required for Android P
if (Utils.tryStartActivity(context, ADVANCED_CONNECTED_DEVICE_SETTINGS))
return
}
// JB and later; we target JB+, so can skip the version check
if (Utils.tryStartActivity(context, Settings.ACTION_NFC_SETTINGS))
return
// Fallback
if (Utils.tryStartActivity(context, Settings.ACTION_WIRELESS_SETTINGS))
return
Log.w(TAG, "Failed to launch NFC settings")
}
}
}
| src/main/java/au/id/micolous/metrodroid/ui/NfcSettingsPreference.kt | 2691949573 |
package <%= appPackage %>.ui.browse
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.contrib.RecyclerViewActions
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.v7.widget.RecyclerView
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.Flowable
import <%= appPackage %>.domain.model.Bufferoo
import <%= appPackage %>.ui.R
import <%= appPackage %>.ui.test.TestApplication
import <%= appPackage %>.ui.test.util.BufferooFactory
import <%= appPackage %>.ui.test.util.RecyclerViewMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class BrowseActivityTest {
@Rule @JvmField
val activity = ActivityTestRule<BrowseActivity>(BrowseActivity::class.java, false, false)
@Test
fun activityLaunches() {
stubBufferooRepositoryGetBufferoos(Flowable.just(BufferooFactory.makeBufferooList(2)))
activity.launchActivity(null)
}
@Test
fun bufferoosDisplay() {
val bufferoos = BufferooFactory.makeBufferooList(1)
stubBufferooRepositoryGetBufferoos(Flowable.just(bufferoos))
activity.launchActivity(null)
checkBufferooDetailsDisplay(bufferoos[0], 0)
}
@Test
fun bufferoosAreScrollable() {
val bufferoos = BufferooFactory.makeBufferooList(20)
stubBufferooRepositoryGetBufferoos(Flowable.just(bufferoos))
activity.launchActivity(null)
bufferoos.forEachIndexed { index, bufferoo ->
onView(withId(R.id.recycler_browse)).perform(RecyclerViewActions.
scrollToPosition<RecyclerView.ViewHolder>(index))
checkBufferooDetailsDisplay(bufferoo, index) }
}
private fun checkBufferooDetailsDisplay(bufferoo: Bufferoo, position: Int) {
onView(RecyclerViewMatcher.withRecyclerView(R.id.recycler_browse).atPosition(position))
.check(matches(hasDescendant(withText(bufferoo.name))))
onView(RecyclerViewMatcher.withRecyclerView(R.id.recycler_browse).atPosition(position))
.check(matches(hasDescendant(withText(bufferoo.title))))
}
private fun stubBufferooRepositoryGetBufferoos(single: Flowable<List<Bufferoo>>) {
whenever(TestApplication.appComponent().bufferooRepository().getBufferoos())
.thenReturn(single)
}
} | templates/buffer-clean-architecture-components-kotlin/mobile-ui/src/androidTest/java/org/buffer/android/boilerplate/ui/browse/BrowseActivityTest.kt | 1264936543 |
package net.squanchy.navigation
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.disposables.CompositeDisposable
import net.squanchy.R
import net.squanchy.navigation.deeplink.DeepLinkRouter
import net.squanchy.onboarding.Onboarding
import net.squanchy.signin.SignInService
import timber.log.Timber
class RoutingActivity : AppCompatActivity() {
private lateinit var deepLinkRouter: DeepLinkRouter
private lateinit var navigator: Navigator
private lateinit var onboarding: Onboarding
private lateinit var signInService: SignInService
private lateinit var firstStartPersister: FirstStartPersister
private val subscriptions = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val component = routingComponent(this)
deepLinkRouter = component.deepLinkRouter()
navigator = component.navigator()
onboarding = component.onboarding()
signInService = component.signInService()
firstStartPersister = component.firstStartPersister()
}
override fun onStart() {
super.onStart()
subscriptions.add(
signInService.signInAnonymouslyIfNecessary()
.subscribe(::onboardOrProceedToRouting, ::handleSignInError)
)
}
private fun handleSignInError(throwable: Throwable) {
Timber.e(throwable, "Error while signing in on routing")
if (!firstStartPersister.hasBeenStartedAlready()) {
// We likely have no data here and it'd be a horrible UX, so we show a warning instead
// to let people know it won't work.
val continuationIntent = createContinueIntentFrom(intent)
navigator.toFirstStartWithNoNetwork(continuationIntent)
} else {
Toast.makeText(this, R.string.routing_sign_in_unexpected_error, Toast.LENGTH_LONG).show()
}
finish()
}
private fun createContinueIntentFrom(intent: Intent) =
Intent(intent).apply {
removeCategory(Intent.CATEGORY_LAUNCHER)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
ONBOARDING_REQUEST_CODE -> handleOnboardingResult(resultCode)
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
private fun handleOnboardingResult(resultCode: Int) {
when (resultCode) {
Activity.RESULT_OK -> onboardOrProceedToRouting()
else -> finish()
}
}
private fun onboardOrProceedToRouting() {
onboarding.nextPageToShow()
?.let { navigator.toOnboardingForResult(it, ONBOARDING_REQUEST_CODE) }
?: proceedTo(intent)
}
private fun proceedTo(intent: Intent) {
if (deepLinkRouter.hasDeepLink(intent)) {
val intentUriString = intent.dataString!!
Timber.i("Deeplink detected, navigating to $intentUriString")
deepLinkRouter.navigateTo(intentUriString)
} else {
navigator.toHomePage()
}
firstStartPersister.storeHasBeenStarted()
finish()
}
override fun onStop() {
super.onStop()
subscriptions.clear()
}
companion object {
private const val ONBOARDING_REQUEST_CODE = 2453
}
}
| app/src/main/java/net/squanchy/navigation/RoutingActivity.kt | 2679393762 |
/*
* Copyright (C) 2019. Zac Sweers
*
* 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.sweers.catchup.service.dribbble.model
/**
* Models a dribbble user
*/
data class User(
val avatarUrl: String,
val htmlUrl: String,
val id: Long,
val name: String,
val pro: Boolean?,
val username: String?
)
| services/dribbble/src/main/kotlin/io/sweers/catchup/service/dribbble/model/User.kt | 3973555543 |
package csumissu.weatherforecast.di
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import csumissu.weatherforecast.App
import csumissu.weatherforecast.util.SimpleActivityLifecycleCallbacks
import dagger.android.AndroidInjection
import dagger.android.support.AndroidSupportInjection
import dagger.android.support.HasSupportFragmentInjector
/**
* @author yxsun
* @since 06/08/2017
*/
interface Injectable
object AutoInjector {
fun init(app: App) {
app.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks() {
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
handleActivityInjection(activity)
}
})
}
private fun handleActivityInjection(activity: Activity) {
if (activity is Injectable) {
AndroidInjection.inject(activity)
} else if (activity is HasSupportFragmentInjector) {
AndroidInjection.inject(activity)
if (activity is FragmentActivity) {
handleFragmentInjection(activity.supportFragmentManager)
}
}
}
private fun handleFragmentInjection(fragmentManager: FragmentManager) {
fragmentManager.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentAttached(fm: FragmentManager?, f: Fragment?, ctx: Context?) {
if (f is Injectable) {
AndroidSupportInjection.inject(f)
}
}
}, true)
}
} | app/src/main/java/csumissu/weatherforecast/di/AutoInjector.kt | 215922030 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.ExpectedTypeUtil
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate
import com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInspection.CommonQuickFixBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.jvm.actions.CreateEnumConstantActionGroup
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.ExpectedTypes
import com.intellij.lang.jvm.actions.JvmActionGroup
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiFile
import com.intellij.psi.util.JavaElementKind
import com.intellij.psi.util.PsiTreeUtil
internal class CreateEnumConstantAction(
target: PsiClass,
override val request: CreateFieldRequest
) : CreateFieldActionBase(target, request), HighPriorityAction {
override fun getActionGroup(): JvmActionGroup = CreateEnumConstantActionGroup
override fun getText(): String = CommonQuickFixBundle.message("fix.create.title.x", JavaElementKind.ENUM_CONSTANT.`object`(), request.fieldName)
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
val constructor = target.constructors.firstOrNull() ?: return IntentionPreviewInfo.EMPTY
val hasParameters = constructor.parameters.isNotEmpty()
val text = if (hasParameters) "${request.fieldName}(...)" else request.fieldName
return IntentionPreviewInfo.CustomDiff(JavaFileType.INSTANCE, "", text)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val name = request.fieldName
val targetClass = target
val elementFactory = JavaPsiFacade.getElementFactory(project)!!
// add constant
var enumConstant: PsiEnumConstant
enumConstant = elementFactory.createEnumConstantFromText(name, null)
enumConstant = targetClass.add(enumConstant) as PsiEnumConstant
// start template
val constructor = targetClass.constructors.firstOrNull() ?: return
val parameters = constructor.parameterList.parameters
if (parameters.isEmpty()) return
val paramString = parameters.joinToString(",") { it.name }
enumConstant = enumConstant.replace(elementFactory.createEnumConstantFromText("$name($paramString)", null)) as PsiEnumConstant
val builder = TemplateBuilderImpl(enumConstant)
val argumentList = enumConstant.argumentList!!
for (expression in argumentList.expressions) {
builder.replaceElement(expression, EmptyExpression())
}
enumConstant = forcePsiPostprocessAndRestoreElement(enumConstant) ?: return
val template = builder.buildTemplate()
val newEditor = positionCursor(project, targetClass.containingFile, enumConstant) ?: return
val range = enumConstant.textRange
newEditor.document.deleteString(range.startOffset, range.endOffset)
startTemplate(newEditor, template, project)
}
}
internal fun canCreateEnumConstant(targetClass: PsiClass, request: CreateFieldRequest): Boolean {
if (!targetClass.isEnum) return false
val lastConstant = targetClass.fields.filterIsInstance<PsiEnumConstant>().lastOrNull()
if (lastConstant != null && PsiTreeUtil.hasErrorElements(lastConstant)) return false
return checkExpectedTypes(request.fieldType, targetClass, targetClass.project)
}
private fun checkExpectedTypes(types: ExpectedTypes, targetClass: PsiClass, project: Project): Boolean {
val typeInfos = extractExpectedTypes(project, types)
if (typeInfos.isEmpty()) return true
val enumType = JavaPsiFacade.getElementFactory(project).createType(targetClass)
return typeInfos.any {
ExpectedTypeUtil.matches(enumType, it)
}
}
| java/java-impl/src/com/intellij/lang/java/actions/CreateEnumConstantAction.kt | 1771797091 |
fun test(value: Any) {
value<caret>
} | plugins/kotlin/code-insight/postfix-templates/testData/expansion/null/notNull.kt | 135852977 |
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SetVFUEntityImpl(val dataSource: SetVFUEntityData) : SetVFUEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: String
get() = dataSource.data
override val fileProperty: Set<VirtualFileUrl>
get() = dataSource.fileProperty
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SetVFUEntityData?) : ModifiableWorkspaceEntityBase<SetVFUEntity, SetVFUEntityData>(result), SetVFUEntity.Builder {
constructor() : this(SetVFUEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SetVFUEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
index(this, "fileProperty", this.fileProperty.toHashSet())
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field SetVFUEntity#data should be initialized")
}
if (!getEntityData().isFilePropertyInitialized()) {
error("Field SetVFUEntity#fileProperty should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override fun afterModification() {
val collection_fileProperty = getEntityData().fileProperty
if (collection_fileProperty is MutableWorkspaceSet<*>) {
collection_fileProperty.cleanModificationUpdateAction()
}
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SetVFUEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (this.fileProperty != dataSource.fileProperty) this.fileProperty = dataSource.fileProperty.toMutableSet()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
private val filePropertyUpdater: (value: Set<VirtualFileUrl>) -> Unit = { value ->
val _diff = diff
if (_diff != null) index(this, "fileProperty", value.toHashSet())
changedProperty.add("fileProperty")
}
override var fileProperty: MutableSet<VirtualFileUrl>
get() {
val collection_fileProperty = getEntityData().fileProperty
if (collection_fileProperty !is MutableWorkspaceSet) return collection_fileProperty
if (diff == null || modifiable.get()) {
collection_fileProperty.setModificationUpdateAction(filePropertyUpdater)
}
else {
collection_fileProperty.cleanModificationUpdateAction()
}
return collection_fileProperty
}
set(value) {
checkModificationAllowed()
getEntityData(true).fileProperty = value
filePropertyUpdater.invoke(value)
}
override fun getEntityClass(): Class<SetVFUEntity> = SetVFUEntity::class.java
}
}
class SetVFUEntityData : WorkspaceEntityData<SetVFUEntity>() {
lateinit var data: String
lateinit var fileProperty: MutableSet<VirtualFileUrl>
fun isDataInitialized(): Boolean = ::data.isInitialized
fun isFilePropertyInitialized(): Boolean = ::fileProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SetVFUEntity> {
val modifiable = SetVFUEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SetVFUEntity {
return getCached(snapshot) {
val entity = SetVFUEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): SetVFUEntityData {
val clonedEntity = super.clone()
clonedEntity as SetVFUEntityData
clonedEntity.fileProperty = clonedEntity.fileProperty.toMutableWorkspaceSet()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SetVFUEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SetVFUEntity(data, fileProperty, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SetVFUEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SetVFUEntityData
if (this.data != other.data) return false
if (this.fileProperty != other.fileProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + fileProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.fileProperty?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SetVFUEntityImpl.kt | 3215310155 |
expect fun <!LINE_MARKER("descr='Has actuals in base_jvm module'")!>foo<!>(): Int
| plugins/kotlin/idea/tests/testData/multiModuleLineMarker/transitive/base_common/common.kt | 2893476265 |
package com.strumenta.kolasu.cli
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.help
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.file
import com.strumenta.kolasu.model.Node
import com.strumenta.kolasu.parsing.ASTParser
import com.strumenta.kolasu.parsing.ParsingResult
import com.strumenta.kolasu.validation.IssueSeverity
import java.io.File
import java.nio.charset.Charset
import java.util.function.Function
import kotlin.system.exitProcess
typealias ParserInstantiator<P> = Function<File, P?>
abstract class ASTProcessingCommand<R : Node, P : ASTParser<R>>(
val parserInstantiator: ParserInstantiator<P>,
help: String = "",
name: String? = null,
) :
CliktCommand(help = help, name = name) {
protected val inputs by argument().file(mustExist = true).multiple()
protected val charset by option("--charset", "-c")
.help("Set the charset to use to load the files. Default is UTF-8")
.default("UTF-8")
protected val ignorePositions by option("--ignore-positions")
.help("Ignore positions, so that they do not appear in the AST")
.flag("--consider-positions", default = false)
protected val verbose by option("--verbose", "-v")
.help("Print additional messages")
.flag(default = false)
override fun run() {
initializeRun()
if (inputs.isEmpty()) {
echo("No inputs specified, exiting", trailingNewline = true)
exitProcess(1)
}
inputs.forEach { processInput(it, explicit = true, relativePath = "") }
finalizeRun()
}
protected open fun initializeRun() {
}
protected open fun finalizeRun() {
}
/**
* If null is returned it means we cannot parse this file
*/
private fun instantiateParser(input: File): P? {
return parserInstantiator.apply(input)
}
protected abstract fun processResult(input: File, relativePath: String, result: ParsingResult<R>, parser: P)
protected abstract fun processException(input: File, relativePath: String, e: Exception)
private fun processSourceFile(input: File, relativePath: String) {
try {
val parser = instantiateParser(input)
if (parser == null) {
if (verbose) {
echo("skipping ${input.absolutePath}", trailingNewline = true)
}
return
}
if (verbose) {
echo("processing ${input.absolutePath}", trailingNewline = true)
}
val parsingResult =
parser.parse(input, Charset.forName(charset), considerPosition = !ignorePositions)
if (verbose) {
val nErrors = parsingResult.issues.count { it.severity == IssueSeverity.ERROR }
val nWarnings = parsingResult.issues.count { it.severity == IssueSeverity.WARNING }
if (nErrors == 0 && nWarnings == 0) {
echo(" no errors and no warnings", trailingNewline = true)
} else {
if (nErrors == 0) {
echo(" $nWarnings warnings", trailingNewline = true)
} else if (nWarnings == 0) {
echo(" $nErrors errors", trailingNewline = true)
} else {
echo(" $nErrors errors and $nWarnings warnings", trailingNewline = true)
}
}
}
processResult(input, relativePath, parsingResult, parser)
} catch (e: Exception) {
processException(input, relativePath, e)
}
}
private fun processInput(input: File, explicit: Boolean = false, relativePath: String) {
if (input.isDirectory) {
input.listFiles()?.forEach {
processInput(it, relativePath = relativePath + File.separator + it.name)
}
} else if (input.isFile) {
processSourceFile(input, relativePath)
} else {
if (explicit) {
echo(
"The provided input is neither a file or a directory, we will ignore it: " +
"${input.absolutePath}",
trailingNewline = true
)
} else {
// ignore silently
}
}
}
}
fun File.changeExtension(newExtension: String): File {
var name = this.name
val i = name.lastIndexOf('.')
return if (i == -1) {
val prefix = this.path.substring(0, this.path.length - this.name.length)
name = "$name.$newExtension"
File("${prefix}$name")
} else {
val prefix = this.path.substring(0, this.path.length - this.name.length)
name = name.substring(0, i + 1) + newExtension
File("${prefix}$name")
}
}
| core/src/main/kotlin/com/strumenta/kolasu/cli/ASTProcessingCommand.kt | 3305870721 |
package com.czbix.v2ex.inject
import com.czbix.v2ex.AppCtx
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import javax.inject.Singleton
@Singleton
@Component(
modules = [
AndroidInjectionModule::class,
AppModule::class,
DbModule::class,
ViewModelModule::class,
ActivityModule::class,
NightModeModule::class
]
)
interface AppComponent : AndroidInjector<AppCtx> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: AppCtx): Builder
fun build(): AppComponent
}
} | app/src/main/kotlin/com/czbix/v2ex/inject/AppComponent.kt | 932210175 |
package com.winterbe.expekt
/**
* @author Benjamin Winterberg
*/
class ExpectCollection<T>(subject: Collection<T>?, flavor: Flavor): ExpectAny<Collection<T>>(subject, flavor) {
private var anyMode = false
private var haveMode = false
val any: ExpectCollection<T> get() {
words.add("any")
anyMode = true
return this
}
val all: ExpectCollection<T> get() {
words.add("all")
anyMode = false
return this
}
override val have: ExpectCollection<T> get() {
words.add("have")
haveMode = true
return this
}
val contain: ExpectCollection<T> get() {
words.add("contain")
haveMode = false
return this
}
fun contain(other: T): ExpectCollection<T> {
words.add("contain")
words.add(other.toString())
verify { subject!!.contains(other) }
return this
}
fun elements(vararg elements: T): ExpectCollection<T> {
words.add("elements")
words.add(elements.toList().toString())
if (anyMode) {
verify { containsAny(elements) }
} else {
verify { containsAll(elements) }
}
return this
}
private fun containsAll(elements: Array<out T>): Boolean {
if (haveMode && elements.size != subject!!.size) {
return false
}
for (element in elements) {
if (!subject!!.contains(element)) {
return false
}
}
return true
}
private fun containsAny(elements: Array<out T>): Boolean {
// is the same for haveAny
for (element in elements) {
if (subject!!.contains(element)) {
return true
}
}
return false
}
val empty: ExpectCollection<T> get() {
words.add("empty")
verify { subject!!.isEmpty() }
return this
}
val size: ExpectComparable<Int> get() {
words.add("size")
val expectInt = ExpectComparable(subject!!.size, flavor)
expectInt.negated = negated
expectInt.words.addAll(words)
expectInt.words.removeAt(0)
expectInt.words.removeAt(0)
return expectInt
}
fun size(size: Int): ExpectCollection<T> {
words.add("size")
words.add(size.toString())
verify { subject!!.size == size }
return this
}
override val to: ExpectCollection<T> get() {
super.to
return this
}
override val be: ExpectCollection<T> get() {
super.be
return this
}
override val been: ExpectCollection<T> get() {
super.been
return this
}
override val that: ExpectCollection<T> get() {
super.that
return this
}
override val which: ExpectCollection<T> get() {
super.which
return this
}
override val and: ExpectCollection<T> get() {
super.and
return this
}
override val has: ExpectCollection<T> get() {
super.has
return this
}
override val with: ExpectCollection<T> get() {
super.with
return this
}
override val at: ExpectCollection<T> get() {
super.at
return this
}
override val a: ExpectCollection<T> get() {
super.a
return this
}
override val an: ExpectCollection<T> get() {
super.an
return this
}
override val of: ExpectCollection<T> get() {
super.of
return this
}
override val same: ExpectCollection<T> get() {
super.same
return this
}
override val the: ExpectCollection<T> get() {
super.the
return this
}
override val `is`: ExpectCollection<T> get() {
super.`is`
return this
}
override val not: ExpectCollection<T> get() {
super.not
return this
}
override val `null`: ExpectCollection<T> get() {
super.`null`
return this
}
override fun <S : Collection<T>> instanceof(type: Class<S>): ExpectCollection<T> {
super.instanceof(type)
return this
}
override fun identity(expected: Collection<T>?): ExpectCollection<T> {
super.identity(expected)
return this
}
override fun equal(expected: Collection<T>?): ExpectCollection<T> {
super.equal(expected)
return this
}
override fun satisfy(predicate: (Collection<T>) -> Boolean): ExpectCollection<T> {
super.satisfy(predicate)
return this
}
} | src/main/kotlin/com/winterbe/expekt/ExpectCollection.kt | 2459332385 |
package io.ktor.network.sockets
import io.ktor.network.selector.*
/**
* UDP socket builder
*/
public class UDPSocketBuilder(
private val selector: SelectorManager,
override var options: SocketOptions.UDPSocketOptions
) : Configurable<UDPSocketBuilder, SocketOptions.UDPSocketOptions> {
/**
* Bind server socket to listen to [localAddress].
*/
public fun bind(
localAddress: SocketAddress? = null,
configure: SocketOptions.UDPSocketOptions.() -> Unit = {}
): BoundDatagramSocket = bindUDP(selector, localAddress, options.udp().apply(configure))
/**
* Create a datagram socket to listen datagrams at [localAddress] and set to [remoteAddress].
*/
public fun connect(
remoteAddress: SocketAddress,
localAddress: SocketAddress? = null,
configure: SocketOptions.UDPSocketOptions.() -> Unit = {}
): ConnectedDatagramSocket = connectUDP(selector, remoteAddress, localAddress, options.udp().apply(configure))
public companion object
}
internal expect fun UDPSocketBuilder.Companion.connectUDP(
selector: SelectorManager,
remoteAddress: SocketAddress,
localAddress: SocketAddress?,
options: SocketOptions.UDPSocketOptions
): ConnectedDatagramSocket
internal expect fun UDPSocketBuilder.Companion.bindUDP(
selector: SelectorManager,
localAddress: SocketAddress?,
options: SocketOptions.UDPSocketOptions
): BoundDatagramSocket
| ktor-network/jvmAndNix/src/io/ktor/network/sockets/UDPSocketBuilder.kt | 3642922389 |
package eu.kanade.tachiyomi.widget.materialdialogs
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import eu.kanade.tachiyomi.databinding.DialogQuadstatemultichoiceItemBinding
private object CheckPayload
private object InverseCheckPayload
private object UncheckPayload
private object IndeterminatePayload
typealias QuadStateMultiChoiceListener = (indices: IntArray) -> Unit
// isAction state: Uncheck-> Check-> Invert else Uncheck-> Indeterminate (only if initial so)-> Check
// isAction for list of action to operate on like filter include, exclude
internal class QuadStateMultiChoiceDialogAdapter(
internal var items: List<CharSequence>,
disabledItems: IntArray?,
private var initialSelected: IntArray,
internal var listener: QuadStateMultiChoiceListener,
val isActionList: Boolean = true
) : RecyclerView.Adapter<QuadStateMultiChoiceViewHolder>() {
private val states = QuadStateTextView.State.values()
private var currentSelection: IntArray = initialSelected
set(value) {
val previousSelection = field
field = value
previousSelection.forEachIndexed { index, previous ->
val current = value[index]
when {
current == QuadStateTextView.State.CHECKED.ordinal && previous != QuadStateTextView.State.CHECKED.ordinal -> {
// This value was selected
notifyItemChanged(index, CheckPayload)
}
current == QuadStateTextView.State.INVERSED.ordinal && previous != QuadStateTextView.State.INVERSED.ordinal -> {
// This value was inverse selected
notifyItemChanged(index, InverseCheckPayload)
}
current == QuadStateTextView.State.UNCHECKED.ordinal && previous != QuadStateTextView.State.UNCHECKED.ordinal -> {
// This value was unselected
notifyItemChanged(index, UncheckPayload)
}
current == QuadStateTextView.State.INDETERMINATE.ordinal && previous != QuadStateTextView.State.INDETERMINATE.ordinal -> {
// This value was set back to Indeterminate
notifyItemChanged(index, IndeterminatePayload)
}
}
}
}
private var disabledIndices: IntArray = disabledItems ?: IntArray(0)
internal fun itemActionClicked(index: Int) {
val newSelection = this.currentSelection.toMutableList()
newSelection[index] = when (currentSelection[index]) {
QuadStateTextView.State.CHECKED.ordinal -> QuadStateTextView.State.INVERSED.ordinal
QuadStateTextView.State.INVERSED.ordinal -> QuadStateTextView.State.UNCHECKED.ordinal
// INDETERMINATE or UNCHECKED
else -> QuadStateTextView.State.CHECKED.ordinal
}
this.currentSelection = newSelection.toIntArray()
listener(currentSelection)
}
internal fun itemDisplayClicked(index: Int) {
val newSelection = this.currentSelection.toMutableList()
newSelection[index] = when (currentSelection[index]) {
QuadStateTextView.State.UNCHECKED.ordinal -> QuadStateTextView.State.CHECKED.ordinal
QuadStateTextView.State.CHECKED.ordinal -> when (initialSelected[index]) {
QuadStateTextView.State.INDETERMINATE.ordinal -> QuadStateTextView.State.INDETERMINATE.ordinal
else -> QuadStateTextView.State.UNCHECKED.ordinal
}
// INDETERMINATE or UNCHECKED
else -> QuadStateTextView.State.UNCHECKED.ordinal
}
this.currentSelection = newSelection.toIntArray()
listener(currentSelection)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): QuadStateMultiChoiceViewHolder {
return QuadStateMultiChoiceViewHolder(
itemBinding = DialogQuadstatemultichoiceItemBinding
.inflate(LayoutInflater.from(parent.context), parent, false),
adapter = this
)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(
holder: QuadStateMultiChoiceViewHolder,
position: Int
) {
holder.isEnabled = !disabledIndices.contains(position)
holder.controlView.state = states[currentSelection[position]]
holder.controlView.text = items[position]
}
override fun onBindViewHolder(
holder: QuadStateMultiChoiceViewHolder,
position: Int,
payloads: MutableList<Any>
) {
when (payloads.firstOrNull()) {
CheckPayload -> {
holder.controlView.state = QuadStateTextView.State.CHECKED
return
}
InverseCheckPayload -> {
holder.controlView.state = QuadStateTextView.State.INVERSED
return
}
UncheckPayload -> {
holder.controlView.state = QuadStateTextView.State.UNCHECKED
return
}
IndeterminatePayload -> {
holder.controlView.state = QuadStateTextView.State.INDETERMINATE
return
}
}
super.onBindViewHolder(holder, position, payloads)
}
}
| app/src/main/java/eu/kanade/tachiyomi/widget/materialdialogs/QuadStateMultiChoiceDialogAdapter.kt | 1761578795 |
package eu.kanade.tachiyomi.ui.browse.source.filter
import android.view.View
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.model.Filter
open class CheckboxItem(val filter: Filter.CheckBox) : AbstractFlexibleItem<CheckboxItem.Holder>() {
override fun getLayoutRes(): Int {
return R.layout.navigation_view_checkbox
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder {
return Holder(view, adapter)
}
override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>?) {
val view = holder.check
view.text = filter.name
view.isChecked = filter.state
holder.itemView.setOnClickListener {
view.toggle()
filter.state = view.isChecked
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return filter == (other as CheckboxItem).filter
}
override fun hashCode(): Int {
return filter.hashCode()
}
class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) {
val check: CheckBox = itemView.findViewById(R.id.nav_view_item)
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/filter/CheckboxItem.kt | 2853096564 |
package org.jetbrains.bio.viktor
import org.junit.Test
import kotlin.test.assertTrue
class NativeSpeedupTest {
@Test
fun nativeSpeedupEnabled() {
assertTrue(
Loader.nativeLibraryLoaded,
"""
Native optimizations disabled.
If running as a project: have you added -Djava.library.path=./build/libs to JVM options?
If running from a JAR: is your system supported?
"""
)
}
} | src/test/kotlin/org/jetbrains/bio/viktor/NativeSpeedupTest.kt | 977128616 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val S3_s3tc = "S3S3TC".nativeClassGL("S3_s3tc", postfix = S3TC) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows specifying texture data in compressed S3TC format.
"""
IntConstant(
"Accepted by the ??? parameter of ??? (presumably by the {@code format} argument of TexImage2D?.",
"RGB_S3TC"..0x83A0,
"RGB4_S3TC"..0x83A1,
"RGBA_S3TC"..0x83A2,
"RGBA4_S3TC"..0x83A3,
"RGBA_DXT5_S3TC"..0x83A4,
"RGBA4_DXT5_S3TC"..0x83A5
)
}
| modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/S3_s3tc.kt | 624828795 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity.internal
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
import org.hisp.dhis.android.core.trackedentity.ownership.ProgramOwner
import org.hisp.dhis.android.core.trackedentity.ownership.ProgramOwnerTableInfo
internal class ProgramOwnerChildrenAppender constructor(
private val childStore: ObjectWithoutUidStore<ProgramOwner>
) : ChildrenAppender<TrackedEntityInstance>() {
override fun appendChildren(tei: TrackedEntityInstance): TrackedEntityInstance {
val builder = tei.toBuilder()
val programOwners = childStore.selectWhere(
WhereClauseBuilder()
.appendKeyStringValue(ProgramOwnerTableInfo.Columns.TRACKED_ENTITY_INSTANCE, tei.uid())
.build()
)
return builder.programOwners(programOwners).build()
}
}
| core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/ProgramOwnerChildrenAppender.kt | 677195558 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.activities.habits.list.views
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.isoron.uhabits.activities.habits.list.MAX_CHECKMARK_COUNT
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.HabitMatcher
import org.isoron.uhabits.core.models.ModelObservable
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.ui.screens.habits.list.HabitCardListCache
import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsMenuBehavior
import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsSelectionMenuBehavior
import org.isoron.uhabits.core.utils.MidnightTimer
import org.isoron.uhabits.inject.ActivityScope
import java.util.LinkedList
import javax.inject.Inject
/**
* Provides data that backs a [HabitCardListView].
*
*
* The data if fetched and cached by a [HabitCardListCache]. This adapter
* also holds a list of items that have been selected.
*/
@ActivityScope
class HabitCardListAdapter @Inject constructor(
private val cache: HabitCardListCache,
private val preferences: Preferences,
private val midnightTimer: MidnightTimer
) : RecyclerView.Adapter<HabitCardViewHolder?>(),
HabitCardListCache.Listener,
MidnightTimer.MidnightListener,
ListHabitsMenuBehavior.Adapter,
ListHabitsSelectionMenuBehavior.Adapter {
val observable: ModelObservable = ModelObservable()
private var listView: HabitCardListView? = null
val selected: LinkedList<Habit> = LinkedList()
override fun atMidnight() {
cache.refreshAllHabits()
}
fun cancelRefresh() {
cache.cancelTasks()
}
fun hasNoHabit(): Boolean {
return cache.hasNoHabit()
}
/**
* Sets all items as not selected.
*/
override fun clearSelection() {
selected.clear()
notifyDataSetChanged()
observable.notifyListeners()
}
override fun getSelected(): List<Habit> {
return ArrayList(selected)
}
/**
* Returns the item that occupies a certain position on the list
*
* @param position position of the item
* @return the item at given position or null if position is invalid
*/
@Deprecated("")
fun getItem(position: Int): Habit? {
return cache.getHabitByPosition(position)
}
override fun getItemCount(): Int {
return cache.habitCount
}
override fun getItemId(position: Int): Long {
return getItem(position)!!.id!!
}
/**
* Returns whether list of selected items is empty.
*
* @return true if selection is empty, false otherwise
*/
val isSelectionEmpty: Boolean
get() = selected.isEmpty()
val isSortable: Boolean
get() = cache.primaryOrder == HabitList.Order.BY_POSITION
/**
* Notify the adapter that it has been attached to a ListView.
*/
fun onAttached() {
cache.onAttached()
midnightTimer.addListener(this)
}
override fun onBindViewHolder(
holder: HabitCardViewHolder,
position: Int
) {
if (listView == null) return
val habit = cache.getHabitByPosition(position)
val score = cache.getScore(habit!!.id!!)
val checkmarks = cache.getCheckmarks(habit.id!!)
val notes = cache.getNotes(habit.id!!)
val selected = selected.contains(habit)
listView!!.bindCardView(holder, habit, score, checkmarks, notes, selected)
}
override fun onViewAttachedToWindow(holder: HabitCardViewHolder) {
listView!!.attachCardView(holder)
}
override fun onViewDetachedFromWindow(holder: HabitCardViewHolder) {
listView!!.detachCardView(holder)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): HabitCardViewHolder {
val view = listView!!.createHabitCardView()
return HabitCardViewHolder(view)
}
/**
* Notify the adapter that it has been detached from a ListView.
*/
fun onDetached() {
cache.onDetached()
midnightTimer.removeListener(this)
}
override fun onItemChanged(position: Int) {
notifyItemChanged(position)
observable.notifyListeners()
}
override fun onItemInserted(position: Int) {
notifyItemInserted(position)
observable.notifyListeners()
}
override fun onItemMoved(oldPosition: Int, newPosition: Int) {
notifyItemMoved(oldPosition, newPosition)
observable.notifyListeners()
}
override fun onItemRemoved(position: Int) {
notifyItemRemoved(position)
observable.notifyListeners()
}
override fun onRefreshFinished() {
observable.notifyListeners()
}
/**
* Removes a list of habits from the adapter.
*
*
* Note that this only has effect on the adapter cache. The database is not
* modified, and the change is lost when the cache is refreshed. This method
* is useful for making the ListView more responsive: while we wait for the
* database operation to finish, the cache can be modified to reflect the
* changes immediately.
*
* @param selected list of habits to be removed
*/
override fun performRemove(selected: List<Habit>) {
for (habit in selected) cache.remove(habit.id!!)
}
/**
* Changes the order of habits on the adapter.
*
*
* Note that this only has effect on the adapter cache. The database is not
* modified, and the change is lost when the cache is refreshed. This method
* is useful for making the ListView more responsive: while we wait for the
* database operation to finish, the cache can be modified to reflect the
* changes immediately.
*
* @param from the habit that should be moved
* @param to the habit that currently occupies the desired position
*/
fun performReorder(from: Int, to: Int) {
cache.reorder(from, to)
}
override fun refresh() {
cache.refreshAllHabits()
}
override fun setFilter(matcher: HabitMatcher) {
cache.setFilter(matcher)
}
/**
* Sets the HabitCardListView that this adapter will provide data for.
*
*
* This object will be used to generated new HabitCardViews, upon demand.
*
* @param listView the HabitCardListView associated with this adapter
*/
fun setListView(listView: HabitCardListView?) {
this.listView = listView
}
override var primaryOrder: HabitList.Order
get() = cache.primaryOrder
set(value) {
cache.primaryOrder = value
preferences.defaultPrimaryOrder = value
}
override var secondaryOrder: HabitList.Order
get() = cache.secondaryOrder
set(value) {
cache.secondaryOrder = value
preferences.defaultSecondaryOrder = value
}
/**
* Selects or deselects the item at a given position.
*
* @param position position of the item to be toggled
*/
fun toggleSelection(position: Int) {
val h = getItem(position) ?: return
val k = selected.indexOf(h)
if (k < 0) selected.add(h) else selected.remove(h)
notifyDataSetChanged()
}
init {
cache.setListener(this)
cache.setCheckmarkCount(
MAX_CHECKMARK_COUNT
)
cache.secondaryOrder = preferences.defaultSecondaryOrder
cache.primaryOrder = preferences.defaultPrimaryOrder
setHasStableIds(true)
}
}
| uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/list/views/HabitCardListAdapter.kt | 4086791587 |
import java.util.Stack
import kotlin.test.assertFalse
import kotlin.test.assertTrue
fun balancedBrackets(input: String, brackets: Map<Char, Char> = mapOf(']' to '[', ')' to '(', '}' to '{')) =
Stack<Char>().apply {
require(input.all { it in brackets.flatMap { (k, v) -> listOf(k, v) } })
input.forEach {
when {
it in brackets.values -> push(it)
isEmpty() || pop() != brackets[it] -> return false
}
}
}.isEmpty()
fun main(args: Array<String>) {
assertTrue(balancedBrackets("()[]{}(([])){[()][]}"))
assertFalse(balancedBrackets("())[]{}"))
assertFalse(balancedBrackets("[(])"))
}
| problems/balanced-brackets/balanced-brackets.kt | 3358496049 |
package com.utynote
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.utynote", appContext.packageName)
}
}
| app/src/androidTest/java/com/utynote/ExampleInstrumentedTest.kt | 2605723390 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.imports.internal.conflicts
import org.hisp.dhis.android.core.imports.internal.ImportConflict
internal object TrackedEntityInstanceNotFoundConflict : TrackerImportConflictItem {
private val regex: Regex = Regex("TrackedEntityInstance '(\\w{11})' not found.")
private fun description(trackedEntityInstanceUid: String) =
"Your entity $trackedEntityInstanceUid does not exist in the server"
override val errorCode: String = "E1063"
override fun matches(conflict: ImportConflict): Boolean {
return regex.matches(conflict.value())
}
override fun getTrackedEntityInstance(conflict: ImportConflict): String? {
return regex.find(conflict.value())?.groupValues?.get(1)
}
override fun getDisplayDescription(
conflict: ImportConflict,
context: TrackerImportConflictItemContext
): String {
return getTrackedEntityInstance(conflict)?.let { trackedEntityInstanceUid ->
description(trackedEntityInstanceUid)
}
?: conflict.value()
}
}
| core/src/main/java/org/hisp/dhis/android/core/imports/internal/conflicts/TrackedEntityInstanceNotFoundConflict.kt | 3155627005 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.dataset.internal
import dagger.Reusable
import io.reactivex.Single
import java.util.Date
import javax.inject.Inject
import org.hisp.dhis.android.core.category.CategoryOption
import org.hisp.dhis.android.core.category.CategoryOptionCollectionRepository
import org.hisp.dhis.android.core.category.CategoryOptionComboService
import org.hisp.dhis.android.core.dataset.DataSet
import org.hisp.dhis.android.core.dataset.DataSetCollectionRepository
import org.hisp.dhis.android.core.dataset.DataSetEditableStatus
import org.hisp.dhis.android.core.dataset.DataSetInstanceService
import org.hisp.dhis.android.core.dataset.DataSetNonEditableReason
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitService
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.PeriodType
import org.hisp.dhis.android.core.period.internal.ParentPeriodGenerator
import org.hisp.dhis.android.core.period.internal.PeriodHelper
@Reusable
@Suppress("TooManyFunctions")
internal class DataSetInstanceServiceImpl @Inject constructor(
private val dataSetCollectionRepository: DataSetCollectionRepository,
private val categoryOptionRepository: CategoryOptionCollectionRepository,
private val organisationUnitService: OrganisationUnitService,
private val periodHelper: PeriodHelper,
private val categoryOptionComboService: CategoryOptionComboService,
private val periodGenerator: ParentPeriodGenerator,
) : DataSetInstanceService {
override fun getEditableStatus(
dataSetUid: String,
periodId: String,
organisationUnitUid: String,
attributeOptionComboUid: String
): Single<DataSetEditableStatus> {
return Single.fromCallable {
blockingGetEditableStatus(
dataSetUid = dataSetUid,
periodId = periodId,
organisationUnitUid = organisationUnitUid,
attributeOptionComboUid = attributeOptionComboUid
)
}
}
@Suppress("ComplexMethod")
override fun blockingGetEditableStatus(
dataSetUid: String,
periodId: String,
organisationUnitUid: String,
attributeOptionComboUid: String
): DataSetEditableStatus {
val dataSet = dataSetCollectionRepository.uid(dataSetUid).blockingGet()
val period = periodHelper.getPeriodForPeriodId(periodId).blockingGet()
return when {
!blockingHasDataWriteAccess(dataSetUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.NO_DATASET_DATA_WRITE_ACCESS)
!blockingIsCategoryOptionHasDataWriteAccess(attributeOptionComboUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.NO_ATTRIBUTE_OPTION_COMBO_ACCESS)
!blockingIsPeriodInCategoryOptionRange(period, attributeOptionComboUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.PERIOD_IS_NOT_IN_ATTRIBUTE_OPTION_RANGE)
!blockingIsOrgUnitInCaptureScope(organisationUnitUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.ORGUNIT_IS_NOT_IN_CAPTURE_SCOPE)
!blockingIsAttributeOptionComboAssignToOrgUnit(attributeOptionComboUid, organisationUnitUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.ATTRIBUTE_OPTION_COMBO_NO_ASSIGN_TO_ORGUNIT)
!blockingIsPeriodInOrgUnitRange(period, organisationUnitUid) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.PERIOD_IS_NOT_IN_ORGUNIT_RANGE)
!blockingIsExpired(dataSet, period) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.EXPIRED)
!blockingIsClosed(dataSet, period) ->
DataSetEditableStatus.NonEditable(DataSetNonEditableReason.CLOSED)
else -> DataSetEditableStatus.Editable
}
}
fun blockingIsCategoryOptionHasDataWriteAccess(categoryOptionComboUid: String): Boolean {
val categoryOptions = getCategoryOptions(categoryOptionComboUid)
return categoryOptionComboService.blockingHasWriteAccess(categoryOptions)
}
fun blockingIsPeriodInCategoryOptionRange(period: Period, categoryOptionComboUid: String): Boolean {
val categoryOptions = getCategoryOptions(categoryOptionComboUid)
val dates = listOf(period.startDate(), period.endDate())
return dates.all { date ->
categoryOptionComboService.isInOptionRange(categoryOptions, date)
}
}
fun blockingIsOrgUnitInCaptureScope(orgUnitUid: String): Boolean {
return organisationUnitService.blockingIsInCaptureScope(orgUnitUid)
}
fun blockingIsAttributeOptionComboAssignToOrgUnit(
categoryOptionComboUid: String,
orgUnitUid: String
): Boolean {
return categoryOptionComboService.blockingIsAssignedToOrgUnit(
categoryOptionComboUid = categoryOptionComboUid,
orgUnitUid = orgUnitUid
)
}
fun blockingIsExpired(dataSet: DataSet, period: Period): Boolean {
val expiryDays = dataSet.expiryDays() ?: return false
val generatedPeriod = period.endDate()?.let { endDate ->
periodGenerator.generatePeriod(
periodType = PeriodType.Daily,
date = endDate,
offset = expiryDays - 1
)
}
return Date().after(generatedPeriod?.endDate())
}
fun blockingIsClosed(dataSet: DataSet, period: Period): Boolean {
val periodType = dataSet.periodType() ?: return true
val openFuturePeriods = dataSet.openFuturePeriods() ?: 0
val generatedPeriod = periodGenerator.generatePeriod(
periodType = periodType,
date = Date(),
offset = openFuturePeriods - 1
)
return period.endDate()?.before(generatedPeriod?.endDate()) ?: true
}
override fun hasDataWriteAccess(dataSetUid: String): Single<Boolean> {
return Single.just(blockingHasDataWriteAccess(dataSetUid))
}
fun blockingHasDataWriteAccess(dataSetUid: String): Boolean {
val dataSet = dataSetCollectionRepository.uid(dataSetUid).blockingGet() ?: return false
return dataSet.access().write() ?: false
}
fun blockingIsPeriodInOrgUnitRange(period: Period, orgUnitUid: String): Boolean {
return listOfNotNull(period.startDate(), period.endDate()).all { date ->
organisationUnitService.blockingIsDateInOrgunitRange(orgUnitUid, date)
}
}
private fun getCategoryOptions(attributeOptionComboUid: String): List<CategoryOption> {
return categoryOptionRepository
.byCategoryOptionComboUid(attributeOptionComboUid)
.blockingGet()
}
}
| core/src/main/java/org/hisp/dhis/android/core/dataset/internal/DataSetInstanceServiceImpl.kt | 4054813189 |
class SomeClass {
class SomeInternal
fun some(a : S<caret>)
}
// INVOCATION_COUNT: 1
// EXIST: SomeClass
// EXIST: SomeInternal
// EXIST: { lookupString:"String", tailText:" (kotlin)", icon: "org/jetbrains/kotlin/idea/icons/classKotlin.svg"}
// EXIST: IllegalStateException
// EXIST: StringBuilder
// EXIST_JAVA_ONLY: StringBuffer
// ABSENT: HTMLStyleElement
| plugins/kotlin/completion/tests/testData/basic/common/InParametersTypes.kt | 272837363 |
package adadawwq32q
import test.pack.one.downParameter
import test.pack.one.downUnder
fun callDown() {
val result = downParameter<caret>(downUnder())
} | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/returnAtEnd/GenericTypeArgument2.kt | 254839846 |
package com.github.sybila.checker
import java.io.PrintStream
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
object CheckerStats {
private val printInterval = 4000
private var output: PrintStream? = System.out
private val totalMapReduce = AtomicLong()
private val totalMapReduceSize = AtomicLong()
private val operator = AtomicReference<String>("none")
private val mapReduce = AtomicLong()
private val mapReduceSize = AtomicLong()
private val lastPrint = AtomicLong(System.currentTimeMillis())
fun reset(output: PrintStream?) {
this.output = output
lastPrint.set(System.currentTimeMillis())
mapReduce.set(0)
mapReduceSize.set(0)
}
fun setOperator(operator: String) {
this.operator.set(operator)
}
fun mapReduce(size: Long) {
val time = System.currentTimeMillis()
val last = lastPrint.get()
val calls = mapReduce.incrementAndGet()
val currentSize = mapReduceSize.addAndGet(size)
//CAS ensures only one thread will actually print something.
//We might lose one or two calls, but that really doesn't matter.
if (time > last + printInterval && lastPrint.compareAndSet(last, time)) {
mapReduce.set(0)
mapReduceSize.set(0)
output?.println("Map-Reduce: $calls calls. (avr. size: ${currentSize/calls})")
output?.println("Verification: ${operator.get()}")
}
//update global stats
totalMapReduce.incrementAndGet()
totalMapReduceSize.addAndGet(size)
}
fun printGlobal() {
val total = totalMapReduce.get()
val totalSize = totalMapReduceSize.get()
output?.println("Total Map-Reduce calls: $total")
output?.println("Average call size: ${totalSize/Math.max(1, total).toDouble()}")
}
} | src/main/kotlin/com/github/sybila/checker/CheckerStats.kt | 1171768560 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.CopyReferenceUtil.getElementsToCopy
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.ui.tabs.impl.TabLabel
import java.awt.datatransfer.StringSelection
abstract class CopyPathProvider : AnAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
val dataContext = e.dataContext
val editor = CommonDataKeys.EDITOR.getData(dataContext)
val project = e.project
e.presentation.isEnabledAndVisible = project != null
&& getQualifiedName(project, getElementsToCopy(editor, dataContext), editor, dataContext) != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = getEventProject(e)
val dataContext = e.dataContext
val editor = CommonDataKeys.EDITOR.getData(dataContext)
val customDataContext = createCustomDataContext(dataContext)
val elements = getElementsToCopy(editor, customDataContext)
project?.let {
val copy = getQualifiedName(project, elements, editor, customDataContext)
CopyPasteManager.getInstance().setContents(StringSelection(copy))
CopyReferenceUtil.setStatusBarText(project, IdeBundle.message("message.path.to.fqn.has.been.copied", copy))
CopyReferenceUtil.highlight(editor, project, elements)
}
}
private fun createCustomDataContext(dataContext: DataContext): DataContext {
val component = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(dataContext)
if (component !is TabLabel) return dataContext
val file = component.info.`object`
if (file !is VirtualFile) return dataContext
return SimpleDataContext.builder()
.setParent(dataContext)
.add(LangDataKeys.VIRTUAL_FILE, file)
.add(CommonDataKeys.VIRTUAL_FILE_ARRAY, arrayOf(file))
.build()
}
@NlsSafe
open fun getQualifiedName(project: Project, elements: List<PsiElement>, editor: Editor?, dataContext: DataContext): String? {
if (elements.isEmpty()) {
return getPathToElement(project, editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }, editor)
}
val refs =
elements
.mapNotNull { getPathToElement(project, (if (it is PsiFileSystemItem) it.virtualFile else it.containingFile?.virtualFile), editor) }
.ifEmpty { CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext)?.mapNotNull { getPathToElement(project, it, editor) } }
.orEmpty()
.filter { it.isNotBlank() }
return if (refs.isNotEmpty()) refs.joinToString("\n") else null
}
open fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?): String? = null
}
abstract class DumbAwareCopyPathProvider : CopyPathProvider(), DumbAware
class CopyAbsolutePathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?) = virtualFile?.presentableUrl
}
class CopyContentRootPathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project,
virtualFile: VirtualFile?,
editor: Editor?): String? {
return virtualFile?.let {
ProjectFileIndex.getInstance(project).getModuleForFile(virtualFile, false)?.let { module ->
ModuleRootManager.getInstance(module).contentRoots.mapNotNull { root ->
VfsUtilCore.getRelativePath(virtualFile, root)
}.singleOrNull()
}
}
}
}
class CopyFileWithLineNumberPathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project,
virtualFile: VirtualFile?,
editor: Editor?): String? {
return if (virtualFile == null) null
else editor?.let { CopyReferenceUtil.getVirtualFileFqn(virtualFile, project) + ":" + (editor.caretModel.logicalPosition.line + 1) }
}
}
class CopySourceRootPathProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?) =
virtualFile?.let {
VfsUtilCore.getRelativePath(virtualFile, ProjectFileIndex.getInstance(project).getSourceRootForFile(virtualFile) ?: return null)
}
}
class CopyTBXReferenceProvider : CopyPathProvider() {
override fun getQualifiedName(project: Project,
elements: List<PsiElement>,
editor: Editor?,
dataContext: DataContext): String? =
CopyTBXReferenceAction.createJetBrainsLink(project, elements, editor)
}
class CopyFileNameProvider : DumbAwareCopyPathProvider() {
override fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?): String? = virtualFile?.name
} | platform/lang-impl/src/com/intellij/ide/actions/CopyPathProvider.kt | 1369168632 |
import java.util.ArrayList
internal class C<T> {
fun foo1(src: Collection<T>) {
val t = src.iterator().next()
}
fun foo2(src: ArrayList<out T>) {
val t = src.iterator().next()
}
fun foo3(dst: MutableCollection<in T>, t: T) {
dst.add(t)
}
fun foo4(comparable: Comparable<T>, t: T): Int {
return comparable.compareTo(t)
}
fun foo5(w: Collection<*>) {}
}
| plugins/kotlin/j2k/old/tests/testData/fileOrElement/projections/projections.kt | 1557422684 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.