path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
data/src/main/java/com/chun/data/model/Schedules.kt | nchungdev | 398,720,732 | false | null | package com.chun.data.model
import com.google.gson.annotations.SerializedName
open class Schedules<T> {
@SerializedName("monday", alternate = ["tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"])
var data: ArrayList<T>? = null
}
| 0 | Kotlin | 0 | 0 | 92a75c4304243f379f168ad4eb786de1028cc727 | 255 | AnimeDi | MIT License |
breathOfTheWild/src/main/kotlin/breathOfTheWild/critter/CrittersRouter.kt | adamWeesner | 239,233,558 | false | null | package breathOfTheWild.critter
import BaseRouter
import shared.zelda.Critter
import shared.zelda.responses.CrittersResponse
import kotlin.reflect.full.createType
data class CrittersRouter(
override val basePath: String,
override val service: CrittersService
) : BaseRouter<Critter, CrittersService>(
CrittersResponse(),
service,
Critter::class.createType()
)
| 1 | Kotlin | 1 | 1 | a04ad390fe844a7d89db2fa726599c23d3f796f6 | 382 | weesnerDevelopment | MIT License |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day07Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import java.util.*
private fun solution1(input: String): Long {
val directories = findDirectories(input)
return directories.entries.map { (_, size) -> size }.filter { it <= 100000 }.sum()
}
private fun solution2(input: String): Long {
val directories = findDirectories(input)
val rootSize = directories.getValue("/")
return directories.entries.map { (_, size) -> size }.sorted()
.first { 70000000L - rootSize + it >= 30000000L }
}
private fun findDirectories(input: String): Map<String, Long> {
val stack = Stack<Pair<String, Long>>()
val directories = mutableMapOf<String, Long>()
var currentDir = "/"
var currentSize = 0L
input.lineSequence().drop(1)
.filter { it.matches("(\\$ cd|\\d+) .*".toRegex()) }
.forEach { entry ->
if (entry == "$ cd ..") {
directories[currentDir] = currentSize
val (dir, size) = stack.pop()
currentDir = dir
currentSize += size
} else if (entry.startsWith("$ cd")) {
val newDir = entry.substring(5)
stack.push(currentDir to currentSize)
currentSize = 0L
currentDir += "/$newDir"
} else
currentSize += entry.takeWhile { it != ' ' }.toLong()
}
directories[currentDir] = currentSize
while (stack.isNotEmpty()) {
val (dir, size) = stack.pop()
currentDir = dir
currentSize += size
directories[currentDir] = currentSize
}
return directories
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 7
class Day07Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 95437L }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 1611443L }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 24933642L }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2086088L }
})
private val exampleInput =
"""
${'$'} cd /
${'$'} ls
dir a
14848514 b.txt
8504156 c.dat
dir d
${'$'} cd a
${'$'} ls
dir e
29116 f
2557 g
62596 h.lst
${'$'} cd e
${'$'} ls
584 i
${'$'} cd ..
${'$'} cd ..
${'$'} cd d
${'$'} ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
""".trimIndent()
| 0 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,796 | adventofcode-kotlin | MIT License |
jetbrains-core/tst/software/aws/toolkits/jetbrains/services/codewhisperer/CodeWhispererClientAdaptorTest.kt | aws | 91,485,909 | false | null | // Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.codewhisperer
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.replaceService
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.doReturnConsecutively
import org.mockito.kotlin.mock
import org.mockito.kotlin.stub
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
import software.amazon.awssdk.services.codewhisperer.CodeWhispererClient
import software.amazon.awssdk.services.codewhisperer.model.ArtifactType
import software.amazon.awssdk.services.codewhisperer.model.CodeScanFindingsSchema
import software.amazon.awssdk.services.codewhisperer.model.CreateCodeScanRequest
import software.amazon.awssdk.services.codewhisperer.model.CreateCodeScanResponse
import software.amazon.awssdk.services.codewhisperer.model.CreateUploadUrlRequest
import software.amazon.awssdk.services.codewhisperer.model.CreateUploadUrlResponse
import software.amazon.awssdk.services.codewhisperer.model.GetCodeScanRequest
import software.amazon.awssdk.services.codewhisperer.model.GetCodeScanResponse
import software.amazon.awssdk.services.codewhisperer.model.ListCodeScanFindingsRequest
import software.amazon.awssdk.services.codewhisperer.model.ListCodeScanFindingsResponse
import software.amazon.awssdk.services.codewhisperer.model.ListRecommendationsRequest
import software.amazon.awssdk.services.codewhisperer.model.ProgrammingLanguage
import software.amazon.awssdk.services.codewhisperer.paginators.ListRecommendationsIterable
import software.amazon.awssdk.services.codewhispererruntime.CodeWhispererRuntimeClient
import software.amazon.awssdk.services.codewhispererruntime.model.CodeAnalysisStatus
import software.amazon.awssdk.services.codewhispererruntime.model.Completion
import software.amazon.awssdk.services.codewhispererruntime.model.CreateArtifactUploadUrlRequest
import software.amazon.awssdk.services.codewhispererruntime.model.CreateArtifactUploadUrlResponse
import software.amazon.awssdk.services.codewhispererruntime.model.GenerateCompletionsRequest
import software.amazon.awssdk.services.codewhispererruntime.model.GenerateCompletionsResponse
import software.amazon.awssdk.services.codewhispererruntime.model.GetCodeAnalysisRequest
import software.amazon.awssdk.services.codewhispererruntime.model.GetCodeAnalysisResponse
import software.amazon.awssdk.services.codewhispererruntime.model.ListCodeAnalysisFindingsRequest
import software.amazon.awssdk.services.codewhispererruntime.model.ListCodeAnalysisFindingsResponse
import software.amazon.awssdk.services.codewhispererruntime.model.Reference
import software.amazon.awssdk.services.codewhispererruntime.model.Span
import software.amazon.awssdk.services.codewhispererruntime.model.StartCodeAnalysisRequest
import software.amazon.awssdk.services.codewhispererruntime.model.StartCodeAnalysisResponse
import software.amazon.awssdk.services.ssooidc.SsoOidcClient
import software.aws.toolkits.core.TokenConnectionSettings
import software.aws.toolkits.core.utils.test.aString
import software.aws.toolkits.jetbrains.core.MockClientManagerRule
import software.aws.toolkits.jetbrains.core.credentials.AwsBearerTokenConnection
import software.aws.toolkits.jetbrains.core.credentials.BearerSsoConnection
import software.aws.toolkits.jetbrains.core.credentials.ManagedSsoProfile
import software.aws.toolkits.jetbrains.core.credentials.MockCredentialManagerRule
import software.aws.toolkits.jetbrains.core.credentials.MockToolkitAuthManagerRule
import software.aws.toolkits.jetbrains.core.credentials.ToolkitConnectionManager
import software.aws.toolkits.jetbrains.core.credentials.sono.SONO_REGION
import software.aws.toolkits.jetbrains.services.codewhisperer.CodeWhispererTestUtil.metadata
import software.aws.toolkits.jetbrains.services.codewhisperer.CodeWhispererTestUtil.pythonRequest
import software.aws.toolkits.jetbrains.services.codewhisperer.CodeWhispererTestUtil.pythonResponse
import software.aws.toolkits.jetbrains.services.codewhisperer.CodeWhispererTestUtil.sdkHttpResponse
import software.aws.toolkits.jetbrains.services.codewhisperer.credentials.CodeWhispererClientAdaptor
import software.aws.toolkits.jetbrains.services.codewhisperer.credentials.CodeWhispererClientAdaptorImpl
class CodeWhispererClientAdaptorTest {
val projectRule = ProjectRule()
val disposableRule = DisposableRule()
val mockClientManagerRule = MockClientManagerRule()
val mockCredentialRule = MockCredentialManagerRule()
val authManagerRule = MockToolkitAuthManagerRule()
@Rule
@JvmField
val ruleChain = RuleChain(projectRule, mockCredentialRule, mockClientManagerRule, disposableRule)
private lateinit var sigv4Client: CodeWhispererClient
private lateinit var bearerClient: CodeWhispererRuntimeClient
private lateinit var ssoClient: SsoOidcClient
private lateinit var sut: CodeWhispererClientAdaptor
private lateinit var connectionManager: ToolkitConnectionManager
@Before
fun setup() {
sut = CodeWhispererClientAdaptorImpl(projectRule.project)
ssoClient = mockClientManagerRule.create<SsoOidcClient>()
sigv4Client = mockClientManagerRule.create<CodeWhispererClient>().stub {
on { listRecommendationsPaginator(any<ListRecommendationsRequest>()) } doReturn listRecommendationsPaginatorRespone
on { createUploadUrl(any<CreateUploadUrlRequest>()) } doReturn createUploadUrlResponse
on { createCodeScan(any<CreateCodeScanRequest>()) } doReturn createCodeScanResponse
on { getCodeScan(any<GetCodeScanRequest>()) } doReturn getCodeScanResponse
on { listCodeScanFindings(any<ListCodeScanFindingsRequest>()) } doReturn listCodeScanFindingsResponse
}
bearerClient = mockClientManagerRule.create<CodeWhispererRuntimeClient>().stub {
on { createArtifactUploadUrl(any<CreateArtifactUploadUrlRequest>()) } doReturn createArtifactUploadUrlResponse
on { startCodeAnalysis(any<StartCodeAnalysisRequest>()) } doReturn startCodeAnalysisResponse
on { getCodeAnalysis(any<GetCodeAnalysisRequest>()) } doReturn getCodeAnalysisResponse
on { listCodeAnalysisFindings(any<ListCodeAnalysisFindingsRequest>()) } doReturn listCodeAnalysisFindingsResponse
}
val mockConnection = mock<BearerSsoConnection>()
whenever(mockConnection.getConnectionSettings()) doReturn mock<TokenConnectionSettings>()
connectionManager = mock {
on {
activeConnectionForFeature(any())
} doReturn authManagerRule.createConnection(ManagedSsoProfile("us-east-1", aString(), emptyList())) as AwsBearerTokenConnection
}
projectRule.project.replaceService(ToolkitConnectionManager::class.java, connectionManager, disposableRule.disposable)
}
@Test
fun `Sono region is us-east-1`() {
assertThat("us-east-1").isEqualTo(SONO_REGION)
}
@Test
fun `listRecommendationsPaginator - sigv4`() {
val request = pythonRequest
val response = pythonResponse
sigv4Client.stub { client ->
on { client.listRecommendations(any<ListRecommendationsRequest>()) } doReturnConsecutively listOf(
response.copy { it.nextToken("second") },
response.copy { it.nextToken("third") },
response.copy { it.nextToken(("")) }
)
}
val nextTokens = listOf("second", "third", "")
val responses = sut.listRecommendationsPaginator(request, true)
argumentCaptor<ListRecommendationsRequest>().apply {
responses.forEachIndexed { i, response ->
assertThat(response.nextToken()).isEqualTo(nextTokens[i])
response.recommendations().forEachIndexed { j, recommendation ->
assertThat(recommendation)
.usingRecursiveComparison()
.isEqualTo(pythonResponse.recommendations()[j])
}
}
verify(sigv4Client, times(3)).listRecommendations(capture())
verifyNoInteractions(bearerClient)
assertThat(this.firstValue.nextToken()).isEqualTo("")
assertThat(this.secondValue.nextToken()).isEqualTo("second")
assertThat(this.thirdValue.nextToken()).isEqualTo("third")
}
}
@Test
fun `listRecommendationsPaginator - bearer`() {
val request = pythonRequest
val response = generateCompletionsResponse
bearerClient.stub { client ->
on { client.generateCompletions(any<GenerateCompletionsRequest>()) } doReturnConsecutively listOf(
response.copy { it.nextToken("second") },
response.copy { it.nextToken("third") },
response.copy { it.nextToken(("")) }
)
}
val nextTokens = listOf("second", "third", "")
val responses = sut.listRecommendationsPaginator(request, false)
argumentCaptor<GenerateCompletionsRequest>().apply {
responses.forEachIndexed { i, response ->
assertThat(response.nextToken()).isEqualTo(nextTokens[i])
response.recommendations().forEachIndexed { j, recommendation ->
assertThat(recommendation)
.usingRecursiveComparison()
.isEqualTo(response.recommendations()[j])
}
}
verify(bearerClient, times(3)).generateCompletions(capture())
verifyNoInteractions(sigv4Client)
assertThat(this.firstValue.nextToken()).isEqualTo("")
assertThat(this.secondValue.nextToken()).isEqualTo("second")
assertThat(this.thirdValue.nextToken()).isEqualTo("third")
}
}
@Test
fun `createUploadUrl - sigv4`() {
val actual = sut.createUploadUrl(createUploadUrlRequest, true)
argumentCaptor<CreateUploadUrlRequest>().apply {
verify(sigv4Client).createUploadUrl(capture())
verifyNoInteractions(bearerClient)
assertThat(firstValue).isEqualTo(createUploadUrlRequest)
assertThat(actual).isSameAs(createUploadUrlResponse)
}
}
@Test
fun `createUploadUrl - bearer`() {
val actual = sut.createUploadUrl(createUploadUrlRequest, false)
argumentCaptor<CreateArtifactUploadUrlRequest>().apply {
verify(bearerClient).createArtifactUploadUrl(capture())
verifyNoInteractions(sigv4Client)
assertThat(actual).isInstanceOf(CreateUploadUrlResponse::class.java)
assertThat(actual).usingRecursiveComparison()
.comparingOnlyFields("uploadUrl", "uploadId")
.isEqualTo(createArtifactUploadUrlResponse)
}
}
@Test
fun `createCodeScan - sigv4`() {
val actual = sut.createCodeScan(createCodeScanRequest, true)
argumentCaptor<CreateCodeScanRequest>().apply {
verify(sigv4Client).createCodeScan(capture())
verifyNoInteractions(bearerClient)
assertThat(firstValue).isSameAs(createCodeScanRequest)
assertThat(actual).isSameAs(createCodeScanResponse)
}
}
@Test
fun `createCodeScan - bearer`() {
val actual = sut.createCodeScan(createCodeScanRequest, false)
argumentCaptor<StartCodeAnalysisRequest>().apply {
verify(bearerClient).startCodeAnalysis(capture())
verifyNoInteractions(sigv4Client)
assertThat(actual).isInstanceOf(CreateCodeScanResponse::class.java)
assertThat(actual).usingRecursiveComparison()
.comparingOnlyFields("jobId", "status", "errorMessage")
.isEqualTo(startCodeAnalysisResponse)
}
}
@Test
fun `getCodeScan - sigv4`() {
val actual = sut.getCodeScan(getCodeScanRequest, true)
argumentCaptor<GetCodeScanRequest>().apply {
verify(sigv4Client).getCodeScan(capture())
verifyNoInteractions(bearerClient)
assertThat(firstValue).isSameAs(getCodeScanRequest)
assertThat(actual).isSameAs(getCodeScanResponse)
}
}
@Test
fun `getCodeScan - bearer`() {
val actual = sut.getCodeScan(getCodeScanRequest, false)
argumentCaptor<GetCodeAnalysisRequest>().apply {
verify(bearerClient).getCodeAnalysis(capture())
verifyNoInteractions(sigv4Client)
assertThat(actual).isInstanceOf(GetCodeScanResponse::class.java)
assertThat(actual).usingRecursiveComparison()
.comparingOnlyFields("status", "errorMessage")
.isEqualTo(getCodeAnalysisResponse)
}
}
@Test
fun `listCodeScanFindings - sigv4`() {
val actual = sut.listCodeScanFindings(listCodeScanFindingsRequest, true)
argumentCaptor<ListCodeScanFindingsRequest>().apply {
verify(sigv4Client).listCodeScanFindings(capture())
verifyNoInteractions(bearerClient)
assertThat(firstValue).isSameAs(listCodeScanFindingsRequest)
assertThat(actual).isSameAs(listCodeScanFindingsResponse)
}
}
@Test
fun `listCodeScanFindings - bearer`() {
val actual = sut.listCodeScanFindings(listCodeScanFindingsRequest, false)
argumentCaptor<ListCodeAnalysisFindingsRequest>().apply {
verify(bearerClient).listCodeAnalysisFindings(capture())
verifyNoInteractions(sigv4Client)
assertThat(actual).isInstanceOf(ListCodeScanFindingsResponse::class.java)
assertThat(actual.codeScanFindings()).isEqualTo(listCodeAnalysisFindingsResponse.codeAnalysisFindings())
assertThat(actual.nextToken()).isEqualTo(listCodeAnalysisFindingsResponse.nextToken())
}
}
private companion object {
val generateCompletionsResponse = GenerateCompletionsResponse.builder()
.nextToken("")
.completions(
Completion.builder()
.content("foo")
.references(
Reference.builder()
.licenseName("123")
.url("456")
.recommendationContentSpan(
Span.builder()
.start(0)
.end(1)
.build()
)
.build()
)
.build()
)
.responseMetadata(metadata)
.sdkHttpResponse(sdkHttpResponse)
.build() as GenerateCompletionsResponse
val createCodeScanRequest = CreateCodeScanRequest.builder()
.artifacts(mapOf(ArtifactType.SOURCE_CODE to "foo"))
.clientToken("token")
.programmingLanguage(
ProgrammingLanguage.builder()
.languageName("python")
.build()
)
.build()
val createUploadUrlRequest = CreateUploadUrlRequest.builder()
.contentMd5("foo")
.artifactType(ArtifactType.SOURCE_CODE)
.build()
val getCodeScanRequest = GetCodeScanRequest.builder()
.jobId("jobid")
.build()
val listCodeScanFindingsRequest = ListCodeScanFindingsRequest.builder()
.codeScanFindingsSchema(CodeScanFindingsSchema.CODESCAN_FINDINGS_1_0)
.jobId("listCodeScanFindings - JobId")
.nextToken("nextToken")
.build()
val createArtifactUploadUrlResponse: CreateArtifactUploadUrlResponse = CreateArtifactUploadUrlResponse.builder()
.uploadUrl("url")
.uploadId("id")
.responseMetadata(metadata)
.sdkHttpResponse(sdkHttpResponse)
.build() as CreateArtifactUploadUrlResponse
val startCodeAnalysisResponse = StartCodeAnalysisResponse.builder()
.jobId("create-code-scan-user")
.status(CodeAnalysisStatus.COMPLETED)
.errorMessage("message")
.responseMetadata(metadata)
.sdkHttpResponse(sdkHttpResponse)
.build() as StartCodeAnalysisResponse
val getCodeAnalysisResponse = GetCodeAnalysisResponse.builder()
.status(CodeAnalysisStatus.PENDING)
.errorMessage("message")
.responseMetadata(metadata)
.sdkHttpResponse(sdkHttpResponse)
.build() as GetCodeAnalysisResponse
val listCodeAnalysisFindingsResponse = ListCodeAnalysisFindingsResponse.builder()
.codeAnalysisFindings("findings")
.nextToken("nextToken")
.responseMetadata(metadata)
.sdkHttpResponse(sdkHttpResponse)
.build() as ListCodeAnalysisFindingsResponse
private val listRecommendationsPaginatorRespone: ListRecommendationsIterable = mock()
private val createUploadUrlResponse: CreateUploadUrlResponse = mock()
private val createCodeScanResponse: CreateCodeScanResponse = mock()
private val getCodeScanResponse: GetCodeScanResponse = mock()
private val listCodeScanFindingsResponse: ListCodeScanFindingsResponse = mock()
}
}
| 306 | Kotlin | 141 | 643 | 09faf6a4bff65b80c5306a0dc0503b66f1e1aef9 | 17,845 | aws-toolkit-jetbrains | Apache License 2.0 |
src/jvmMain/kotlin/ess/papyrus/StringTable.kt | jfmherokiller | 366,592,978 | false | null | /*
* Copyright 2016 <NAME>.
*
* 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 ess.papyrus
import PlatformByteBuffer
import ess.ESS.ESSContext
import ess.WStringElement
import java.nio.BufferUnderflowException
/**
* An abstraction describing a string table.
*
* @author <NAME>
*/
class StringTable : ArrayList<TString?>, PapyrusElement {
/**
* Creates a new `TString` by reading from a
* `ByteBuffer`. No error handling is performed.
*
* @param input The input stream.
* @return The new `TString`.
* @throws PapyrusFormatException
*/
@Throws(PapyrusFormatException::class)
fun read(input: PlatformByteBuffer): TString? {
var index: Int
if (STR32) {
// SkyrimSE, Fallout4, and SkyrimLE with CrashFixes uses 32bit string indices.
index = input.getInt()
} else {
index = UtilityFunctions.toUnsignedInt(input.getShort())
// SkyrimLegendary and Fallout4 use 16bit string indices.
// Various corrections are possible though.
if (index == 0xFFFF && !STBCORRECTION) {
index = input.getInt()
}
}
if (index < 0 || index >= this.size) {
throw PapyrusFormatException(String.format("Invalid TString index: %d / %d", index, this.size))
}
return get(index)
}
/**
* Creates a new `StringTable` by reading from a
* `ByteBuffer`. No error handling is performed.
*
* @param input The input stream.
* @param context The `ESSContext` info.
* @throws PapyrusElementException
*/
constructor(input: PlatformByteBuffer, context: ESSContext) {
STR32 = context.isStr32
var strCount: Int
if (STR32) {
// SkyrimSE uses 32bit string indices.
strCount = input.getInt()
STBCORRECTION = false
} else {
// Skyrim Legendary (without CrashFixes) and old versions of
// Fallout4 use 16bit string indices.
// Various corrections are possible though.
strCount = UtilityFunctions.toUnsignedInt(input.getShort())
// Large string table version.
if (strCount == 0xFFFF) {
strCount = input.getInt()
}
// Fallback for catching the stringtable bug.
if (context.game!!.isFO4 && strCount < 7000 || context.game!!.isSkyrim && strCount < 20000) {
strCount = strCount or 0x10000
STBCORRECTION = true
} else {
STBCORRECTION = false
}
}
// Store the string count.
STRCOUNT = strCount
// Read the actual strings.
try {
ensureCapacity(strCount)
for (i in 0 until strCount) {
try {
val WSTR = WStringElement.read(input)
val TSTR = if (STR32) TString32(WSTR, i) else TString16(this, WSTR, i)
this.add(TSTR)
} catch (ex: BufferUnderflowException) {
throw PapyrusException("Error reading string #$i", ex, null)
}
}
} catch (ex: BufferUnderflowException) {
isTruncated = true
val msg = String.format("Error; read %d/%d strings.", this.size, strCount)
throw PapyrusElementException(msg, ex, this)
}
isTruncated = false
}
/**
* Creates an empty `StringTable` with the truncated flag.
*/
constructor() {
STBCORRECTION = false
STR32 = false
isTruncated = true
STRCOUNT = 0
}
/**
* @see ess.Element.write
* @param output The output stream.
*/
override fun write(output: PlatformByteBuffer?) {
check(!STBCORRECTION) { "String-Table-Bug correction in effect. Cannot write." }
check(!isTruncated) { "StringTable is truncated. Cannot write." }
if (STR32) {
// SkyrimSE uses 32bit string indices.
output?.putInt(this.size)
} else // SkyrimLegendary and Fallout4 use 16bit string indices.
// Various corrections are possible though.
// Large string table version.
{
if (this.size > 0xFFF0 && !STBCORRECTION) {
output?.putShort(0xFFFF.toShort())
output?.putInt(this.size)
} else {
output?.putShort(this.size.toShort())
}
}
// Write the actual strings.
this.forEach { tstr: TString? -> tstr?.writeFull(output) }
}
/**
* @see ess.Element.calculateSize
* @return The size of the `Element` in bytes.
*/
override fun calculateSize(): Int {
var sum = 0
sum += if (STR32) {
4
} else if (this.size > 0xFFF0 && !STBCORRECTION) {
6
} else {
2
}
var result = 0
for (tString in this) {
val calculateFullSize = tString?.calculateFullSize()
if (calculateFullSize != null) {
result += calculateFullSize
}
}
sum += result
return sum
}
/**
*
* @param str
* @return
*/
fun resolve(str: String?): TString? {
for (tstr in this) {
if (tstr?.equals(str) == true) {
return tstr
}
}
return null
}
/**
* Checks if the `StringTable` contains a `TString`
* that matches a specified string value.
*
* @param val The value to match against.
* @return True if the `StringTable` contains a matching
* `TString`, false otherwise.
*/
fun containsMatching(`val`: String?): Boolean {
for (v in this) {
if (v != null) {
if (v.equals(`val`)) {
return true
}
}
}
return false
}
/**
* Adds a new string to the `StringTable` and returns the
* corresponding `TString`.
*
* @param val The value of the new string.
* @return The new `TString`, or the existing one if the
* `StringTable` already contained a match.
*/
fun addString(`val`: String?): TString {
var match: TString? = null
for (v in this) {
if (v?.equals(`val`) == true) {
match = v
break
}
}
if (match != null) {
return match
}
val tstr = if (STR32) TString32(`val`, this.size) else TString16(this, `val`, this.size)
this.add(tstr)
return tstr
}
/**
* A flag indicating that the string-table-bug correction is in effect. This
* means that the table is NOT SAVABLE.
*
* @return
*/
fun hasSTB(): Boolean {
return STBCORRECTION
}
/**
* @return For a truncated `StringTable` returns the number of
* missing strings. Otherwise returns 0.
*/
val missingCount: Int
get() = STRCOUNT - this.size
/**
* A flag indicating that the string-table-bug correction is in effect.
*/
val STBCORRECTION: Boolean
/**
* @return A flag indicating that the string table is truncated.
*/
/**
* Stores the truncated condition.
*/
val isTruncated: Boolean
/**
* Stores the parsing context information.
*/
private val STR32: Boolean
/**
* Stores the declared string table size. If the `StringTable` is
* truncated, this will not actually match the size of the list.
*/
private val STRCOUNT: Int
} | 0 | Kotlin | 0 | 0 | cff93de2d16b33afc4cc046347d856cb6281795a | 8,255 | ResaverResaved | Apache License 2.0 |
exceptions/src/main/java/com/kylecorry/andromeda/exceptions/StackTraceBugReportGenerator.kt | kylecorry31 | 394,273,851 | false | {"Kotlin": 838369, "Python": 307} | package com.kylecorry.andromeda.exceptions
import android.content.Context
class StackTraceBugReportGenerator : IBugReportGenerator {
override fun generate(context: Context, throwable: Throwable): String {
val message = throwable.message ?: ""
val stackTrace = throwable.stackTraceToString()
return "Message: ${message}\n\n$stackTrace"
}
} | 43 | Kotlin | 4 | 21 | 0bc951ae92aa706bc8bbd742dc7b4a2ebc71152a | 372 | andromeda | MIT License |
kotlin-electron/src/jsMain/generated/electron/main/PushNotifications.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron.main
typealias PushNotifications = electron.core.PushNotifications
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 139 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/albuquerque/cryptoe_wallet/core/holder/BaseViewHolder.kt | rebecaalbuquerque | 286,322,724 | false | null | package com.albuquerque.cryptoe_wallet.core.holder
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
/**
* Custom class that simplify the use a an ViewHolder for DataBinding usage.
* */
abstract class BaseViewHolder<T>(var binding: ViewDataBinding): RecyclerView.ViewHolder(binding.root), IBindView<T> {
abstract override fun bind(item: T)
} | 0 | Kotlin | 0 | 0 | 6e8e78a9931d271d529f068c498a1748a813e12f | 394 | android-crypto-e-wallet | MIT License |
features/labs/src/main/java/com/keelim/labs/ui/motion/MotionActivity.kt | keelim | 202,127,420 | false | null | /*
* Designed and developed by 2021 keelim (Jaehyun Kim)
*
* 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.keelim.labs.ui.motion
import android.os.Bundle
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import com.keelim.cnubus.labs.databinding.ActivityMotionBinding
class MotionActivity : AppCompatActivity() {
private val binding by lazy { ActivityMotionBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.container.setOnTouchListener { _, motion: MotionEvent ->
handleTouch(motion)
true
}
}
private fun handleTouch(m: MotionEvent) {
val pointerCount = m.pointerCount
for (i in 0 until pointerCount) {
val x = m.x
val y = m.y
val id = m.getPointerId(i)
val action = m.actionMasked
val actionIndex = m.actionIndex
var actionString: String = when (action) {
MotionEvent.ACTION_DOWN -> "Down"
MotionEvent.ACTION_UP -> "Up"
MotionEvent.ACTION_POINTER_DOWN -> "Pointer Down"
MotionEvent.ACTION_POINTER_UP -> "Pointer Up"
MotionEvent.ACTION_MOVE -> "MOVE"
else -> ""
}
val state = "Action $actionString Index $actionIndex Id: X: $x Y: $y"
if (id == 0) {
binding.textView1.text = state
} else {
binding.textView2.text = state
}
}
}
}
| 6 | Kotlin | 0 | 1 | 836c7fca6793ed74249f9430c798466b1a7aaa27 | 2,154 | project_cnuBus | Apache License 2.0 |
src/main/kotlin/aoc2017/FractalArt.kt | komu | 113,825,414 | false | null | package komu.adventofcode.aoc2017
import komu.adventofcode.utils.nonEmptyLines
fun fractalArt(input: String, iterations: Int): Int {
val rules = RuleBook.parse(input)
var block = Block(listOf(".#.", "..#", "###"))
repeat(iterations) {
block = block.enhance(rules)
}
return block.pixelsOnCount
}
private class RuleBook(private val rules: List<Rule>) {
fun findReplacement(fingerprint: Fingerprint) =
rules.find { it.matches(fingerprint) }?.output ?: error("no matching rule for $fingerprint")
companion object {
fun parse(input: String) = RuleBook(input.nonEmptyLines().map(Rule.Companion::parse))
}
}
private class Block private constructor(val size: Int) {
private val grid = Array(size) { CharArray(size) }
constructor(lines: List<String>) : this(lines.size) {
lines.forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
grid[y][x] = c
}
}
}
val pixelsOnCount: Int
get() = grid.sumBy { r -> r.count { it == '#' } }
override fun toString() = buildString {
for (line in grid)
appendLine(String(line))
}
fun enhance(rules: RuleBook) = when {
size % 2 == 0 -> enhance(rules, 2, 3)
size % 3 == 0 -> enhance(rules, 3, 4)
else -> error("invalid size $size")
}
private fun enhance(rules: RuleBook, mod: Int, newMod: Int): Block {
val parts = size / mod
val enhanced = Block(parts * newMod)
for (y in 0 until parts) {
for (x in 0 until parts) {
val fingerprint = fingerprint(x * mod, y * mod, mod)
val replacement = rules.findReplacement(fingerprint)
enhanced.copyFrom(x * newMod, y * newMod, replacement)
}
}
return enhanced
}
private fun fingerprint(x: Int, y: Int, size: Int) = buildString {
for (yy in y until y + size)
for (xx in x until x + size)
append(grid[yy][xx])
}
private fun copyFrom(x: Int, y: Int, block: Block) {
for (yy in 0 until block.size)
for (xx in 0 until block.size) {
val v = block.grid[yy][xx]
grid[yy + y][xx + x] = v
}
}
}
private typealias Fingerprint = String
private class Rule(permutationIndices: List<List<Int>>, private val pattern: String, val output: Block) {
private val permutations = permutationIndices.map { indices ->
indices.map { pattern[it] }.joinToString("")
}.toSet()
fun matches(fingerprint: Fingerprint) = fingerprint in permutations
companion object {
private val permutations2x2 =
digitLists("0123", "2031", "2310", "1203", "1032", "2301", "3210")
private val permutations3x3 = run {
val rots = digitLists("012345678", "630741852", "876543210", "258147036")
val flips = digitLists("012345678", "210543876", "678345012", "876543210")
rots.flatMap { rot -> flips.map { flip -> rot.map { flip[it] } } }
}
private val regex = Regex("(.+) => (.+)")
fun parse(input: String): Rule {
val m = regex.matchEntire(input) ?: error("invalid input '$input'")
val pattern = m.groupValues[1].split('/').joinToString("")
val replacement = Block(m.groupValues[2].split('/'))
return when (pattern.length) {
4 -> Rule(permutations2x2, pattern, replacement)
9 -> Rule(permutations3x3, pattern, replacement)
else -> error("invalid pattern '$pattern'")
}
}
private fun digitLists(vararg s: String): List<List<Int>> =
s.map { r -> r.map { it.toInt() - '0'.toInt() } }
}
}
| 0 | Kotlin | 0 | 0 | f07e74761d742c519fef4ba06fa474f1016bdbbd | 3,809 | advent-of-code | MIT License |
azure-communication-ui/calling/src/main/java/com/azure/android/communication/ui/calling/redux/reducer/ToastNotificationReducer.kt | Azure | 429,521,705 | false | {"Kotlin": 2573728, "Java": 167445, "Shell": 3964, "HTML": 1856} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.calling.redux.reducer
import com.azure.android.communication.ui.calling.redux.action.Action
import com.azure.android.communication.ui.calling.redux.action.ToastNotificationAction
import com.azure.android.communication.ui.calling.redux.state.ToastNotificationState
internal interface ToastNotificationReducer : Reducer<ToastNotificationState>
internal class ToastNotificationReducerImpl : ToastNotificationReducer {
override fun reduce(state: ToastNotificationState, action: Action): ToastNotificationState {
return when (action) {
is ToastNotificationAction.ShowNotification -> {
state.copy(kind = action.kind)
}
is ToastNotificationAction.DismissNotification -> {
state.copy(kind = null)
}
else -> state
}
}
}
| 6 | Kotlin | 27 | 24 | 96a897fb62cf8ce39a30f8bb7232df8aa888e084 | 970 | communication-ui-library-android | MIT License |
azure-communication-ui/calling/src/main/java/com/azure/android/communication/ui/calling/redux/reducer/ToastNotificationReducer.kt | Azure | 429,521,705 | false | {"Kotlin": 2573728, "Java": 167445, "Shell": 3964, "HTML": 1856} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.calling.redux.reducer
import com.azure.android.communication.ui.calling.redux.action.Action
import com.azure.android.communication.ui.calling.redux.action.ToastNotificationAction
import com.azure.android.communication.ui.calling.redux.state.ToastNotificationState
internal interface ToastNotificationReducer : Reducer<ToastNotificationState>
internal class ToastNotificationReducerImpl : ToastNotificationReducer {
override fun reduce(state: ToastNotificationState, action: Action): ToastNotificationState {
return when (action) {
is ToastNotificationAction.ShowNotification -> {
state.copy(kind = action.kind)
}
is ToastNotificationAction.DismissNotification -> {
state.copy(kind = null)
}
else -> state
}
}
}
| 6 | Kotlin | 27 | 24 | 96a897fb62cf8ce39a30f8bb7232df8aa888e084 | 970 | communication-ui-library-android | MIT License |
aoc16/day_03/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "OCaml": 82410, "Kotlin": 78968, "Go": 30927, "Makefile": 13967, "Roff": 9981, "Shell": 2098} | import java.io.File
fun isTriangle(sides: List<Int>): Boolean {
val (a, b, c) = sides
return a + b > c && a + c > b && b + c > a
}
fun vertical(chunk: List<String>, idx: Int): List<Int> =
chunk.map { it.trim().split("\\s+".toRegex()).get(idx).toInt() }
fun main() {
val lines = File("input").readLines()
val first = lines
.filter { isTriangle(it.trim().split("\\s+".toRegex()).map { it.toInt() }) }
.count()
println("First: $first")
val second = lines
.chunked(3)
.map { listOf(vertical(it, 0), vertical(it, 1), vertical(it, 2)) }
.flatten()
.filter { isTriangle(it) }
.count()
println("Second: $second")
}
| 0 | Rust | 1 | 0 | a85327c981794f2688f82cd8db703acbab2ff940 | 700 | advent-of-code | MIT License |
src/main/kotlin/no/nav/syfo/sykmelding/service/OppdaterTopicsService.kt | navikt | 247,334,648 | false | null | package no.nav.syfo.sykmelding.service
import no.nav.syfo.log
import no.nav.syfo.model.ReceivedSykmelding
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
class OppdaterTopicsService(
private val kafkaProducerReceivedSykmelding: KafkaProducer<String, ReceivedSykmelding>,
private val sm2013AutomaticHandlingTopic: String
) {
fun oppdaterOKTopic(receivedSykmelding: ReceivedSykmelding) {
log.info("Skriver sykmelding med id {} til ok-topic", receivedSykmelding.sykmelding.id)
try {
kafkaProducerReceivedSykmelding.send(ProducerRecord(sm2013AutomaticHandlingTopic, receivedSykmelding.sykmelding.id, receivedSykmelding)).get()
} catch (e: Exception) {
log.error("Noe gikk galt ved skriving til OK-topic: {}", e.cause)
throw e
}
}
}
| 0 | Kotlin | 0 | 0 | 9751a00f96e790703f0c66f88b529d15dec0cbe6 | 877 | egenmeldt-sykmelding-backend | MIT License |
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/sync/CredentialsInvalidItemsView.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} | package com.duckduckgo.autofill.sync
import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableStringBuilder
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.findViewTreeViewModelStoreOwner
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.autofill.api.AutofillScreens.AutofillSettingsScreen
import com.duckduckgo.autofill.api.AutofillSettingsLaunchSource
import com.duckduckgo.autofill.impl.R
import com.duckduckgo.autofill.impl.databinding.ViewCredentialsInvalidItemsWarningBinding
import com.duckduckgo.autofill.sync.CredentialsInvalidItemsViewModel.Command
import com.duckduckgo.autofill.sync.CredentialsInvalidItemsViewModel.Command.NavigateToCredentials
import com.duckduckgo.autofill.sync.CredentialsInvalidItemsViewModel.ViewState
import com.duckduckgo.common.ui.viewbinding.viewBinding
import com.duckduckgo.common.utils.ConflatedJob
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.common.utils.ViewViewModelFactory
import com.duckduckgo.di.scopes.ViewScope
import com.duckduckgo.navigation.api.GlobalActivityStarter
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@InjectWith(ViewScope::class)
class CredentialsInvalidItemsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
) : FrameLayout(context, attrs, defStyle) {
@Inject
lateinit var globalActivityStarter: GlobalActivityStarter
@Inject
lateinit var viewModelFactory: ViewViewModelFactory
@Inject
lateinit var dispatcherProvider: DispatcherProvider
private var coroutineScope: CoroutineScope? = null
private var job: ConflatedJob = ConflatedJob()
private val binding: ViewCredentialsInvalidItemsWarningBinding by viewBinding()
private val viewModel: CredentialsInvalidItemsViewModel by lazy {
ViewModelProvider(
findViewTreeViewModelStoreOwner()!!,
viewModelFactory
)[CredentialsInvalidItemsViewModel::class.java]
}
override fun onAttachedToWindow() {
AndroidSupportInjection.inject(this)
super.onAttachedToWindow()
findViewTreeLifecycleOwner()?.lifecycle?.addObserver(viewModel)
@SuppressLint("NoHardcodedCoroutineDispatcher")
coroutineScope = CoroutineScope(SupervisorJob() + dispatcherProvider.main())
viewModel.viewState()
.onEach { render(it) }
.launchIn(coroutineScope!!)
job += viewModel.commands()
.onEach { processCommands(it) }
.launchIn(coroutineScope!!)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
findViewTreeLifecycleOwner()?.lifecycle?.removeObserver(viewModel)
coroutineScope?.cancel()
job.cancel()
coroutineScope = null
}
private fun processCommands(command: Command) {
when (command) {
NavigateToCredentials -> navigateToCredentials()
}
}
private fun render(viewState: ViewState) {
this.isVisible = viewState.warningVisible
val spannable = SpannableStringBuilder(
context.resources.getQuantityString(
R.plurals.syncCredentialInvalidItemsWarning,
viewState.invalidItemsSize,
viewState.hint,
viewState.invalidItemsSize - 1,
),
).append(context.getText(R.string.syncCredentialInvalidItemsWarningLink))
binding.credentialsInvalidItemsWarning.setClickableLink(
"manage_passwords",
spannable,
onClick = {
viewModel.onWarningActionClicked()
},
)
}
private fun navigateToCredentials() {
globalActivityStarter.start(
this.context,
AutofillSettingsScreen(source = AutofillSettingsLaunchSource.Sync)
)
}
}
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 4,304 | DuckDuckGo | Apache License 2.0 |
core/src/main/kotlin/dev/komu/kraken/model/actions/RestAction.kt | komu | 83,556,775 | false | {"Kotlin": 225797} | package dev.komu.kraken.model.actions
import dev.komu.kraken.model.creature.Player
class RestAction(private val player: Player) : Action {
override fun perform(): ActionResult {
player.message("Resting...")
return ActionResult.Success
}
}
| 0 | Kotlin | 0 | 0 | 680362d8e27c475b4ef1e2d13b67cb87f67249f6 | 265 | kraken | Apache License 2.0 |
util/src/test/kotlin/io/github/zebalu/advent2020/ResourceReaderTest.kt | zebalu | 317,448,231 | false | null | package io.github.zebalu.adven2020
import kotlin.test.assertEquals
import org.junit.Test as test
import io.github.zebalu.advent2020.ResourceReader
class ResourceReaderTest {
@test fun readsAllLines() {
val lines = ResourceReader.lines("/test_1.txt")
assertEquals(3, lines.size)
}
@test fun readGroups() {
val groups = ResourceReader.lineGroups("/test_2.txt")
assertEquals(2, groups.size)
assertEquals(2, groups[0].size)
assertEquals(3, groups[1].size)
}
} | 0 | Kotlin | 0 | 1 | ca54c64a07755ba044440832ba4abaa7105cdd6e | 473 | advent2020 | Apache License 2.0 |
src/main/kotlin/com/marvinelsen/willow/sources/moe/MoeParser.kt | HalfAnAvocado | 717,460,519 | false | {"Kotlin": 79178, "CSS": 1408} | package com.marvinelsen.willow.sources.moe
import com.marvinelsen.willow.sources.common.Parser
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import java.io.InputStream
@OptIn(ExperimentalSerializationApi::class)
object MoeParser : Parser<MoeEntry> {
override fun parse(inputStream: InputStream) = Json.decodeFromStream<List<MoeEntry>>(inputStream)
}
| 15 | Kotlin | 0 | 5 | cd4f8e383ef56baf0a07d71cb015bbd5f1f29063 | 458 | willow | Apache License 2.0 |
src/test/io/github/config4k/TestToConfigForArbitraryGenericType.kt | hsyed | 125,596,516 | true | {"Kotlin": 52156, "Python": 449} | package io.github.config4k
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.it
class TestToConfigForArbitraryGenericType : Spek({
context("PetPerson>.toConfig") {
it("should return Config having PetPerson<Dog>") {
val person = PetPerson("foo", 20, Dog("woof")).toConfig("person")
person.extract<PetPerson<Dog>>("person") shouldBe PetPerson("foo", 20, Dog("woof"))
}
it("should return Config having PetPerson<Yeti>") {
val person = PetPerson("foo", 20, Yeti).toConfig("person")
person.extract<PetPerson<Yeti>>("person") shouldBe PetPerson("foo", 20, Yeti)
}
}
context("TwoPetPerson.toConfig") {
it("should return Config having TwoPetPerson<Dog, Cat>") {
val person = TwoPetPerson("foo", 20, Dog("woof"), Cat(7)).toConfig("person")
person.extract<TwoPetPerson<Dog, Cat>>("person") shouldBe TwoPetPerson("foo", 20, Dog("woof"), Cat(7))
}
it("should return Config having TwoPetPerson<Snake<Mouse>, Cat>") {
val person = TwoPetPerson("foo", 20, Snake(20, Mouse("Joe")), Cat(7)).toConfig("person")
person.extract<TwoPetPerson<Snake<Mouse>, Cat>>("person") shouldBe TwoPetPerson("foo", 20, Snake(20, Mouse("Joe")),
Cat(7))
}
}
}) | 0 | Kotlin | 0 | 0 | ec5117f26dec3efdbd9a54683a07ef6aedd3ea29 | 1,385 | config4k | Apache License 2.0 |
bjdui/src/main/kotlin/net/sonmoosans/bjdui/plugin/ui/hook/ButtonClick.kt | fuma-nama | 502,647,871 | false | {"Kotlin": 131688} | package net.sonmoosans.bjda.plugins.ui.hook
import net.sonmoosans.bjda.plugins.ui.UIEvent
import net.sonmoosans.bjda.plugins.ui.hook.event.ButtonListener
import net.sonmoosans.bjda.ui.core.hooks.Delegate
import net.sonmoosans.bjdui.types.AnyComponent
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent
import net.dv8tion.jda.api.interactions.components.buttons.ButtonInteraction
/**
* Create a Click Event Listener and returns its id
*/
class ButtonClick(
id: String = UIEvent.createId(),
private val handler: (event: ButtonInteractionEvent) -> Unit
) : EventHook(id), ButtonListener {
override fun onClick(event: ButtonInteractionEvent) {
handler(event)
}
override fun listen() {
UIEvent.listen(id, this)
}
override fun onDestroy() {
UIEvent.buttons.remove(id)
}
companion object {
/**
* Create and Use the hook and return its id as a delegate
*/
fun AnyComponent.onClick(id: String = UIEvent.createId(), handler: (event: ButtonInteractionEvent) -> Unit): Delegate<String> {
val hook = ButtonClick(id, handler)
return Delegate { this use hook }
}
/**
* Listen button events of specified id, but don't attach to any element
*
* @return button id
*/
fun onClickStatic(id: String, handler: (event: ButtonInteraction) -> Unit): String {
ButtonClick(id, handler).listen()
return id
}
}
} | 0 | Kotlin | 1 | 14 | 6a88eba7ced7e2392ce958289c9ba5e1141ad4f6 | 1,534 | B-JDA | MIT License |
kotlin-electron/src/jsMain/generated/electron/main/TouchBarPopover.kt | JetBrains | 93,250,841 | false | {"Kotlin": 11411371, "JavaScript": 154302} | package electron.main
typealias TouchBarPopover = electron.core.TouchBarPopover
| 28 | Kotlin | 173 | 1,250 | 9e9dda28cf74f68b42a712c27f2e97d63af17628 | 81 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/laurenyew/coxautomotiveapp/data/DealershipDao.kt | laurenyew | 208,376,361 | false | null | package laurenyew.coxautomotiveapp.data
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
/**
* Interface w/ Room to handle SQL Queries
*/
@Dao
interface DealershipDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(dealership: Dealership)
@Query("DELETE FROM dealership_table")
fun deleteAll()
@Query("SELECT * FROM dealership_table ORDER BY name ASC")
fun getAllDealerships(): LiveData<List<Dealership>>
} | 0 | Kotlin | 0 | 0 | 97ae04f4238b22e0fc903a9ec4c96b44efea1bd5 | 563 | CoxAutomotiveApp | MIT License |
missingdot/src/commonMain/kotlin/dev/atsushieno/missingdot/xml/XmlNodeType.kt | atsushieno | 398,649,969 | false | null | package dev.atsushieno.missingdot.xml
enum class XmlNodeType {
Document,
Doctype,
Element,
EndElement,
Attribute,
Text,
Comment,
ProcessingInstruction
} | 0 | Kotlin | 0 | 0 | c11ad24b0b9834c878ca5178ecbd2e9c71238278 | 161 | missing-dot | MIT License |
shared/src/main/java/com/devlomi/shared/common/Extensions.kt | 3llomi | 569,805,694 | false | {"Kotlin": 353465} | package com.devlomi.shared.common
import android.content.Context
import android.content.res.Configuration
import android.graphics.Paint
import android.graphics.Rect
import android.util.TypedValue
import com.batoulapps.adhan.CalculationParameters
import com.batoulapps.adhan.Coordinates
import com.batoulapps.adhan.Prayer
import com.batoulapps.adhan.PrayerTimes
import com.batoulapps.adhan.data.DateComponents
import com.google.android.gms.tasks.Task
import com.google.android.gms.wearable.DataMap
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.util.Calendar
import java.util.Locale
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
fun spToPx(sp: Float, context: Context): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
sp,
context.resources.displayMetrics
)
.toInt()
}
fun dpToPx(dp: Float, context: Context): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
context.resources.displayMetrics
).toInt()
}
fun String.getBounds(paint: Paint): Rect {
val rect = Rect()
paint.getTextBounds(this, 0, this.length, rect)
return rect
}
fun DataMap.getDoubleOrNull(key: String): Double? {
if (this.containsKey(key)) {
return this.getDouble(key)
}
return null
}
suspend fun <T> Task<T>.await(): T {
return suspendCancellableCoroutine { continuation ->
this.addOnCompleteListener {
if (it.exception != null) {
continuation.resumeWithException(it.exception!!)
} else {
continuation.resume(it.result)
}
}
}
}
fun Int.toHexColor() = String.format("#%08X", -0x1 and this)
fun DataMap.getBooleanOrNull(key: String) =
if (this.containsKey(key)) this.getBoolean(key) else null
fun DataMap.getIntOrNull(key: String) =
if (this.containsKey(key)) this.getInt(key) else null
fun PrayerTimes.previousPrayer(): Prayer {
return when (nextPrayer()) {
Prayer.NONE -> Prayer.NONE
Prayer.FAJR -> Prayer.ISHA
Prayer.SUNRISE -> Prayer.FAJR
Prayer.DHUHR -> Prayer.SUNRISE
Prayer.ASR -> Prayer.DHUHR
Prayer.MAGHRIB -> Prayer.ASR
Prayer.ISHA -> Prayer.MAGHRIB
}
}
fun getIshaaTimePreviousDay(
time: Long,
coordinates: Coordinates,
prayerTimesParams: CalculationParameters
): Long {
val cal = Calendar.getInstance()
cal.timeInMillis = time
cal.add(Calendar.DATE, -1)
return PrayerTimes(
coordinates,
DateComponents.from(cal.time),
prayerTimesParams
).timeForPrayer(Prayer.ISHA).time
}
fun Context.getLocaleStringResource(
locale: Locale,
resourceId: Int,
): String {
val config = Configuration(resources.configuration)
config.setLocale(locale)
return createConfigurationContext(config).getText(resourceId).toString()
}
fun InputStream.writeToFile(file: File) {
this.use { inputStream ->
file.outputStream().use { inputStream.copyTo(it) }
}
}
fun OutputStream.writeFromFile(file: File) {
this.use { outputStream ->
file.inputStream().use { inputStream ->
inputStream.copyTo(outputStream)
}
}
}
| 2 | Kotlin | 2 | 9 | d42a6c69d5013177274d127484696173d67ee33d | 3,336 | PrayerWatchFace | Apache License 2.0 |
spring/src/test/kotlin/controller/RatingsControllerTest.kt | crowdproj | 518,714,370 | false | null | package com.crowdproj.rating.spring.controller
import com.crowdproj.rating.api.v1.models.*
import com.crowdproj.rating.common.CwpRatingContext
import com.crowdproj.rating.mappers.*
import com.crowdproj.rating.stubs.CwpRatingStub
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
// Temporary simple test with stubs
@WebMvcTest(RatingsController::class)
internal class RatingsControllerTest {
@Autowired
private lateinit var mvc: MockMvc
@Autowired
private lateinit var mapper: ObjectMapper
@Test
fun createRating() = testStubRating(
"/api/v1/ratings/create",
RatingCreateRequest(),
CwpRatingContext().apply { ratingResponse = CwpRatingStub.get() }.toTransportCreate()
)
@Test
fun readRating() = testStubRating(
"/api/v1/ratings/read",
RatingReadRequest(),
CwpRatingContext().apply { ratingResponse = CwpRatingStub.get() }.toTransportRead()
)
@Test
fun updateRating() = testStubRating(
"/api/v1/ratings/update",
RatingUpdateRequest(),
CwpRatingContext().apply { ratingResponse = CwpRatingStub.get() }.toTransportUpdate()
)
@Test
fun deleteRating() = testStubRating(
"/api/v1/ratings/delete",
RatingDeleteRequest(),
CwpRatingContext().toTransportDelete()
)
@Test
fun searchRating() = testStubRating(
"/api/v1/ratings/search",
RatingSearchRequest(),
CwpRatingContext().apply { ratingsResponse.add(CwpRatingStub.get()) }.toTransportSearch()
)
private fun <Req : Any, Res : Any> testStubRating(
url: String,
requestObj: Req,
responseObj: Res,
) {
val request = mapper.writeValueAsString(requestObj)
val response = mapper.writeValueAsString(responseObj)
mvc.perform(
post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(request)
)
.andExpect(status().isOk)
.andExpect(content().json(response))
}
}
| 0 | Kotlin | 2 | 0 | 668859f333e9d397870f4492463dc948bdfea83a | 2,547 | crowdproj-ratings | Apache License 2.0 |
Android/app/src/main/java/ru/alexskvortsov/policlinic/domain/repository/DoctorProfileRepository.kt | AlexSkvor | 244,438,301 | false | null | package ru.alexskvortsov.policlinic.domain.repository
import io.reactivex.Completable
import io.reactivex.Observable
import ru.alexskvortsov.policlinic.data.storage.database.entities.CompetenceEntity
import ru.alexskvortsov.policlinic.domain.states.doctor.DoctorPerson
interface DoctorProfileRepository {
fun isLoginUnique(login: String): Observable<Boolean>
fun getDoctor(): Observable<DoctorPerson>
fun getAllCompetences(): Observable<List<CompetenceEntity>>
fun saveDoctor(person: DoctorPerson): Completable
} | 0 | Kotlin | 0 | 0 | 5cc6a10a1399ee08643e69308afd4626938882b0 | 530 | polyclinic | Apache License 2.0 |
Android/app/src/main/java/ru/alexskvortsov/policlinic/domain/repository/DoctorProfileRepository.kt | AlexSkvor | 244,438,301 | false | null | package ru.alexskvortsov.policlinic.domain.repository
import io.reactivex.Completable
import io.reactivex.Observable
import ru.alexskvortsov.policlinic.data.storage.database.entities.CompetenceEntity
import ru.alexskvortsov.policlinic.domain.states.doctor.DoctorPerson
interface DoctorProfileRepository {
fun isLoginUnique(login: String): Observable<Boolean>
fun getDoctor(): Observable<DoctorPerson>
fun getAllCompetences(): Observable<List<CompetenceEntity>>
fun saveDoctor(person: DoctorPerson): Completable
} | 0 | Kotlin | 0 | 0 | 5cc6a10a1399ee08643e69308afd4626938882b0 | 530 | polyclinic | Apache License 2.0 |
src/test/kotlin/g0001_0100/s0042_trapping_rain_water/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0042_trapping_rain_water
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun trap() {
assertThat(Solution().trap(intArrayOf(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)), equalTo(6))
}
@Test
fun trap2() {
assertThat(Solution().trap(intArrayOf(4, 2, 0, 3, 2, 5)), equalTo(9))
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 441 | LeetCode-in-Kotlin | MIT License |
app/src/main/java/com/femi/e_class/data/repository/base/BaseRepositoryImpl.kt | Vader-Femi | 569,005,599 | false | {"Kotlin": 164756} | package com.femi.e_class.data.repository.base
import com.femi.e_class.data.UserPreferences
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.CollectionReference
import kotlinx.coroutines.flow.first
import javax.inject.Inject
open class BaseRepositoryImpl @Inject constructor(
private val firebaseAuth: FirebaseAuth,
private val collectionReference: CollectionReference,
private val dataStore: UserPreferences
): BaseRepository {
override suspend fun userEmail(email: String) = dataStore.userEmail(email)
override suspend fun userEmail(): String = dataStore.userEmail.first()
override suspend fun userMatric(matric: Long) = dataStore.userMatric(matric)
override suspend fun userMatric(): Long = dataStore.userMatric.first()
override suspend fun userFName(fName: String) = dataStore.userFName(fName)
override suspend fun userFName(): String = dataStore.userFName.first()
override suspend fun userLName(lName: String) = dataStore.userLName(lName)
override suspend fun userLName(): String = dataStore.userLName.first()
override suspend fun videoResolution(resolution: Int) = dataStore.videoResolution(resolution)
override suspend fun videoResolution(): Int = dataStore.videoResolution.first()
override fun getAuthReference() = firebaseAuth
override fun getCollectionReference() = collectionReference
} | 0 | Kotlin | 0 | 1 | 2d9864966e47188927ebf7f5f180c56cce7c2482 | 1,403 | Class-Konnect | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Cello.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.Cello: ImageVector
get() {
if (_cello != null) {
return _cello!!
}
_cello = Builder(name = "Cello", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(23.707f, 1.707f)
curveToRelative(0.391f, -0.391f, 0.391f, -1.023f, 0.0f, -1.414f)
reflectiveCurveToRelative(-1.023f, -0.391f, -1.414f, 0.0f)
lineToRelative(-5.779f, 5.779f)
curveToRelative(-1.604f, -1.295f, -3.644f, -2.072f, -5.862f, -2.072f)
curveToRelative(-0.087f, 0.0f, -0.174f, 0.0f, -0.256f, 0.005f)
curveToRelative(-1.384f, 0.048f, -2.56f, 0.998f, -2.857f, 2.31f)
curveToRelative(-0.197f, 0.87f, -0.636f, 1.664f, -1.27f, 2.298f)
curveToRelative(-0.838f, 0.838f, -1.952f, 1.329f, -3.135f, 1.383f)
curveToRelative(-1.245f, 0.056f, -2.345f, 0.929f, -2.736f, 2.173f)
curveToRelative(-0.265f, 0.842f, -0.398f, 1.678f, -0.398f, 2.484f)
curveToRelative(0.0f, 2.218f, 0.777f, 4.257f, 2.072f, 5.862f)
lineToRelative(-1.779f, 1.779f)
curveToRelative(-0.391f, 0.391f, -0.391f, 1.023f, 0.0f, 1.414f)
curveToRelative(0.195f, 0.195f, 0.451f, 0.293f, 0.707f, 0.293f)
reflectiveCurveToRelative(0.512f, -0.098f, 0.707f, -0.293f)
lineToRelative(1.779f, -1.779f)
curveToRelative(1.604f, 1.295f, 3.644f, 2.072f, 5.862f, 2.072f)
curveToRelative(0.801f, 0.0f, 1.63f, -0.132f, 2.466f, -0.393f)
curveToRelative(1.271f, -0.396f, 2.17f, -1.566f, 2.188f, -2.847f)
curveToRelative(0.016f, -1.241f, 0.509f, -2.408f, 1.387f, -3.287f)
horizontalLineToRelative(0.0f)
curveToRelative(0.63f, -0.632f, 1.421f, -1.07f, 2.286f, -1.269f)
curveToRelative(1.343f, -0.307f, 2.321f, -1.499f, 2.325f, -2.857f)
curveToRelative(0.0f, -2.218f, -0.777f, -4.257f, -2.072f, -5.862f)
lineToRelative(5.779f, -5.779f)
close()
moveTo(18.0f, 13.362f)
curveToRelative(0.0f, 0.416f, -0.325f, 0.792f, -0.771f, 0.894f)
curveToRelative(-1.233f, 0.282f, -2.359f, 0.906f, -3.257f, 1.804f)
curveToRelative(-1.249f, 1.25f, -1.949f, 2.91f, -1.972f, 4.675f)
curveToRelative(-0.006f, 0.419f, -0.335f, 0.823f, -0.783f, 0.963f)
curveToRelative(-0.643f, 0.201f, -1.271f, 0.303f, -1.87f, 0.303f)
curveToRelative(-1.666f, 0.0f, -3.204f, -0.558f, -4.438f, -1.496f)
lineToRelative(1.797f, -1.797f)
curveToRelative(0.391f, -0.391f, 0.391f, -1.023f, 0.0f, -1.414f)
reflectiveCurveToRelative(-1.023f, -0.391f, -1.414f, 0.0f)
lineToRelative(-1.797f, 1.797f)
curveToRelative(-0.938f, -1.234f, -1.496f, -2.772f, -1.496f, -4.438f)
curveToRelative(0.0f, -0.603f, 0.104f, -1.237f, 0.307f, -1.884f)
curveToRelative(0.138f, -0.438f, 0.516f, -0.758f, 0.918f, -0.775f)
curveToRelative(1.684f, -0.076f, 3.267f, -0.774f, 4.459f, -1.967f)
curveToRelative(0.9f, -0.9f, 1.525f, -2.031f, 1.807f, -3.269f)
curveToRelative(0.094f, -0.414f, 0.514f, -0.738f, 0.981f, -0.755f)
lineToRelative(0.181f, -0.003f)
curveToRelative(1.666f, 0.0f, 3.204f, 0.557f, 4.437f, 1.496f)
lineToRelative(-5.797f, 5.797f)
curveToRelative(-0.391f, 0.391f, -0.391f, 1.023f, 0.0f, 1.414f)
curveToRelative(0.195f, 0.195f, 0.451f, 0.293f, 0.707f, 0.293f)
reflectiveCurveToRelative(0.512f, -0.098f, 0.707f, -0.293f)
lineToRelative(5.796f, -5.796f)
curveToRelative(0.939f, 1.236f, 1.497f, 2.778f, 1.497f, 4.451f)
close()
moveTo(17.0f, 1.5f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
close()
moveTo(24.0f, 5.5f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
close()
}
}
.build()
return _cello!!
}
private var _cello: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,644 | icons | MIT License |
src/main/kotlin/com/skillw/pouvoir/internal/hologram/HologramLine.kt | Glom-c | 396,683,163 | false | null | package com.skillw.pouvoir.internal.hologram
import io.netty.util.internal.ConcurrentSet
import org.bukkit.Location
import org.bukkit.entity.Player
import taboolib.module.chat.colored
private var index = 114514
private fun nextInt(): Int {
return index++
}
class HologramLine(location: Location, line: String) {
val viewers = ConcurrentSet<Player>()
constructor(location: Location, line: String, vararg viewers: Player) : this(location, line) {
this.viewers.addAll(viewers)
for (viewer in viewers) {
armorStand.visible(viewer, true)
}
}
constructor(location: Location, line: String, viewers: Set<Player>) : this(location, line) {
this.viewers.addAll(viewers)
for (viewer in viewers) {
armorStand.visible(viewer, true)
}
}
private val armorStand =
PouArmorStand(nextInt(), location) {
it.setSmall(true)
it.setMarker(true)
it.setBasePlate(false)
it.setInvisible(true)
it.setCustomName(line.colored())
it.setCustomNameVisible(true)
}
fun update(line: String) {
if (!armorStand.isDeleted) {
armorStand.destroy()
armorStand.setCustomName(line.colored())
armorStand.respawn()
}
}
fun teleport(location: Location) {
if (!armorStand.isDeleted) {
armorStand.teleport(location)
}
}
fun delete() {
armorStand.delete()
}
fun destroy() {
armorStand.destroy()
}
} | 0 | HTML | 0 | 2 | 5608ced58650c3dac96c6c336a736a62fda9e5fb | 1,577 | Pouvoir | MIT License |
features/src/main/kotlin/ru/mobileup/template/features/pokemons/ui/details/RealPokemonDetailsComponent.kt | MobileUpLLC | 485,284,340 | false | {"Kotlin": 124942, "FreeMarker": 3484, "Shell": 3159} | package ru.mobileup.template.features.pokemons.ui.details
import com.arkivanov.decompose.ComponentContext
import dev.icerock.moko.resources.desc.desc
import me.aartikov.replica.single.Replica
import ru.mobileup.template.core.error_handling.ErrorHandler
import ru.mobileup.template.core.message.data.MessageService
import ru.mobileup.template.core.message.domain.Message
import ru.mobileup.template.core.utils.observe
import ru.mobileup.template.features.pokemons.domain.DetailedPokemon
import ru.mobileup.template.features.pokemons.domain.PokemonType
class RealPokemonDetailsComponent(
componentContext: ComponentContext,
private val pokemonReplica: Replica<DetailedPokemon>,
private val messageService: MessageService,
errorHandler: ErrorHandler
) : ComponentContext by componentContext, PokemonDetailsComponent {
override val pokemonState = pokemonReplica.observe(this, errorHandler)
override fun onTypeClick(type: PokemonType) {
pokemonState.value.data?.let {
messageService.showMessage(
Message(
text = "Types are: ${it.types.joinToString { it.name }}".desc()
)
)
}
}
override fun onRetryClick() {
pokemonReplica.refresh()
}
override fun onRefresh() {
pokemonReplica.refresh()
}
}
| 1 | Kotlin | 2 | 12 | d2c6e03655532c2945013115869c763056951706 | 1,343 | MobileUp-Android-Template | MIT License |
AtomicKotlin/Power Tools/Operator Overloading/Examples/src/ContainerAccess.kt | fatiq123 | 726,462,263 | false | {"Kotlin": 370528, "HTML": 6544, "JavaScript": 5252, "Java": 4416, "CSS": 3780, "Assembly": 94} | // OperatorOverloading/ContainerAccess.kt
package operatoroverloading
import atomictest.eq
data class C(val c: MutableList<Int>) {
override fun toString() = "C($c)"
}
operator fun C.contains(e: E) = e.v in c
operator fun C.get(i: Int): E = E(c[i])
operator fun C.set(i: Int, e: E) {
c[i] = e.v
}
fun main() {
val c = C(mutableListOf(2, 3))
(E(2) in c) eq true // c.contains(E(2))
(E(4) in c) eq false // c.contains(E(4))
c[1] eq E(3) // c.get(1)
c[1] = E(4) // c.set(2, E(4))
c eq C(mutableListOf(2, 4))
} | 0 | Kotlin | 0 | 0 | 3d351652ebe1dd7ef5f93e054c8f2692c89a144e | 544 | AtomicKotlinCourse | MIT License |
src/jvmTest/kotlin/com/bkahlert/kommons/debug/TraceKtTest.kt | bkahlert | 323,048,013 | false | null | package com.bkahlert.kommons.debug
import strikt.api.Assertion
/**
* Helper property that supports
* [print debugging][https://en.wikipedia.org/wiki/Debugging#Print_debugging]
* by printing `this` assertions builder's subject.
*/
@Deprecated("Don't forget to remove after you finished debugging.", replaceWith = ReplaceWith("this"))
@Suppress("RedundantVisibilityModifier")
public val <T : Assertion.Builder<V>, V> T.trace: T
get() = also {
get {
val subject: V = this
@Suppress("DEPRECATION")
subject.trace
}
}
/**
* Helper function that supports
* [print debugging][https://en.wikipedia.org/wiki/Debugging#Print_debugging]
* passing `this` assertion builder's subject and the subject applied to the given [transform] to [println]
* while still returning `this`.
*/
@Suppress("RedundantVisibilityModifier")
@Deprecated("Don't forget to remove after you finished debugging.", replaceWith = ReplaceWith("this"))
public fun <T : Assertion.Builder<V>, V> T.trace(description: CharSequence? = null, transform: (V.() -> Any)?): T =
also {
get {
val subject: V = this
@Suppress("DEPRECATION")
subject.trace(description, transform)
}
}
| 7 | Kotlin | 0 | 9 | 35e2ac1c4246decdf7e7a1160bfdd5c9e28fd066 | 1,261 | kommons | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/broken/Eos.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.crypto.broken
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.crypto.BrokenGroup
public val BrokenGroup.Eos: ImageVector
get() {
if (_eos != null) {
return _eos!!
}
_eos = Builder(name = "Eos", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth
= 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.48f, 15.6201f)
lineTo(5.22f, 16.9401f)
curveTo(5.1f, 17.5201f, 5.43f, 18.2401f, 5.95f, 18.5401f)
lineTo(11.27f, 21.5801f)
curveTo(11.68f, 21.8101f, 12.35f, 21.8101f, 12.76f, 21.5801f)
lineTo(18.08f, 18.5401f)
curveTo(18.6f, 18.2401f, 18.92f, 17.5301f, 18.81f, 16.9401f)
lineTo(17.1f, 8.3701f)
curveTo(17.06f, 8.1601f, 16.92f, 7.8601f, 16.78f, 7.7001f)
lineTo(13.18f, 3.3801f)
curveTo(12.55f, 2.6201f, 11.51f, 2.6201f, 10.88f, 3.3801f)
lineTo(7.28f, 7.7001f)
curveTo(7.15f, 7.8601f, 7.0f, 8.1601f, 6.96f, 8.3701f)
lineTo(6.44f, 10.9801f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.8097f, 8.52f)
lineTo(12.4697f, 20.68f)
curveTo(12.3097f, 21.12f, 11.6897f, 21.12f, 11.5297f, 20.68f)
lineTo(7.1797f, 8.5f)
}
}
.build()
return _eos!!
}
private var _eos: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 2,601 | VuesaxIcons | MIT License |
app/src/main/java/m/derakhshan/refectory/feature_authentication/presentation/sign_up/SignUpViewModel.kt | m-derakhshan | 453,145,306 | false | {"Kotlin": 122565} | package m.derakhshan.refectory.feature_authentication.presentation.sign_up
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import m.derakhshan.refectory.core.domain.model.Request
import m.derakhshan.refectory.feature_authentication.domain.model.UserModel
import m.derakhshan.refectory.feature_authentication.domain.use_cases.AuthenticationUseCase
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val useCase: AuthenticationUseCase
) : ViewModel() {
private val _state = mutableStateOf(SignUpState())
val state: State<SignUpState> = _state
private val _snackBar = MutableSharedFlow<SignUpSnackBarState>()
val snackBar = _snackBar.asSharedFlow()
private val _navigate = MutableSharedFlow<SignUpNavigationState>()
val navigate = _navigate.asSharedFlow()
init {
_state.value = _state.value.copy(
taxCode = savedStateHandle.get<String>("tax_code") ?: _state.value.taxCode
)
}
fun onEvent(event: SignUpEvent) {
when (event) {
is SignUpEvent.SignUp -> {
signUp()
}
is SignUpEvent.NameChanged -> {
_state.value = _state.value.copy(
name = enterRemoval(event.name)
)
}
is SignUpEvent.SurnameChanged -> {
_state.value = _state.value.copy(
surname = enterRemoval(event.surname)
)
}
is SignUpEvent.PhoneChanged -> {
_state.value = _state.value.copy(
phoneNumber = enterRemoval(event.phone)
)
}
is SignUpEvent.EmailChanged -> {
_state.value = _state.value.copy(
email = enterRemoval(event.email)
)
}
is SignUpEvent.PhotoChanged -> {
_state.value = _state.value.copy(
photo = event.photo
)
}
is SignUpEvent.AddImageClicked -> {
_state.value = _state.value.copy(
openImagePicker = true
)
}
is SignUpEvent.CloseImagePicker -> {
_state.value = _state.value.copy(
openImagePicker = false
)
}
}
}
private fun enterRemoval(text: String) = text.replace("\n", "")
private fun signUp() {
_state.value = _state.value.copy(
isSignUpExpanded = false
)
viewModelScope.launch {
try {
val result = useCase.signUpUseCase(
UserModel(
id = _state.value.id,
name = _state.value.name,
surname = _state.value.surname,
photo = _state.value.photo.toString(),
phoneNumber = _state.value.phoneNumber,
email = _state.value.email,
taxCode = _state.value.taxCode
)
)
when (result) {
is Request.Success -> {
useCase.storeUserDataInDatabase(result.data)
_navigate.emit(
SignUpNavigationState(
navigateToHomeScreen = true
)
)
}
is Request.Error -> {
_snackBar.emit(
SignUpSnackBarState(message = result.message)
)
}
}
} catch (e: Exception) {
_snackBar.emit(
SignUpSnackBarState(message = e.message ?: "Unknown error.")
)
}
_state.value = _state.value.copy(
isSignUpExpanded = true
)
}
}
} | 0 | Kotlin | 0 | 0 | 9e0d512cf9419562e4fadf6a76c9b2b672886279 | 4,410 | Refectory | The Unlicense |
utils/src/commonMain/kotlin/io/github/dmitriy1892/kmp/libs/utils/coroutines/mutex/MutexExtensions.kt | Dmitriy1892 | 782,469,883 | false | {"Kotlin": 75653, "Shell": 2195, "Swift": 342} | package io.github.dmitriy1892.kmp.libs.utils.coroutines.mutex
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* Locks the current thread until [action] was end his work.
*
* @param action suspendable action that need to execute
* @return [T]
*/
@RestrictedMutexApi
inline fun <T> Mutex.withThreadLock(crossinline action: suspend () -> T): T {
return runBlocking { [email protected] { action() } }
} | 0 | Kotlin | 0 | 0 | fce0d13490d4e45b1bd56a55effe4f5c6bfffec6 | 491 | kmp-libs | Apache License 2.0 |
app/src/main/java/cn/junmov/mirror/user/ui/SyncFragment.kt | junmov | 314,679,541 | false | null | package cn.junmov.mirror.user.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import cn.junmov.mirror.databinding.FragmentSyncBinding
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SyncFragment : Fragment() {
private val viewModel: SyncViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
val binding = FragmentSyncBinding.inflate(inflater, container, false)
binding.apply {
vm = viewModel
lifecycleOwner = this@SyncFragment
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.message.observe(viewLifecycleOwner) {
Snackbar.make(view, it, Snackbar.LENGTH_SHORT).show()
}
}
} | 0 | Kotlin | 0 | 0 | f328452115af11d9db77f8caaf5bda0b46f7a69b | 1,112 | mirror-android | MIT License |
app/src/main/java/com/kylecorry/trail_sense/tools/battery/infrastructure/commands/BatteryLogCommand.kt | kylecorry31 | 215,154,276 | false | null | package com.kylecorry.trail_sense.tools.battery.infrastructure.commands
import android.content.Context
import com.kylecorry.andromeda.battery.Battery
import com.kylecorry.andromeda.battery.BatteryChargingStatus
import com.kylecorry.trail_sense.shared.commands.CoroutineCommand
import com.kylecorry.trail_sense.tools.battery.domain.BatteryReadingEntity
import com.kylecorry.trail_sense.tools.battery.infrastructure.persistence.BatteryRepo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.time.Duration
import java.time.Instant
class BatteryLogCommand(private val context: Context) : CoroutineCommand {
override suspend fun execute() {
val battery = Battery(context)
val batteryRepo = BatteryRepo.getInstance(context)
withContext(Dispatchers.IO) {
try {
withTimeoutOrNull(Duration.ofSeconds(10).toMillis()) {
battery.read()
}
} finally {
battery.stop(null)
}
}
val pct = battery.percent
val charging = battery.chargingStatus == BatteryChargingStatus.Charging
val time = Instant.now()
val capacity = battery.capacity
val reading = BatteryReadingEntity(pct, capacity, charging, time)
if (battery.hasValidReading) {
batteryRepo.add(reading)
}
batteryRepo.deleteBefore(Instant.now().minus(Duration.ofDays(1)))
}
} | 405 | Kotlin | 44 | 677 | 83d40025d6d797c248af8ceba3a6bd2df7455af2 | 1,512 | Trail-Sense | MIT License |
Projeto 2/timeConverter2.0.kt | RafaPear | 867,356,904 | false | {"Kotlin": 5350, "Batchfile": 139} | fun clear(){print("\u001b[H\u001b[2J")}
@Throws(NumberFormatException::class)
fun main(){
var program = true
while(program){
while(program){
//Set up User Input
clear()
println(">> Input seconds to convert, 0 to exit")
print("<< ")
var inputSeconds : Int = 1
//Get user input and test for int
try{
inputSeconds = readln().toInt()
}catch(e: Exception){
clear()
println("Input must be an integer: $e\nPress enter to continue...")
readln()
break
}
if (inputSeconds < 0){
clear()
println("Error: input must be greater than zero\nPress enter to continue...")
readln()
break
}
else if (inputSeconds == 0) program = false
else{
//if the input is greater than zero and is an integer:
//Convert time
if (inputSeconds > 0){
val days = inputSeconds/86400
val hours = (inputSeconds%86400)/3600
val minutes = (inputSeconds%3600)/60
val remainSeconds = (inputSeconds%3600)%60
clear()
print(">> $days d : $hours h : $minutes m : $remainSeconds s\nPress enter to continue...")
readln()
}
}
}
}
} | 0 | Kotlin | 0 | 0 | dcb72c72aa48be1e46d78225b6ff008c31fcb55a | 1,130 | LEIC-Projetos-Kotlin | MIT License |
shared/src/commonMain/kotlin/com/jetbrains/kmpapp/screens/SpeedViewModel.kt | vov4ik-v | 806,748,892 | false | {"Kotlin": 15320, "Swift": 4802} | package com.jetbrains.kmpapp.screens
import com.rickclephas.kmm.viewmodel.KMMViewModel
import kotlinx.coroutines.flow.MutableStateFlow
class SpeedViewModel : KMMViewModel() {
private val _speedData = MutableStateFlow<Float?>(null)
// Функція для оновлення швидкості
fun updateSpeed(speed: Float) {
_speedData.value = speed
}
}
| 0 | Kotlin | 0 | 0 | e23eb1b6d975ce2c58b09c3d6df24c43a2cb0291 | 354 | TrainApp | Apache License 2.0 |
im-user/user-domain/src/commonMain/kotlin/city/smartb/im/user/domain/features/command/UserUpdateFunction.kt | smartbcity | 651,445,390 | false | null | package city.smartb.im.user.domain.features.command
import city.smartb.im.commons.model.Address
import city.smartb.im.organization.domain.model.OrganizationId
import city.smartb.im.user.domain.model.UserId
import f2.dsl.cqrs.Command
import f2.dsl.cqrs.Event
import f2.dsl.fnc.F2Function
import i2.keycloak.f2.role.domain.RoleName
import kotlin.js.JsExport
import kotlin.js.JsName
/**
* Update a user.
* @d2 function
* @parent [city.smartb.im.user.domain.D2UserPage]
* @order 20
*/
typealias UserUpdateFunction = F2Function<UserUpdateCommand, UserUpdatedEvent>
typealias KeycloakUserUpdateCommand = i2.keycloak.f2.user.domain.features.command.UserUpdateCommand
typealias KeycloakUserUpdateFunction = i2.keycloak.f2.user.domain.features.command.UserUpdateFunction
@JsExport
@JsName("UserUpdateCommandDTO")
interface UserUpdateCommandDTO: Command {
/**
* Identifier of the user.
*/
val id: UserId
/**
* First name of the user.
* @example [city.smartb.im.user.domain.model.User.givenName]
*/
val givenName: String
/**
* Family name of the user.
* @example [city.smartb.im.user.domain.model.User.familyName]
*/
val familyName: String
/**
* Address of the user.
*/
val address: Address?
/**
* Telephone number of the user.
* @example [city.smartb.im.user.domain.model.User.phone]
*/
val phone: String?
/**
* Organization to which the user belongs.
*/
val memberOf: OrganizationId?
/**
* Add roles to the user.
* @example [["admin"]]
*/
val roles: List<RoleName>
/**
* Additional arbitrary attributes assigned to the user.
* @example [city.smartb.im.user.domain.model.User.attributes]
*/
val attributes: Map<String, String>?
}
/**
* @d2 command
* @parent [UserUpdateFunction]
*/
data class UserUpdateCommand(
override val id: UserId,
override val givenName: String,
override val familyName: String,
override val address: Address?,
override val phone: String?,
override val memberOf: OrganizationId?,
override val roles: List<RoleName>,
override val attributes: Map<String, String>?
): UserUpdateCommandDTO
@JsExport
@JsName("UserUpdatedEventDTO")
interface UserUpdatedEventDTO: Event {
/**
* Identifier of the user.
*/
val id: UserId
}
/**
* @d2 event
* @parent [UserUpdateFunction]
*/
data class UserUpdatedEvent(
override val id: UserId
): UserUpdatedEventDTO
| 0 | Kotlin | 0 | 0 | 6a727ac998241724d073ac66247496355316f934 | 2,503 | connect-im | Apache License 2.0 |
src/main/kotlin/vlkv/configuration/yaml/DataFixes.kt | veelkoov | 413,134,828 | false | null | package vlkv.configuration.yaml
class DataFixes {
lateinit var fixes: List<Fix>
}
| 0 | Kotlin | 0 | 0 | a3e4fc164226ed639859d37f6f987ec4ae37c5ca | 87 | HoldMyAB | MIT License |
user-service-remote/src/main/kotlin/io/github/pak3nuh/monolith/service/user/RemoteUserServiceFactory.kt | pak3nuh | 660,976,930 | false | {"Kotlin": 24611} | package io.github.pak3nuh.monolith.service.user
import io.github.pak3nuh.monolith.core.service.DependencyDeclaration
import io.github.pak3nuh.monolith.core.service.Service
import io.github.pak3nuh.monolith.core.service.ServiceDependencies
import io.github.pak3nuh.monolith.core.service.ServiceLocality
import kotlin.reflect.KClass
class RemoteUserServiceFactory: UserServiceFactory {
override val locality = ServiceLocality.REMOTE
override val serviceType: KClass<UserService> = UserService::class
override val dependencies: Sequence<DependencyDeclaration<out Service>>
get() = sequenceOf()
override fun create(dependencies: ServiceDependencies): UserService {
TODO()
}
} | 0 | Kotlin | 0 | 0 | f71a3a7d491937e83e31615dc208e08254723dea | 710 | awesome-monolith | MIT License |
src/main/kotlin/io/zayasanton/app/api/filters/models/ExchangeRequest.kt | azayas97 | 784,997,922 | false | {"Kotlin": 68644} | package io.zayasanton.app.api.filters.models
data class ExchangeRequest(
val userId: String,
val sessionId: String,
)
| 0 | Kotlin | 0 | 0 | 1cc7567bc10cd3da1ec216e79b61d85b89ce55c2 | 127 | doctor-contact-service | MIT License |
easypermission/src/main/java/aditya/wibisana/easypermission/ActionManageOverlayPermission.kt | adityawibisana | 736,298,847 | false | {"Kotlin": 10085} | package aditya.wibisana.easypermission
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
class ActionManageOverlayPermission(appCompatActivity: AppCompatActivity)
: SimplePermission(appCompatActivity) {
override fun reload(activity: AppCompatActivity) {
_isPermissionGranted.value = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
true
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Settings.canDrawOverlays(activity)
} else {
if (Settings.canDrawOverlays(activity)) true
try {
val mgr = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val viewToAdd = View(activity)
val params = WindowManager.LayoutParams(
0,
0,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
else
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSPARENT
)
viewToAdd.layoutParams = params
mgr.addView(viewToAdd, params)
mgr.removeView(viewToAdd)
true
} catch (e: Exception) {
e.printStackTrace()
}
false
}
}
override fun request(activity: AppCompatActivity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
val uri = Uri.parse("package:${activity.packageName}")
val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, uri)
activity.startActivity(intent)
}
} | 0 | Kotlin | 0 | 0 | 1a68dfe08443e9e7309a9ed04c6c0dfcb31ee4ee | 2,066 | android_easy_permission | MIT License |
shared/src/commonMain/kotlin/com/codewithfk/eventhub/event/data/response/Genre.kt | furqanullah717 | 698,731,559 | false | {"Kotlin": 71888, "Swift": 802} | package com.codewithfk.eventhub.event.data.response
data class Genre(
val id: String,
val name: String
) | 0 | Kotlin | 0 | 0 | 61edd24b574684028463528dee56527ce9225a9b | 113 | event-hub-kmm | MIT License |
src/main/kotlin/dev/emortal/doors/pathfinding/Directions.kt | emortalmc | 532,048,771 | false | null | package dev.emortal.doors.pathfinding
enum class Directions(val offX: Int, val offY: Int, val offZ: Int) {
NORTH(0, 0, -1),
EAST(1, 0, 0),
SOUTH(0, 0, 1),
WEST(-1, 0, 0),
// NORTHUP(0, 1, -1),
// SOUTHUP(0, 1, 1),
// WESTUP(-1, 1, 0),
// EASTUP(1, 1, 0),
//
// NORTHDOWN(0, -1, -1),
// SOUTHDOWN(0, -1, 1),
// WESTDOWN(-1, -1, 0),
// EASTDOWN(1, -1, 0)
} | 1 | Kotlin | 1 | 2 | a99f1cab532dde948b39b7ede26072d2395434ce | 396 | MineDoors | MIT License |
app/src/main/java/pl/jakubokrasa/bikeroutes/features/photos/presentation/PhotoGalleryFragment.kt | JakubOkrasa | 367,399,523 | false | null | package pl.jakubokrasa.bikeroutes.features.photos.presentation
import android.os.Bundle
import android.view.View
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import pl.jakubokrasa.bikeroutes.R
import pl.jakubokrasa.bikeroutes.core.base.presentation.BaseFragment
import pl.jakubokrasa.bikeroutes.databinding.FragmentPhotogalleryBinding
import pl.jakubokrasa.bikeroutes.features.photos.presentation.model.PhotoInfoDisplayable
import pl.jakubokrasa.bikeroutes.features.ui_features.myroutes.presentation.MyRoutesViewModel
class PhotoGalleryFragment(): BaseFragment<MyRoutesViewModel>(R.layout.fragment_photogallery) {
override val viewModel: MyRoutesViewModel by sharedViewModel()
private var _binding: FragmentPhotogalleryBinding? = null
private val binding get() = _binding!!
private var photos = ArrayList<PhotoInfoDisplayable>()
private lateinit var galleryAdapter: PhotoGalleryAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentPhotogalleryBinding.bind(view)
photos.addAll(getPhotos())
galleryAdapter = PhotoGalleryAdapter(requireContext(), photos, viewModel)
binding.viewPager.adapter = galleryAdapter
binding.viewPager.setCurrentItem(getPosition(), false)
}
override fun initObservers() {
super.initObservers()
observePhotoRemovePos()
}
private fun observePhotoRemovePos() {
viewModel.photoRemovePos.observe(viewLifecycleOwner, {
if(photos.isNotEmpty())
galleryAdapter.removePhoto(it)
})
}
private fun getPhotos(): List<PhotoInfoDisplayable> {
val serializable =
arguments?.getSerializable(PHOTOS_BUNDLE_KEY) as List<PhotoInfoDisplayable>
if (serializable is List<*>?) {
serializable.let {
return serializable
}
}
return emptyList()
}
private fun getPosition(): Int {
return arguments?.getInt(PHOTO_POSITION_BUNDLE_KEY)?: 0
}
override fun onDestroy() {
super.onDestroy()
destroyRecycler() // needed for every Recycler View Adapter while using Navigation Component
}
private fun destroyRecycler() {
// without "binding.viewPager.layoutManager = null" (in viewpager is no layoutManager)
binding.viewPager.adapter = null
}
companion object {
const val PHOTOS_BUNDLE_KEY = "photosBundleKey"
const val PHOTO_POSITION_BUNDLE_KEY = "photoPositionBundleKey"
}
} | 1 | Kotlin | 0 | 0 | f392343249e3f4c15c54b4f01b26ec46cab2c41d | 2,606 | BikeRoutes | Apache License 2.0 |
app/src/main/java/io/github/droidkaigi/confsched2018/presentation/search/SearchSpeakersFragment.kt | satorufujiwara | 119,129,920 | true | {"Kotlin": 434412, "Ruby": 2122, "Java": 780} | package io.github.droidkaigi.confsched2018.presentation.search
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.firebase.analytics.FirebaseAnalytics
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import io.github.droidkaigi.confsched2018.databinding.FragmentSearchSpeakersBinding
import io.github.droidkaigi.confsched2018.di.Injectable
import io.github.droidkaigi.confsched2018.presentation.NavigationController
import io.github.droidkaigi.confsched2018.presentation.Result
import io.github.droidkaigi.confsched2018.presentation.common.itemdecoration.StickyHeaderItemDecoration
import io.github.droidkaigi.confsched2018.presentation.search.item.SpeakerItem
import io.github.droidkaigi.confsched2018.presentation.search.item.SpeakersSection
import io.github.droidkaigi.confsched2018.util.ext.observe
import timber.log.Timber
import javax.inject.Inject
class SearchSpeakersFragment : Fragment(), Injectable {
private var fireBaseAnalytics: FirebaseAnalytics? = null
private lateinit var binding: FragmentSearchSpeakersBinding
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject lateinit var navigationController: NavigationController
private val searchSpeakersViewModel: SearchSpeakersViewModel by lazy {
ViewModelProviders.of(this, viewModelFactory).get(SearchSpeakersViewModel::class.java)
}
private val speakersSection = SpeakersSection()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = FragmentSearchSpeakersBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
searchSpeakersViewModel.speakers.observe(this, { result ->
when (result) {
is Result.Success -> {
speakersSection.updateSpeakers(result.data)
}
is Result.Failure -> {
Timber.e(result.e)
}
}
})
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
fireBaseAnalytics = FirebaseAnalytics.getInstance(context)
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
fireBaseAnalytics?.setCurrentScreen(activity!!, null, this::class.java.simpleName)
}
}
private fun setupRecyclerView() {
val groupAdapter = GroupAdapter<ViewHolder>().apply {
setOnItemClickListener { item, _ ->
val speakerItem = item as? SpeakerItem ?: return@setOnItemClickListener
navigationController.navigateToSpeakerDetailActivity(speakerItem.speaker.id)
}
add(speakersSection)
}
binding.searchSessionRecycler.apply {
adapter = groupAdapter
}
binding.searchSessionRecycler.addItemDecoration(StickyHeaderItemDecoration(context,
object : StickyHeaderItemDecoration.Callback {
override fun getGroupId(position: Int): Long {
val initial = speakersSection.getSpeakerNameOrNull(position)?.get(0)
initial ?: return -1
return Character.toUpperCase(initial).toLong()
}
override fun getGroupFirstLine(position: Int): String? {
return speakersSection.getSpeakerNameOrNull(position)?.get(0)?.toString()
}
}))
}
companion object {
fun newInstance(): SearchSpeakersFragment = SearchSpeakersFragment()
}
}
| 0 | Kotlin | 0 | 1 | 70b07377c7f17839537f836039dd981d0f96fa08 | 4,274 | conference-app-2018 | Apache License 2.0 |
src/main/kotlin/com/github/strindberg/ideaemacs/services/MyProjectService.kt | strindberg | 527,434,893 | false | {"Kotlin": 7209} | package com.github.strindberg.ideaemacs.services
import com.intellij.openapi.project.Project
import com.github.strindberg.ideaemacs.MyBundle
class MyProjectService(project: Project) {
init {
println(MyBundle.message("projectService", project.name))
System.getenv("CI")
?: TODO("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
}
| 0 | Kotlin | 0 | 0 | 19473e3eaf8d1f5c4ac1be9b3b7c33afc8b61b1d | 443 | IdeaEmacs | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt | ChiuLui | 343,302,687 | false | null | /*
* 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
*
* 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.example.androiddevchallenge
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat.startActivity
import com.example.androiddevchallenge.data.Dog
import com.example.androiddevchallenge.ui.theme.MyTheme
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val context = LocalContext.current
MyTheme {
ShowDogList(context = context)
}
}
}
}
@Composable
fun DogList(dogs: List<Dog>, onDogClick: (Dog) -> Unit = {}) {
LazyColumn(
contentPadding = PaddingValues(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(dogs) { dog ->
DogItem(
dog,
Modifier
.clickable { onDogClick(dog) }
.fillMaxWidth()
)
}
}
}
@Composable
fun DogItem(dog: Dog, modifier: Modifier = Modifier) {
Card(modifier) {
Row {
Image(
painterResource(dog.photo),
"Picture of dog: ${dog.name}",
Modifier.size(120.dp),
contentScale = ContentScale.Crop
)
Column(Modifier.padding(8.dp)) {
Text(dog.name, style = MaterialTheme.typography.h4)
Text("Breed: ${dog.breed}", style = MaterialTheme.typography.body2)
Text("Address: ${dog.address}", style = MaterialTheme.typography.body2)
}
}
}
}
@Composable
fun ShowDogList(context: Context) {
val dogList = listOf(
Dog(
"Cookie", "Golden Retriever", "2",
"Boy", "Washington", R.drawable.dog_4
),
Dog(
"Coco", "Husky", "1",
"Girl", "Los Angeles", R.drawable.dog_7
),
Dog(
"Happy", "Corgi", "3",
"Girl", "Alaska", R.drawable.dog_6
),
Dog(
"Barbara", "Labrador", "1",
"Girl", "Philadelphia", R.drawable.dog_5
),
Dog(
"Honey", "Akita", "4",
"Boy", "Washington", R.drawable.dog_3
),
Dog(
"Anna", "Teddy", "5",
"Girl", "New York", R.drawable.dog_2
),
Dog(
"Katrina", "Samoyed", "2",
"Boy", "Chicago", R.drawable.dog_1
),
Dog(
"Emily", "Chihuahua", "1",
"Girl", "Los Angeles", R.drawable.dog_0
)
)
Surface(
color = MaterialTheme.colors.background,
) {
Column {
TopAppBar(
title = {
Text("Puppy Adoption")
}
)
DogList(
dogList,
onDogClick = {
val intent = Intent(context, DogDetailActivity::class.java)
val bundle = Bundle()
bundle.putString("name", it.name)
bundle.putString("breed", it.breed)
bundle.putString("age", it.age)
bundle.putString("gender", it.gender)
bundle.putString("address", it.address)
bundle.putInt("photo", it.photo)
// bundle.putParcelable("dog", it)
intent.putExtras(bundle)
startActivity(context, intent, null)
}
)
}
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun ShowDogListLight() {
val context = LocalContext.current
MyTheme {
ShowDogList(context)
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun ShowDogListDark() {
val context = LocalContext.current
MyTheme(darkTheme = true) {
ShowDogList(context)
}
}
| 0 | Kotlin | 0 | 0 | 9127fe48c3e6d775aa41b0222717495769573712 | 5,718 | ChallengePuppyAdoption | Apache License 2.0 |
lightweightlibrary/src/main/java/com/tradingview/lightweightcharts/api/options/models/HandleScrollOptions.kt | tradingview | 284,986,398 | false | null | package com.tradingview.lightweightcharts.api.options.models
data class HandleScrollOptions(
var mouseWheel: Boolean? = null,
var pressedMouseMove: Boolean? = null,
var horzTouchDrag: Boolean? = null,
var vertTouchDrag: Boolean? = null
)
inline fun handleScrollOptions(init: HandleScrollOptions.() -> Unit): HandleScrollOptions {
return HandleScrollOptions().apply(init)
} | 25 | Kotlin | 27 | 86 | 08c3dbda653a1d5f78f7c5d47c990c7f9887d9e4 | 394 | lightweight-charts-android | Apache License 2.0 |
app/src/main/java/id/android/movie/presentation/ui/UiState.kt | budioktaviyan | 273,710,455 | false | null | package id.android.movie.presentation.ui
import androidx.compose.Composable
import androidx.compose.getValue
import androidx.compose.onActive
import androidx.compose.setValue
import androidx.compose.state
import id.android.movie.data.Result
import id.android.movie.presentation.ui.UiState.Error
import id.android.movie.presentation.ui.UiState.Loading
import id.android.movie.presentation.ui.UiState.Success
typealias RepositoryCall<T> = ((Result<T>) -> Unit) -> Unit
sealed class UiState<out T> {
object Loading : UiState<Nothing>()
data class Success<out T>(val data: T) : UiState<T>()
data class Error(val exception: Exception) : UiState<Nothing>()
}
/**
* UiState factory that updates its internal state with the [com.example.jetnews.data.Result]
* of a repository called as a parameter.
*
* To load asynchronous data, effects are better pattern than using @Model classes since
* effects are Compose lifecycle aware.
*/
@Composable
fun <T> uiStateFrom(
repositoryCall: RepositoryCall<T>
): UiState<T> {
var state: UiState<T> by state<UiState<T>> { Loading }
onActive {
repositoryCall { result ->
state = when (result) {
is Result.Success -> Success(result.data)
is Result.Error -> Error(result.exception)
}
}
}
return state
}
/**
* Helper function that loads data from a repository call. Only use in Previews!
*/
@Composable
fun <T> previewDataFrom(
repositoryCall: RepositoryCall<T>
): T {
var state: T? = null
repositoryCall { result ->
state = (result as Result.Success).data
}
return state!!
} | 0 | Kotlin | 0 | 1 | 86aa19703b10632eb64f5b19859477b92756dd2a | 1,588 | movie-compose | MIT License |
app/src/main/java/com/altaureum/covid/tracking/common/IntentData.kt | jllarraz | 249,151,516 | false | null | package com.altaureum.covid.tracking.common
object IntentData {
val KEY_DATA="KEY_DATA"
val KEY_SERVICE_UUID="KEY_SERVICE_UUID"
val KEY_INCLUDE_CLIENT_LOCATION="KEY_INCLUDE_CLIENT_LOCATION"
} | 0 | Kotlin | 1 | 2 | 08f20f2de577e2fdf76dd8c45bcff9109a5c9b54 | 204 | CovidContactTracking | Apache License 2.0 |
app/src/main/java/com/example/flyapp/view/AirportFragment.kt | giobirkelund | 415,696,064 | false | null | package com.example.flyapp.view
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.flyapp.InternetStatus
import com.example.flyapp.R
import com.example.flyapp.adapter.AirportAdapter
import com.example.flyapp.models.calculateDistance
import com.example.flyapp.viewmodel.SharedViewModel
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class AirportFragment(sharedViewModel: SharedViewModel) : Fragment() {
private val myViewModel = sharedViewModel
private lateinit var spinner: Spinner
private var userLocation: LatLng? = null
private lateinit var swipeRefreshLayout: SwipeRefreshLayout
private var gpsEnabled = false
private lateinit var airportRecyclerView: RecyclerView
private lateinit var spinnerAdapter: ArrayAdapter<String>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_airport, container, false)
swipeRefreshLayout = view.findViewById(R.id.swipe_layout)
// Starts the progressbar, and shows it during API-call
// progress = view.findViewById(R.id.progress_bar)
spinner = view.findViewById(R.id.sorting_spinner)
populateSpinner(spinner); setSpinnerListener(spinner)
// We find the recyclerview
airportRecyclerView = view.findViewById(R.id.airport_RecyclerView)
// Attach a LayoutManager
airportRecyclerView.layoutManager = LinearLayoutManager(context)
// Set the refresh-action for our SwipeRefreshLayout
setSwipeRefreshAction()
setObservers()
return view
}
private fun setSwipeRefreshAction() {
Log.i("swipe internet:", InternetStatus.getConnection().toString())
swipeRefreshLayout.setOnRefreshListener {
Log.i("Action", "onRefresh called from SwipeRefreshLayout")
if (InternetStatus.getConnection() == true) {
// Updates the RecyclerView
CoroutineScope(Dispatchers.IO).launch {
updateLiveData()
}
} else {
Log.i("swipe internet:", "in else statement")
Toast.makeText(context, "Not connected to internet", Toast.LENGTH_SHORT).show()
swipeRefreshLayout.isRefreshing = false
}
}
}
private fun setObservers() {
// We observe changes to our LiveData of Airport-objects, located in AirportViewModel
myViewModel.getAirportLiveData().observe(viewLifecycleOwner, Observer {
swipeRefreshLayout.isRefreshing = false
if(userLocation != null){
calculateDistance(it.toMutableList(), userLocation!!.latitude, userLocation!!.longitude)
}
// And when a change occurs, we simply update the adapter with the new data
airportRecyclerView.adapter = AirportAdapter(it.toMutableList(), gpsEnabled)
Log.d("Action:", "Change noticed by observer, and recyclerview updated")
})
myViewModel.getUserLocation().observe(viewLifecycleOwner, Observer {
Log.d("UserLocation", "noticed by observer in AirportFragment")
if(userLocation == null) {
userLocation = LatLng(it.latitude, it.longitude)
myViewModel.updateWithGpsInfo()
gpsEnabled = true
if(this::spinnerAdapter.isInitialized) {
spinnerAdapter.insert("Nearest//Farthest", 3)
spinnerAdapter.notifyDataSetChanged()
}
}
})
}
private fun populateSpinner(spinner: Spinner) {
val list = ArrayList<String>()
list.add("Most visited"); list.add("Hottest"); list.add("Coldest")
if(gpsEnabled) list.add("Nearest//Farthest")
spinnerAdapter = ArrayAdapter(this.requireContext(), R.layout.spinner_list_layout, list)
spinnerAdapter.setDropDownViewResource(R.layout.my_spinner_dropdown_item)
spinner.adapter = spinnerAdapter
// Setting the background!
val mCon = spinner.context
val resID: Int = mCon.resources.getIdentifier(
"spinner_style_corner" , "drawable", mCon.packageName)
spinner.setPopupBackgroundDrawable(ResourcesCompat.getDrawable(
requireContext().resources, resID, requireContext().theme))
}
private fun setSpinnerListener(spinner: Spinner) {
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
// Nothing
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
myViewModel.sortAirports(spinner.selectedItem.toString(), userLocation)
}
}
}
suspend fun updateLiveData() {
try {
myViewModel.setAirportLiveData(spinner.selectedItem.toString())
} catch(e: Exception) {
Handler(Looper.getMainLooper()).post { // This is where your UI code goes.
Toast.makeText(context,"Not connected to internet",Toast.LENGTH_SHORT).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | b6d0400fa6d142f39147257ae2a9a3756582b09b | 5,931 | Airplane-Enthusiast-Android-App | MIT License |
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/item/detail/ConsumableDetails.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.model.item.detail
import com.bselzer.gw2.v2.model.color.DyeColorId
import com.bselzer.gw2.v2.model.enumeration.wrapper.ConsumableDetailType
import com.bselzer.gw2.v2.model.enumeration.wrapper.ConsumableUnlockType
import com.bselzer.gw2.v2.model.guild.upgrade.GuildUpgradeId
import com.bselzer.gw2.v2.model.recipe.RecipeId
import com.bselzer.gw2.v2.model.skin.SkinId
import com.bselzer.gw2.v2.model.wrapper.ImageLink
import com.bselzer.ktx.serialization.serializer.MillisecondDurationSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.time.Duration
@Serializable
data class ConsumableDetails(
@SerialName("type")
val type: ConsumableDetailType = ConsumableDetailType(),
@SerialName("description")
val description: String = "",
@Serializable(with = MillisecondDurationSerializer::class)
@SerialName("duration_ms")
val duration: Duration = Duration.ZERO,
/**
* The unlock type for unlockable consumables.
*
* Null if this consumable is not unlockable.
*/
@SerialName("unlock_type")
val unlockType: ConsumableUnlockType? = null,
/**
* The id of the dye color when the [unlockType] is for a dye.
* @see <a href="https://wiki.guildwars2.com/wiki/API:2/colors">the wiki</a>
*/
@SerialName("color_id")
val colorId: DyeColorId = DyeColorId(),
/**
* The id of the recipe when the [unlockType] is for a recipe.
* @see <a href="https://wiki.guildwars2.com/wiki/API:2/recipes">the wiki</a>
*/
@SerialName("recipe_id")
val recipeId: RecipeId = RecipeId(),
/**
* The ids of the additional recipe unlocks.
* @see <a href="https://wiki.guildwars2.com/wiki/API:2/recipes">the wiki</a>
*/
@SerialName("extra_recipe_ids")
val extraRecipeIds: List<RecipeId> = emptyList(),
/**
* The id of the guild upgrade.
* @see <a href="https://wiki.guildwars2.com/wiki/API:2/guild/upgrades">the wiki</a>
*/
@SerialName("guild_upgrade_id")
val guildUpgradeId: GuildUpgradeId = GuildUpgradeId(),
/**
* The number of stacks of the effect applied by this item.
*/
@SerialName("apply_count")
val applyCount: Int = 0,
/**
* The effect type name.
*/
@SerialName("name")
val name: String = "",
/**
* The link to the effect icon.
*/
@SerialName("icon")
val iconLink: ImageLink = ImageLink(),
/**
* The ids of the skins this item unlocks.
* @see <a href="https://wiki.guildwars2.com/wiki/API:2/skins">the wiki</a>
*/
@SerialName("skins")
val skinIds: List<SkinId> = emptyList()
) | 2 | Kotlin | 0 | 2 | 32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27 | 2,693 | GW2Wrapper | Apache License 2.0 |
app/src/main/java/com/olabode/wilson/pytutor/ui/auth/resetpassword/ResetPasswordViewModel.kt | whilson03 | 173,095,316 | false | null | package com.olabode.wilson.pytutor.ui.auth.resetpassword
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import com.olabode.wilson.pytutor.repository.auth.AuthRepository
import com.olabode.wilson.pytutor.utils.states.DataState
/**
* Created by <NAME> on 9/23/20.
*/
class ResetPasswordViewModel @ViewModelInject constructor(
private val authRepository: AuthRepository
) : ViewModel() {
fun resetPassword(email: String): LiveData<DataState<String>> {
return authRepository.sendPasswordResetLink(email).asLiveData()
}
} | 2 | Kotlin | 3 | 4 | 440cdf95f1c7e750fcadb49623d6f15b993163cd | 651 | PyTutor | MIT License |
spring-boot/projeto-plenitute-no-olhar/src/main/kotlin/kronos/projetoplenitutenoolhar/controller/AgendamentoController.kt | kronos-agendamento | 758,290,087 | false | {"Kotlin": 63915, "HTML": 38487, "CSS": 23175, "JavaScript": 5155} | package kronos.projetoplenitutenoolhar.controller
import kronos.projetoplenitutenoolhar.dominio.Agendamento
import kronos.projetoplenitutenoolhar.repositorio.AgendamentoRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/agendamentos")
class AgendamentoController(
val agendamentoRepository: AgendamentoRepository
) {
@PostMapping
fun criar(@RequestBody novoAgendamento: Agendamento,
@Autowired agendamentoRepository: AgendamentoRepository
): ResponseEntity<Agendamento> {
val agendamentoSalvo = agendamentoRepository.save(novoAgendamento)
return ResponseEntity.status(201).body(agendamentoSalvo)
}
@GetMapping
fun exibirAgendamento():ResponseEntity<List<Agendamento>>{
val listaAgendamento = agendamentoRepository.findAll()
if(listaAgendamento.isEmpty()){
return ResponseEntity.status(204).build()
}
return ResponseEntity.status(200).body(listaAgendamento)
}
@DeleteMapping("/{codigo}")
fun deletar(@PathVariable codigo:Int):ResponseEntity<Void>{
if(agendamentoRepository.existsById(codigo)){
agendamentoRepository.deleteById(codigo)
return ResponseEntity.status(204).build()
}
return ResponseEntity.status(404).build()
}
@PutMapping("/{codigo}")
fun alterarAgendamento(@PathVariable codigo:Int, @RequestBody agendamento: Agendamento)
:ResponseEntity<Agendamento>{
if(agendamentoRepository.existsById(codigo)){
agendamento.idAgendamento = codigo
agendamentoRepository.save(agendamento)
return ResponseEntity.status(200).body(agendamento)
}
return ResponseEntity.status(204).build()
}
} | 0 | Kotlin | 0 | 2 | da76a7a92ffb706f2651c332ec98da9793cb8eca | 1,888 | projeto-teste | MIT License |
app/src/main/java/org/treeo/treeo/network/workers/UploadQueueWorker.kt | fairventures-worldwide | 498,242,730 | false | {"Kotlin": 586304, "C++": 87995, "Java": 3688, "CMake": 2149} | package org.treeo.treeo.network.workers
import android.content.Context
import android.content.SharedPreferences
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.google.gson.Gson
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import org.treeo.treeo.db.dao.ActivityDao
import org.treeo.treeo.db.models.UploadQueueEntity
import org.treeo.treeo.network.RequestManager
import org.treeo.treeo.network.models.ActivityUploadDTO
import org.treeo.treeo.network.models.BinaryDataDTO
import org.treeo.treeo.network.models.MeasurementDTO
import org.treeo.treeo.repositories.DBMainRepository
import org.treeo.treeo.util.*
import java.io.File
@HiltWorker
class UploadQueueWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val preferences: SharedPreferences,
private val requestManager: RequestManager,
private val dbMainRepository: DBMainRepository,
private val activityDao: ActivityDao,
private val dispatcher: IDispatcherProvider
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val uploadQueue = getUploadQueueOnce()
return if (uploadQueue.isNotEmpty()) {
var shouldRetryUpload = false
for (item in uploadQueue) {
val uploadFailed = uploadQueueItem(item)
if (uploadFailed != null) {
shouldRetryUpload = true
}
}
if (shouldRetryUpload) Result.retry() else Result.success()
} else {
Result.success()
}
}
private suspend fun getUploadQueueOnce(): List<UploadQueueEntity> {
return withContext(dispatcher.io()) {
activityDao.getUploadQueueSync()
}
}
/**
* Uploads a single queue item depending on its content type.
* @param item The item to be uploaded.
* @return true if the upload failed, null if the upload was successful.
*/
private suspend fun uploadQueueItem(item: UploadQueueEntity): Boolean? {
var shouldRetryUpload: Boolean?
try {
var responseCode = 0
when (item.type) {
"questionnaire" -> {
val questionnaireData = Gson().fromJson(
item.activityData,
ActivityUploadDTO::class.java
)
responseCode =
uploadQuestionnaireData(mapOf("activity" to questionnaireData))
}
ACTIVITY_TYPE_LAND_SURVEY -> {
val measurementData = Gson().fromJson(
item.activityData,
MeasurementDTO::class.java
)
responseCode = uploadMeasurementData(measurementData)
}
"binary_upload" -> {
val binaryData = Gson().fromJson(
item.activityData,
BinaryDataDTO::class.java
)
responseCode = uploadBinaryData(binaryData)
}
ACTIVITY_TYPE_TREE_MONITORING, ACTIVITY_FOREST_INVENTORY -> {
val treeMonitoringData = Gson().fromJson(
item.activityData,
ActivityUploadDTO::class.java
)
responseCode =
uploadQuestionnaireData(mapOf("activity" to treeMonitoringData))
}
SUB_ACTIVITY_TYPE_TREE_MEASUREMENT -> {
val measurementData = Gson().fromJson(
item.activityData,
MeasurementDTO::class.java
)
responseCode = uploadMeasurementData(measurementData)
}
}
shouldRetryUpload = if (responseCode == 201) {
deleteUploadedActivity(item.activityId, item.id)
null
} else if (responseCode == 400 || responseCode == 404 || responseCode == 422 || responseCode == 500) {
true
} else {
true
}
} catch (e: Exception) {
shouldRetryUpload = true
}
return shouldRetryUpload
}
private suspend fun uploadQuestionnaireData(
dataMap: Map<String, ActivityUploadDTO>
): Int {
return requestManager.createActivity(dataMap)
}
private suspend fun uploadMeasurementData(measurement: MeasurementDTO): Int {
return requestManager.uploadMeasurementData(measurement)
}
private suspend fun uploadBinaryData(binaryDataDTO: BinaryDataDTO): Int {
val file = File(binaryDataDTO.file)
val fileRequestBody = file
.asRequestBody("multipart/form-file".toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData(
"file",
file.name,
fileRequestBody
)
val measurementId = binaryDataDTO.measurementId
val measurementRequestBody = RequestBody.create(
"text/plain".toMediaTypeOrNull(),
measurementId
)
return requestManager.uploadBinaryData(
filePart,
measurementRequestBody
)
}
private suspend fun deleteUploadedActivity(activityId: Long, queueItemId: Long) {
// TODO: Delete queue item instead of simply marking it as not for upload
dbMainRepository.markQueueItemAsUploaded(activityId, queueItemId)
}
}
| 0 | Kotlin | 0 | 0 | 2e3e780e325cb97c72a79d9d22fc7ac053fee350 | 5,875 | treeo2-mobile-app-open | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/subjectaccessrequestapi/config/AuthAwareAuthenticationToken.kt | ministryofjustice | 712,487,650 | false | {"Kotlin": 105831, "Dockerfile": 1374} | package uk.gov.justice.digital.hmpps.subjectaccessrequestapi.config
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
class AuthAwareAuthenticationToken(
jwt: Jwt,
private val aPrincipal: String,
authorities: Collection<GrantedAuthority>,
) : JwtAuthenticationToken(jwt, authorities) {
override fun getPrincipal(): String {
return aPrincipal
}
}
| 4 | Kotlin | 1 | 1 | 23349095fa075347ee75dcca8c67ed907c42f272 | 518 | hmpps-subject-access-request-api | MIT License |
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/domain/model/Tariff.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 518481, "Swift": 693} | /*
* Copyright (c) 2024. <NAME>
* https://github.com/ryanw-mobile
* Sponsored by RW MobiMedia UK Limited
*
*/
package com.rwmobi.kunigami.domain.model
import androidx.compose.runtime.Immutable
@Immutable
data class Tariff(
val code: String,
val fullName: String,
val displayName: String,
val vatInclusiveUnitRate: Double,
val vatInclusiveStandingCharge: Double,
)
| 24 | Kotlin | 0 | 2 | 241e0ea08e92d663e8c9fb2732627dc054e24db6 | 392 | OctoMeter | MIT License |
app/src/main/kotlin/ru/cherryperry/amiami/screen/activity/OnBackKeyPressedListener.kt | wargry | 139,280,084 | true | {"Kotlin": 102696} | package ru.cherryperry.amiami.screen.activity
interface OnBackKeyPressedListener {
fun onBackPressed(): Boolean
} | 0 | Kotlin | 0 | 0 | ada84ecfc0a574380f49446048be4e550a7ed018 | 119 | Amiami-android-app | Apache License 2.0 |
app/src/main/java/com/databrains/bi4ss/models/StatisticsResponse.kt | DatabrainsDz | 163,342,179 | false | null | package com.databrains.bi4ss.models
import com.google.gson.annotations.SerializedName
class StatisticsResponse(@SerializedName("title") val title: String,
@SerializedName("status") val status: String,
@SerializedName("data") val data: DataStats) | 0 | Kotlin | 0 | 1 | fd2b9f5c11e036a640928d74f0e94a0e95a369a7 | 297 | BI4SS-Android | Apache License 2.0 |
app/src/main/java/com/weighttracker/screen/converter/ConverterState.kt | nicolegeorgieva | 556,229,503 | false | {"Kotlin": 221653} | package com.weighttracker.screen.converter
data class ConverterState(
val lb: Double?,
val kg: Double?,
val feet: Double?,
val m: Double?
) | 0 | Kotlin | 0 | 5 | 9df6604d4968d62958667658a33ee7cb64c86db7 | 156 | weight-tracker-android | MIT License |
kotlin/ex-200/src/second/210804-2-078-ElvisOperator.kt | cureasher | 388,688,952 | false | null | package code.second
fun main(args: Array<String>) {
val numbernull: Int? = null
println(numbernull ?: 0)
val numberfifteen: Int? = 15
println(numberfifteen ?: 0)
var text: String? = null
println(text ?: "Hello")
} | 0 | Kotlin | 0 | 0 | 9893a70ed6b1400bc7a2e004d4f400760f46fb42 | 239 | TIL | MIT License |
app/src/debug/java/com/serj113/imaginemovies/wrapper/DebugApplicationWrapperImpl.kt | serj113 | 260,604,628 | false | null | package com.serj113.imaginemovies.wrapper
import android.app.Application
class DebugApplicationWrapperImpl : ApplicationWrapper {
override fun setupFlipper(application: Application) {
FlipperDeps.setup(application)
}
} | 0 | Kotlin | 0 | 4 | c20db689fd0236df08237adb0c948586eef83ab0 | 236 | Imagine-Movies | Apache License 2.0 |
node/src/main/kotlin/me/slavita/construction/world/GameWorld.kt | Roman-Andr | 535,243,293 | false | {"Kotlin": 482345} | package me.slavita.construction.world
import me.func.MetaWorld
import me.func.builder.MetaSubscriber
import me.func.mod.reactive.ReactivePlace
import me.func.unit.Building
import me.func.world.WorldMeta
import me.slavita.construction.app
import me.slavita.construction.city.CityGlows
import me.slavita.construction.city.SpeedPlaces
import me.slavita.construction.city.showcase.Showcases
import me.slavita.construction.common.utils.V2i
import me.slavita.construction.common.utils.register
import me.slavita.construction.structure.WorldCell
import me.slavita.construction.ui.npc.NpcManager
import me.slavita.construction.utils.label
import me.slavita.construction.utils.labels
import org.bukkit.Location
import org.bukkit.entity.Player
import java.util.UUID
class GameWorld(val map: WorldMeta) {
val glows = hashSetOf<ReactivePlace>()
val cells = arrayListOf<WorldCell>()
var freelanceCell: WorldCell
val emptyBlock = StructureBlock(map.world.getBlockAt(0, 0, 0))
private val blocks = hashMapOf<UUID, HashMap<V2i, HashSet<StructureBlock>>>()
init {
app.mainWorld = this
MetaWorld.universe(
map.world,
*MetaSubscriber()
.customModifier { chunk ->
val chunks = blocks[chunk.owner] ?: return@customModifier chunk
val blocks = chunks[V2i(chunk.chunk.locX, chunk.chunk.locZ)] ?: return@customModifier chunk
blocks.forEach { block ->
chunk.modify(
block.position,
block.sourceCraftData
)
}
chunk
}
.buildingLoader { building ->
val user = app.getUserOrNull(building) ?: return@buildingLoader arrayListOf()
val buildings = arrayListOf<Building>()
user.data.cities.forEach { city ->
city.cityStructures.forEach { structure ->
buildings.add(
structure.building.apply {
show(user.player)
}
)
}
city.cityCells.forEach { cityCell ->
buildings.add(cityCell.worldCell.stubBuilding)
}
}
buildings
}.build()
)
labels("place").forEachIndexed { index, label ->
cells.add(WorldCell(index, label).apply { allocate() })
}
freelanceCell = WorldCell(0, label("freelance")!!).apply { allocate() }
register(
NpcManager,
CityGlows,
SpeedPlaces,
Showcases
)
}
@Suppress("DEPRECATION")
fun placeFakeBlock(player: Player, block: StructureBlock, save: Boolean = true) {
player.sendBlockChange(
Location(map.world, block.position.x.toDouble(), block.position.y.toDouble(), block.position.z.toDouble()),
block.type,
block.sourceData
)
if (save) {
val chunk = V2i(block.position.x / 16, block.position.z / 16)
blocks.getOrPut(player.uniqueId) { hashMapOf() }.getOrPut(chunk) { hashSetOf() }.add(block)
}
}
fun clearBlocks(player: UUID) {
blocks[player]?.clear()
}
}
| 0 | Kotlin | 0 | 1 | e4e3c255bbfdfb5369ca66e57842e2c8712d2a10 | 3,488 | simulator-mayor | Apache License 2.0 |
settings/src/main/java/org/futo/circles/settings/feature/advanced/AdvancedSettingsDialogFragment.kt | circles-project | 615,347,618 | false | {"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922} | package org.futo.circles.settings.feature.advanced
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
import org.futo.circles.core.base.fragment.BaseFullscreenDialogFragment
import org.futo.circles.core.extensions.showNoInternetConnection
import org.futo.circles.core.provider.PreferencesProvider
import org.futo.circles.core.utils.LauncherActivityUtils
import org.futo.circles.settings.databinding.DialogFragmentAdvancedSettingsBinding
@AndroidEntryPoint
class AdvancedSettingsDialogFragment :
BaseFullscreenDialogFragment<DialogFragmentAdvancedSettingsBinding>(
DialogFragmentAdvancedSettingsBinding::inflate
) {
private val preferencesProvider by lazy { PreferencesProvider(requireContext()) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViews()
}
private fun setupViews() {
with(binding) {
lPhotos.setOnClickListener { togglePhotos() }
lDevMode.setOnClickListener { toggleDeveloperMode() }
tvClearCache.setOnClickListener { clearCacheAndReload() }
svDevMode.isChecked = preferencesProvider.isDeveloperModeEnabled()
svPhotos.isChecked = preferencesProvider.isPhotoGalleryEnabled()
}
}
private fun clearCacheAndReload() {
if (showNoInternetConnection()) return
(activity as? AppCompatActivity)?.let {
LauncherActivityUtils.clearCacheAndRestart(it)
}
}
private fun toggleDeveloperMode() {
val isEnabled = preferencesProvider.isDeveloperModeEnabled()
preferencesProvider.setDeveloperMode(!isEnabled)
binding.svDevMode.isChecked = !isEnabled
}
private fun togglePhotos() {
val isEnabled = preferencesProvider.isPhotoGalleryEnabled()
preferencesProvider.setPhotoGalleryEnabled(!isEnabled)
binding.svPhotos.isChecked = !isEnabled
}
} | 8 | Kotlin | 4 | 29 | 7edec708f9c491a7b6f139fc2f2aa3e2b7149112 | 2,045 | circles-android | Apache License 2.0 |
screencaptor/src/main/java/com/wealthfront/screencaptor/ScreenshotQuality.kt | wealthfront | 267,915,434 | false | {"Kotlin": 38185} | package com.wealthfront.screencaptor
/**
* Specifies the compression quality of the screenshot.
*/
enum class ScreenshotQuality(val value: Int) {
LOW(25),
MID(50),
HIGH(75),
BEST(100)
}
| 5 | Kotlin | 3 | 15 | fc84ba0d36fdbb648c3ab889ca21b96207e193e5 | 197 | screencaptor | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/LightEmergencyOn.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.LightEmergencyOn: ImageVector
get() {
if (_lightEmergencyOn != null) {
return _lightEmergencyOn!!
}
_lightEmergencyOn = Builder(name = "LightEmergencyOn", defaultWidth = 512.0.dp,
defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(24.0f, 23.0f)
horizontalLineToRelative(0.0f)
curveToRelative(0.0f, 0.552f, -0.448f, 1.0f, -1.0f, 1.0f)
lineTo(1.0f, 24.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f)
horizontalLineToRelative(0.0f)
curveToRelative(0.0f, -1.657f, 1.343f, -3.0f, 3.0f, -3.0f)
horizontalLineToRelative(18.0f)
curveToRelative(1.657f, 0.0f, 3.0f, 1.343f, 3.0f, 3.0f)
close()
moveTo(22.211f, 6.203f)
lineToRelative(1.5f, -1.517f)
curveToRelative(0.389f, -0.393f, 0.385f, -1.025f, -0.008f, -1.414f)
curveToRelative(-0.394f, -0.389f, -1.026f, -0.385f, -1.414f, 0.008f)
lineToRelative(-1.5f, 1.517f)
curveToRelative(-0.389f, 0.393f, -0.385f, 1.025f, 0.008f, 1.414f)
curveToRelative(0.195f, 0.192f, 0.449f, 0.289f, 0.703f, 0.289f)
curveToRelative(0.258f, 0.0f, 0.516f, -0.099f, 0.711f, -0.297f)
close()
moveTo(18.388f, 2.96f)
lineToRelative(0.777f, -1.5f)
curveToRelative(0.254f, -0.49f, 0.062f, -1.094f, -0.428f, -1.348f)
curveToRelative(-0.488f, -0.254f, -1.094f, -0.064f, -1.348f, 0.428f)
lineToRelative(-0.777f, 1.5f)
curveToRelative(-0.254f, 0.49f, -0.062f, 1.094f, 0.428f, 1.348f)
curveToRelative(0.146f, 0.076f, 0.304f, 0.112f, 0.459f, 0.112f)
curveToRelative(0.361f, 0.0f, 0.711f, -0.196f, 0.889f, -0.54f)
close()
moveTo(3.203f, 6.211f)
curveToRelative(0.393f, -0.389f, 0.396f, -1.021f, 0.008f, -1.414f)
lineToRelative(-1.5f, -1.517f)
curveToRelative(-0.387f, -0.393f, -1.022f, -0.396f, -1.414f, -0.008f)
curveToRelative(-0.393f, 0.389f, -0.396f, 1.021f, -0.008f, 1.414f)
lineToRelative(1.5f, 1.517f)
curveToRelative(0.195f, 0.198f, 0.453f, 0.297f, 0.711f, 0.297f)
curveToRelative(0.254f, 0.0f, 0.509f, -0.097f, 0.703f, -0.289f)
close()
moveTo(6.96f, 3.388f)
curveToRelative(0.49f, -0.254f, 0.682f, -0.857f, 0.428f, -1.348f)
lineToRelative(-0.777f, -1.5f)
curveToRelative(-0.255f, -0.492f, -0.86f, -0.682f, -1.348f, -0.428f)
curveToRelative(-0.49f, 0.254f, -0.682f, 0.857f, -0.428f, 1.348f)
lineToRelative(0.777f, 1.5f)
curveToRelative(0.178f, 0.344f, 0.527f, 0.54f, 0.889f, 0.54f)
curveToRelative(0.155f, 0.0f, 0.312f, -0.036f, 0.459f, -0.112f)
close()
moveTo(21.0f, 13.0f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.553f, -0.447f, 1.0f, -1.0f, 1.0f)
lineTo(4.0f, 18.0f)
curveToRelative(-0.553f, 0.0f, -1.0f, -0.447f, -1.0f, -1.0f)
verticalLineToRelative(-4.0f)
curveToRelative(0.0f, -4.963f, 4.037f, -9.0f, 9.0f, -9.0f)
reflectiveCurveToRelative(9.0f, 4.037f, 9.0f, 9.0f)
close()
moveTo(13.0f, 10.0f)
curveToRelative(0.0f, -0.553f, -0.447f, -1.0f, -1.0f, -1.0f)
curveToRelative(-2.206f, 0.0f, -4.0f, 1.794f, -4.0f, 4.0f)
curveToRelative(0.0f, 0.553f, 0.447f, 1.0f, 1.0f, 1.0f)
reflectiveCurveToRelative(1.0f, -0.447f, 1.0f, -1.0f)
curveToRelative(0.0f, -1.103f, 0.897f, -2.0f, 2.0f, -2.0f)
curveToRelative(0.553f, 0.0f, 1.0f, -0.447f, 1.0f, -1.0f)
close()
}
}
.build()
return _lightEmergencyOn!!
}
private var _lightEmergencyOn: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,053 | icons | MIT License |
HenCoderSample/app/src/main/java/com/apkfuns/hencodersample/CustomView.kt | pengwei1024 | 81,442,430 | false | {"Java": 91397, "Kotlin": 39733, "Objective-C": 31279, "C++": 6937, "CMake": 3430, "HTML": 1446, "Ruby": 516, "Shell": 336} | package com.apkfuns.hencodersample
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
/**
* Created by pengwei on 2017/12/6.
*/
class CustomView : View {
private val paint: Paint = Paint()
private val rectPaint:Paint = Paint()
private val rectF = RectF(400f, 50f, 700f, 400f)
private val PinkPaint = Paint()
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(context, attrs, defStyleAttr, 0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
PinkPaint.color = Color.parseColor("#66ffaaff")
paint.isAntiAlias = true
paint.style = Paint.Style.STROKE
paint.strokeWidth = 10f
canvas?.drawCircle(300f, 300f, 200f, paint)
rectPaint.color = Color.parseColor("#88880000")
canvas?.drawRect(100f, 100f, 500f, 500f, rectPaint)
canvas?.drawPoint(800f, 400f, paint)
// 绘制多个点
var points = floatArrayOf(0f, 0f, 50f, 50f, 50f, 100f, 100f, 50f, 100f, 100f, 150f, 50f, 150f, 100f)
canvas?.drawPoints(points, 2 /* 跳过两个数,即前两个 0 */,
8 /* 一共绘制 8 个数(4 个点)*/, paint)
// 绘制椭圆
canvas?.drawOval(rectF, paint)
// 绘制多条线
points = floatArrayOf(20f, 20f, 120f, 20f, 70f, 20f, 70f, 120f, 20f, 120f, 120f, 120f, 150f, 20f, 250f, 20f, 150f, 20f, 150f, 120f, 250f, 20f, 250f, 120f, 150f, 120f, 250f, 120f)
canvas?.drawLines(points, paint)
// 圆角矩形
canvas?.drawRoundRect(rectF, 50f, 50f, PinkPaint)
// 画扇形
val rectF = RectF(200f, 600f, 800f, 1000f)
canvas?.drawArc(rectF, 180f, 180f, false, rectPaint)
// 绘制图片
val options = BitmapFactory.Options()
options.inSampleSize = 1
val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher, options)
canvas?.drawBitmap(bitmap, 0f, 600f, paint)
// 绘制文字
val textPaint = Paint()
textPaint.textSize = 72f
canvas?.drawText("Hello world", 0f, 800f, textPaint)
}
} | 1 | null | 1 | 1 | b3e7b092f4eff16f03cc5c8aa8fc42c5ee87e89c | 2,370 | sampleShare | Apache License 2.0 |
android/app/src/main/java/com/algorand/android/modules/swap/previewsummary/ui/usecase/SwapPreviewSummaryPreviewUseCase.kt | perawallet | 364,359,642 | false | {"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596} | /*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.swap.previewsummary.ui.usecase
import com.algorand.android.modules.accounticon.ui.usecase.CreateAccountIconDrawableUseCase
import com.algorand.android.modules.accounts.domain.usecase.AccountDisplayNameUseCase
import com.algorand.android.modules.currency.domain.model.Currency
import com.algorand.android.modules.swap.assetswap.domain.model.SwapQuote
import com.algorand.android.modules.swap.previewsummary.ui.mapper.SwapPreviewSummaryPreviewMapper
import com.algorand.android.modules.swap.previewsummary.ui.model.SwapPreviewSummaryPreview
import com.algorand.android.modules.swap.utils.getFormattedMinimumReceivedAmount
import com.algorand.android.modules.swap.utils.priceratioprovider.SwapPriceRatioProviderMapper
import com.algorand.android.utils.formatAsCurrency
import com.algorand.android.utils.formatAsPercentage
import javax.inject.Inject
class SwapPreviewSummaryPreviewUseCase @Inject constructor(
private val swapPriceRatioProviderMapper: SwapPriceRatioProviderMapper,
private val swapPreviewSummaryPreviewMapper: SwapPreviewSummaryPreviewMapper,
private val accountDisplayNameUseCase: AccountDisplayNameUseCase,
private val createAccountIconDrawableUseCase: CreateAccountIconDrawableUseCase
) {
fun getInitialPreview(swapQuote: SwapQuote): SwapPreviewSummaryPreview {
return with(swapQuote) {
swapPreviewSummaryPreviewMapper.mapToSwapPreviewSummaryPreview(
priceRatioProvider = swapPriceRatioProviderMapper.mapToSwapPriceRatioProvider(swapQuote),
slippageTolerance = slippage.formatAsPercentage(),
priceImpact = priceImpact.toString(),
minimumReceived = getFormattedMinimumReceivedAmount(swapQuote),
formattedExchangeFee = exchangeFeeAmount.formatAsCurrency(Currency.ALGO.symbol),
formattedPeraFee = peraFeeAmount.formatAsCurrency(Currency.ALGO.symbol),
formattedTotalFee = totalFee.formatAsCurrency(Currency.ALGO.symbol),
accountDisplayName = accountDisplayNameUseCase.invoke(swapQuote.accountAddress),
accountIconDrawablePreview = createAccountIconDrawableUseCase.invoke(accountAddress)
)
}
}
}
| 22 | Swift | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 2,839 | pera-wallet | Apache License 2.0 |
ui-components/src/main/java/com/example/ui_components/buttons/AnonymousButton.kt | 4mr0m3r0 | 259,181,662 | false | {"Kotlin": 58386} | package com.example.ui_components.buttons
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.ui_components.R
import com.example.ui_components.theme.DesignSystemTheme
@Composable
fun AnonymousButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
text: String
) {
OutlinedButton(onClick = onClick, modifier = modifier, enabled = enabled) {
Icon(painter = painterResource(id = R.drawable.incognito), contentDescription = null)
Text(text = text, modifier = Modifier.padding(start = 8.dp))
}
}
@Preview("Light")
@Composable
private fun Light() {
DesignSystemTheme {
Surface {
AnonymousButton(onClick = { /*TODO*/ }, text = "Anonymous Button")
}
}
}
@Preview("Dark")
@Composable
private fun Dark() {
DesignSystemTheme(darkTheme = true) {
Surface {
AnonymousButton(onClick = { /*TODO*/ }, text = "Anonymous Button")
}
}
} | 0 | Kotlin | 1 | 4 | f8c1723b4e547fcfc0f9eba1727ec719a909cdf5 | 1,360 | composing-atomic-design | MIT License |
app/src/main/java/com/example/mcdonalds/model/DownloadManager.kt | AlexTesta00 | 481,898,468 | false | null | package com.example.mcdonalds.model
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.mcdonalds.controller.CategoryAdapter
import com.example.mcdonalds.controller.ProductAdapter
import com.example.mcdonalds.utils.MessageManager
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.*
import kotlinx.coroutines.tasks.await
import java.lang.Exception
import java.lang.IllegalStateException
import java.util.stream.Collectors
@Suppress("OPT_IN_IS_NOT_ENABLED")
@OptIn(DelicateCoroutinesApi::class)
class DownloadManager (private var itemsView: RecyclerView,
private var categoryView: RecyclerView,
private var defaultCategory : Category,
private var currentActivity : AppCompatActivity){
//Primary Constructors
init {
//Download All Items
this.downloadItems()
//Download All Categories
this.downloadCategories()
}
companion object{
private var mcItems : MutableList<McItem> = mutableListOf()
private var categories : MutableList<Category> = mutableListOf()
fun getItemsFromName(vararg itemName : String) : MutableList<McItem>{
val list = mutableListOf<McItem>()
if(!itemsAreEmpty()){
itemName.forEach { name ->
val correctElements = mcItems.stream().filter { it.getName() == name }.findAny()
if(correctElements.isPresent){
list.add(correctElements.get())
}
}
}else{
throw IllegalStateException("Class DownloadManager not instantiated")
}
return list
}
private fun itemsAreEmpty() : Boolean{
return mcItems.isEmpty()
}
private fun categoriesAreEmpty() : Boolean{
return categories.isEmpty()
}
}
/*This is caused because firebase return an ArrayList of element
* but kotlin compiler know element of instance Any?*/
@Suppress("UNCHECKED_CAST")
private fun downloadItems() {
if(itemsAreEmpty()){
GlobalScope.launch(Dispatchers.IO) {
val db = Firebase.firestore
db.collection("item")
.get()
.addOnSuccessListener {
for (document in it) {
val pseudoCategory = document["category"] as DocumentReference
val category = Category(pseudoCategory.id)
//SingleMcItem Attribute
val ingredientsItem: MutableList<DocumentReference> =
document["ingredients"] as MutableList<DocumentReference>
val ingredients: MutableList<Ingredient> = mutableListOf()
val name: String = document["name"] as String
val image: String = document["image"] as String
val imageDescription: String = document["imageDescription"] as String
val singlePrice: Double = document["singlePrice"] as Double
//Recover All Ingredient
for (ingredient in ingredientsItem) {
//Recover Ingredient and Add on Ingredients list
db.document(ingredient.path)
.get()
.addOnSuccessListener { currentItem ->
val weight = (currentItem["weight"] as Long).toFloat()
val nameOfItem = currentItem["name"] as String
val imageOfItem = currentItem["image"] as String
val calories = (currentItem["calories"] as Long).toInt()
var modifiable = (currentItem["modifiable"] as Boolean?)
if (modifiable == null) {
modifiable = false
}
ingredients.add(
Ingredient(
nameOfItem,
imageOfItem,
modifiable,
weight,
calories
)
)
}
}
//Add Ingredients On List
mcItems.add(
SingleMcItem(
name,
image,
imageDescription,
singlePrice,
category,
ingredients
)
)
}
}
.addOnFailureListener {
throw Exception("Download Items Failed : $it")
}.await()
withContext(Dispatchers.Main){
updateItems(itemsView, defaultCategory)
}
}
}else{
updateItems(itemsView, defaultCategory)
}
}
private fun downloadCategories() {
if(categoriesAreEmpty()){
GlobalScope.launch(Dispatchers.IO) {
val db = Firebase.firestore
db.collection("category")
.get()
.addOnSuccessListener {
for (document in it){
categories.add(Category(document.id))
}
}
.addOnFailureListener{
throw Exception("Download Category Failed : $it")
}
.await()
withContext(Dispatchers.Main){
updateCategories(categoryView)
}
}
}else{
updateCategories(categoryView)
}
}
private fun getItemsByCategory(category: Category) : MutableList<McItem>{
return mcItems.stream().filter{it.getCategory() == category.name}.collect(Collectors.toList())
}
private infix fun updateCategories(recyclerView: RecyclerView){
val adapter = CategoryAdapter(categories)
recyclerView.adapter = adapter
}
private fun updateItems(recyclerView: RecyclerView, category: Category){
val adapter = ProductAdapter(this.getItemsByCategory(category),
this.currentActivity)
recyclerView.adapter = adapter
}
fun changeCurrentCategory(newCategory: Category){
this.updateItems(this.itemsView, newCategory)
}
@Suppress("UNCHECKED_CAST")
fun recoverHistory(idOrder : String, activity : Activity){
GlobalScope.launch(Dispatchers.IO) {
val database = Firebase.database
val reference = database.reference
reference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.value != null){
val value = snapshot.value as Map<String, Map<String,List<String>>>
val containsKey = value.values.stream().map{it.keys}.filter{it.contains(idOrder)}.count()
if(containsKey > 0){
//Get List of Items
val items = value.values.stream()
.map{ it[idOrder]}
.collect(Collectors.toList())
MessageManager.displayReplaceOrderMessage(activity as AppCompatActivity,
idOrder,
*items[0]!!.toTypedArray())
}else{
MessageManager.displayNoHolderOrderPresent(activity)
}
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
} | 0 | Kotlin | 0 | 0 | c2648c80ed70804dde353a57bf7ea8b01840603a | 9,192 | McDonaldsApp | Apache License 2.0 |
src/main/kotlin/devs/delminius/plugins/Koin.kt | MilicTG | 438,282,980 | false | {"Kotlin": 31091, "HTML": 7785, "Shell": 7548, "JavaScript": 5252, "Batchfile": 4533, "CSS": 3780, "Assembly": 10} | package devs.delminius.plugins
import devs.delminius.di.koinModule
import io.ktor.application.*
import org.koin.ktor.ext.Koin
import org.koin.logger.slf4jLogger
fun Application.configureKoin() {
install(Koin) {
// slf4jLogger()
modules(koinModule)
}
} | 0 | Kotlin | 0 | 0 | 74c6989c0ae937331479d36e596615c0c9a6fe02 | 276 | BorutoServer | MIT License |
app/src/main/java/isel/pdm/ee/battleship/game/domain/Coordinates.kt | RaulJCS5 | 687,139,113 | false | {"Kotlin": 192619} | package isel.pdm.ee.battleship.game.domain
const val BOARD_SIDE = 10
/**
* Represents coordinates in the board.
* @property row The row of the coordinate.
* @property column The column of the coordinate.
*/
data class Coordinate(val row: Int, val column: Int) {
init {
require(isValidRow(row) && isValidColumn(column))
}
override fun toString(): String {
return "($row,$column)"
}
}
/**
* Checks whether [value] is a valid row index
*/
fun isValidRow(value: Int) = value in 0 until BOARD_SIDE
/**
* Checks whether [value] is a valid column index
*/
fun isValidColumn(value: Int) = value in 0 until BOARD_SIDE
| 0 | Kotlin | 0 | 0 | 398944274ea3b4cfcf092f204a71b07ec46c6352 | 654 | battleships-ee | MIT License |
api-tester/src/main/java/com/revenuecat/apitester/kotlin/PresentedOfferingContextAPI.kt | RevenueCat | 127,346,826 | false | {"Kotlin": 2863661, "Java": 78781, "Ruby": 27742, "Shell": 443} | package com.revenuecat.apitester.kotlin
import com.revenuecat.purchases.PresentedOfferingContext
@Suppress("unused", "UNUSED_VARIABLE")
private class PresentedOfferingContextAPI {
fun check(presentedOfferingContext: PresentedOfferingContext) {
val offeringIdentifier: String = presentedOfferingContext.offeringIdentifier
}
fun checkConstructor(offeringId: String) {
val presentedOfferingContext = PresentedOfferingContext(offeringId)
}
}
| 22 | Kotlin | 41 | 220 | 6bac0e0da280cb49450990c3967c66156d5f126d | 473 | purchases-android | MIT License |
src/main/kotlin/no/fintlabs/operator/api/Constants.kt | FINTLabs | 540,843,912 | false | {"Kotlin": 125215, "Smarty": 1822, "Dockerfile": 157} | package no.fintlabs.operator.api
const val DEPLOYMENT_CORRELATION_ID_ANNOTATION = "fintlabs.no/deployment-correlation-id"
val MANAGED_BY_FLAISERATOR_LABEL = "app.kubernetes.io/managed-by" to "flaiserator"
const val MANAGED_BY_FLAISERATOR_SELECTOR = "app.kubernetes.io/managed-by=flaiserator"
const val ORG_ID_LABEL = "fintlabs.no/org-id"
const val TEAM_LABEL = "fintlabs.no/team"
const val LOKI_LOGGING_LABEL = "observability.fintlabs.no/loki" | 0 | Kotlin | 0 | 0 | 9e75df325ef180cd32a1dc1e8b770228d136cb8d | 447 | flaiserator | MIT License |
ksoc-client-shared/src/commonMain/kotlin/com/kotlineering/ksoc/client/domain/auth/AuthService.kt | redefinescience | 613,084,470 | false | null | package com.kotlineering.ksoc.client.domain.auth
import com.kotlineering.ksoc.client.domain.ServiceResult
import com.kotlineering.ksoc.client.remote.ApiResult
import com.kotlineering.ksoc.client.domain.user.UserInfo
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.datetime.Clock
class AuthService(
private val authRepository: AuthRepository,
private val dispatcher: CoroutineDispatcher
) {
enum class AuthType {
Microsoft, Google, Apple, Facebook,
}
private fun authStateFromAuthInfo(authInfo: AuthInfo?) = when {
authInfo == null -> AuthState.NoUser
authInfo.userInfo == null -> AuthState.NoProfile(authInfo.userId)
else -> AuthState.LoggedIn(authInfo.userInfo)
}
val currentAuthState get() = authStateFromAuthInfo(authRepository.authInfo.value)
val authState = authRepository.authInfo.map {
authStateFromAuthInfo(it)
}.distinctUntilChanged()
val userId = authRepository.authInfo.map { it?.userId }
val userInfo = authRepository.authInfo.map { it?.userInfo }
// To be used during activity onCreate()
// Conditionally run this (based on expiry etc..),
// Do not set content until this is complete
fun refreshToken() = flow {
emit(authRepository.performManualRefresh())
}.flowOn(dispatcher)
fun logout() = flow {
authRepository.performLogout()
emit(ServiceResult.Success(null))
}.flowOn(dispatcher)
fun login(type: AuthType, code: String) = flow {
emit(
when (val result = authRepository.performLogin(type, code)) {
is ApiResult.Success -> ServiceResult.Success(result.data.userId)
is ApiResult.Failure -> ServiceResult.Failure("Login Failure")
}
)
}.flowOn(dispatcher)
fun updateProfile(
userInfo: UserInfo
) = flow {
emit(
when (val result = authRepository.performUpdateProfile(userInfo)) {
is ApiResult.Success -> ServiceResult.Success(result.data)
is ApiResult.Failure -> ServiceResult.Failure("Failed to update user profile")
}
)
}.flowOn(dispatcher)
// TODO: Temp
fun loginFake(type: AuthType, code: String) {
authRepository.setAuthInfo(
AuthInfo(
"testUer($type)",
code,
Clock.System.now(),
"testRefresh",
Clock.System.now(),
null
)
)
}
}
| 6 | Kotlin | 0 | 0 | ffda4017261729c2792d946c5a514dd1eb31532c | 2,688 | ksoc-client | Apache License 2.0 |
core/main/kotlin/me/kgustave/dkt/core/internal/websocket/handlers/GuildMemberRemoveHandler.kt | Shengaero | 151,363,236 | false | null | /*
* Copyright 2018 <NAME>
*
* 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 me.kgustave.dkt.core.internal.websocket.handlers
import me.kgustave.dkt.core.internal.cache.EventCache
import me.kgustave.dkt.core.internal.data.events.RawGuildMemberRemoveEvent
import me.kgustave.dkt.core.internal.entities.DiscordBotImpl
import me.kgustave.dkt.core.internal.entities.MemberImpl
import me.kgustave.dkt.core.internal.websocket.DiscordWebSocket
import me.kgustave.dkt.core.internal.websocket.Payload
internal class GuildMemberRemoveHandler(bot: DiscordBotImpl): WebSocketHandler(bot) {
override fun handle(payload: Payload) {
val event = payload.d as RawGuildMemberRemoveEvent
if(bot.guildSetupManager.removeMember(event.guildId, event.user)) return
val guild = bot.guildCache[event.guildId] ?: return DiscordWebSocket.Log.debug(
"Received GUILD_MEMBER_REMOVE event for guild that was not cached! " +
"This is likely a guild that was left!"
)
val member = guild.memberCache.remove(event.user.id) as? MemberImpl ?:
return logUnCachedEntity("GUILD_MEMBER_REMOVE", "member", event.user.id)
val voiceState = member.voiceState
val connectedVoiceChannel = voiceState.channel
if(connectedVoiceChannel != null) {
voiceState.channel = null
connectedVoiceChannel.connectedMembers.remove(member.user.id)
// TODO Event
}
// the member is not us and it's not in any other guilds, so we need to remove it
if(member.user.id != bot.self.id && bot.guildCache.values.none { member.user.id in it.memberCache }) {
val user = bot.userCache.remove(member.user.id)!!
user.privateChannel?.let { privateChannel ->
user.untracked = true
privateChannel.untracked = true
bot.untrackedUsers[user.id] = user
bot.untrackedPrivateChannels[privateChannel.id] = privateChannel
}
bot.eventCache.clear(EventCache.Type.USER, user.id)
}
// TODO Event
}
}
| 1 | Kotlin | 0 | 10 | 745f72c59ed8e331975f0f62057f8f09fb9722fc | 2,644 | discord.kt | Apache License 2.0 |
src/main/kotlin/website/cousinomath/Scanner.kt | CousinoMath | 190,498,147 | false | null | package website.cousinomath
class Scanner(val source: String) {
val length = this.source.length
var tokens: MutableList<Token> = ArrayList<Token>()
var start = 0
var current = 0
val constants = setOf("e", "pi")
val functions = setOf("acos", "asin", "atan", "cos", "exp", "log", "sin", "tan")
fun lex(): Result<List<Token>, String> {
if (current == 0) {
while (current < length) {
skipWhitespace()
if (current >= length) { break; }
start = current
advance()
val result = lexToken()
if (result.isErr) {
return Err(result.err!!);
}
tokens.add(result.ok!!)
}
tokens.add(Token(TokenType.EOI, "♠"))
}
return Ok<List<Token>, String>(tokens)
}
private fun advance() {
if (current < length) {
current += 1
}
}
private fun skipWhitespace() {
while (current < length && source[current] == ' ') {
advance()
}
}
private fun substring(): String = source.substring(start, current)
private fun lexToken(): Result<Token, String> {
return when (source[start]) {
'+' -> Ok<Token, String>(Token(TokenType.PLUS, "+"))
'-' -> Ok<Token, String>(Token(TokenType.DASH, "-"))
'*' -> Ok<Token, String>(Token(TokenType.STAR, "*"))
'/' -> Ok<Token, String>(Token(TokenType.SLASH, "/"))
'=' -> Ok<Token, String>(Token(TokenType.EQUALS, "="))
'(' -> Ok(Token(TokenType.LPAREN, "("))
')' -> Ok(Token(TokenType.RPAREN, ")"))
'^' -> Ok(Token(TokenType.CARET, "^"))
in '0'..'9', '.' -> lexNumber()
in 'a'..'z', in 'A'..'Z' -> lexIdentifier()
else -> Err<Token, String>("Unrecognized token ${source[start]}.")
}
}
private fun lexNumber(): Result<Token, String> {
while (current < length && (source[current] in '0'..'9' || source[current] == '.')) {
advance()
}
val substr = substring()
try {
return Ok(Token(TokenType.NUMBER, substr, java.lang.Double.parseDouble(substr)))
} catch(nfe: NumberFormatException) {
return Err(nfe.getLocalizedMessage())
}
}
private fun lexIdentifier(): Result<Token, String> {
while (current < length && (source[current] in 'a'..'z' || source[current] in 'A'..'Z')) {
advance()
}
val substr = substring()
return when (substr) {
in constants -> Ok<Token, String>(Token(TokenType.CONSTANT, substr))
in functions -> Ok<Token, String>(Token(TokenType.FUNCTION, substr))
else -> Ok<Token, String>(Token(TokenType.VARIABLE, substr))
}
}
} | 0 | Kotlin | 0 | 0 | b64a0d14d5a0cbfacdae732cdbc611ae80f951df | 2,563 | kt-calculator | MIT License |
src/client/kotlin/dev/dakoda/dvr/skills/gui/DVRSkillsGUI.kt | vanilla-refresh | 707,433,202 | false | {"Kotlin": 116265, "Java": 31150} | package dev.dakoda.dvr.skills.gui
import net.minecraft.util.Identifier
object DVRSkillsGUI {
val EXP_BAR_LONG_EMPTY = Identifier("dvr-skills", "menu/exp_bar_long_empty")
val EXP_BAR_LONG_EMPTY_HOVERED = Identifier("dvr-skills", "menu/exp_bar_long_empty_hovered")
val EXP_BAR_LONG_FULL = Identifier("dvr-skills", "menu/exp_bar_long_full")
val EXP_BAR_LONG_FULL_HOVERED = Identifier("dvr-skills", "menu/exp_bar_long_full_hovered")
val EXP_BAR_SHORT_EMPTY = Identifier("dvr-skills", "menu/exp_bar_short_empty")
val EXP_BAR_SHORT_FULL = Identifier("dvr-skills", "menu/exp_bar_short_full")
val EXP_BAR_SHORT_GAIN = Identifier("dvr-skills", "menu/exp_bar_short_gain")
val PIN_SELECTED = Identifier("dvr-skills", "menu/pin_selected")
val PIN_UNSELECTED = Identifier("dvr-skills", "menu/pin_unselected")
val WINDOW = Identifier("dvr-skills", "menu/window")
val WINDOW_DECOR = Identifier("dvr-skills", "menu/window_decor")
}
| 0 | Kotlin | 0 | 0 | 8237fac7fdb9c3ff7645786b5c39fd9e9c4e701e | 962 | dvr-skills | MIT License |
api/src/main/kotlin/glimpse/models/Model.kt | glimpse-graphics | 44,015,157 | false | {"Kotlin": 207226, "GLSL": 7035} | package glimpse.models
import glimpse.Matrix
import glimpse.MatrixBuilder
import glimpse.matrix
/**
* A three-dimensional model.
*
* @param mesh Mesh defining model's surface.
* @param transformation Model transformation matrix lambda.
*/
class Model(val mesh: Mesh, val transformation: () -> Matrix = { Matrix.IDENTITY }) {
/**
* Returns a [Model], transformed with the [transformationMatrix].
*/
fun transform(transformationMatrix: Matrix) =
Model(mesh) { transformationMatrix * transformation() }
/**
* Returns a [Model], transformed with the [transformation].
*/
fun transform(transformation: MatrixBuilder.() -> Unit) =
Model(mesh, matrix(this.transformation, transformation))
}
| 0 | Kotlin | 0 | 16 | 5069cc1c3f2d8cb344740f3d33bcf11848f94583 | 711 | glimpse-framework | Apache License 2.0 |
cache/src/main/kotlin/org/openrs2/cache/MutableNamedEntry.kt | openrs2 | 315,027,372 | false | null | package org.openrs2.cache
import org.openrs2.util.krHashCode
public interface MutableNamedEntry : NamedEntry {
public override var nameHash: Int
public fun setName(name: String) {
nameHash = name.krHashCode()
}
public fun clearName() {
nameHash = -1
}
public fun remove()
}
| 0 | Kotlin | 2 | 8 | 12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b | 319 | openrs2 | ISC License |
satisfaketion-core/src/test/kotlin/io/github/rgbrizzlehizzle/satisfaketion/core/util/TestModels.kt | rgbrizzlehizzle | 368,589,852 | false | null | package io.github.rgbrizzlehizzle.satisfaketion.core.util
data class SimpleDataClass(val a: String, val b: Int)
data class AnotherSimpleClass(val c: Boolean, val d: String = "hey dude")
| 4 | Kotlin | 1 | 6 | 60e769997cf2272f90f6be13c6cf810ce50ef593 | 187 | satisfaketion | MIT License |
app/src/main/java/com/koodipuukko/dragonsquad/UnitMap.kt | tmmvn | 450,234,293 | false | {"Kotlin": 297115, "Java": 366} | package com.koodipuukko.dragonsquad
class UnitMap
| 0 | Kotlin | 0 | 1 | aa10dfac2364fd19898614fa218ba21f3964b84c | 51 | kotlin-android-game-snippets | Eiffel Forum License v2.0 |
klang/klang/src/main/kotlin/klang/parser/json/domain/Node.kt | ygdrasil-io | 634,882,904 | false | {"Kotlin": 292451, "C": 3541, "Shell": 2951, "Objective-C": 1076, "C++": 567} | package klang.parser.json.domain
import arrow.core.raise.either
import kotlinx.serialization.json.*
import mu.KotlinLogging
data class Node<T>(val content: T, val children: List<Node<T>>) {
fun notLastOf(sibling: List<Node<T>>): Boolean = sibling.last() != this
}
typealias TranslationUnitNode = Node<Pair<TranslationUnitKind, JsonObject>>
val TranslationUnitNode.kind: TranslationUnitKind
get() = content.first
val TranslationUnitNode.json: JsonObject
get() = content.second
private val logger = KotlinLogging.logger {}
internal fun JsonObject.toNode(): TranslationUnitNode = Node(
kind() to this,
this["inner"]
?.jsonArray
?.mapNotNull { (it as? JsonObject) ?: it.unknownNode() }
?.map { it.toNode() }
?: emptyList()
)
internal fun JsonObject.kind() = (this["kind"]
?.let(JsonElement::jsonPrimitive)
?.let(JsonPrimitive::content)
?.let { TranslationUnitKind.of(it) }
?: error("no kind: $this"))
private fun JsonElement.unknownNode(): JsonObject? {
logger.error { "unknown node: $this" }
return null
}
| 2 | Kotlin | 1 | 0 | 5889fb009a06f141d238587b7288ef727873253e | 1,033 | klang | MIT License |
lib/src/test/kotlin/io/kpeg/samples/seq.kt | AzimMuradov | 378,630,452 | false | null | package io.kpeg.samples
import io.kpeg.pe.Symbol.Rule
fun Rule.seq() {
// John 42 - OK
// John 402 - OK
// John -4 - FAIL
// John 0 - OK
// John 034034 - OK
// Jon 42 - FAIL
data class Person(val name: String, val age: Int)
seq<Person> {
val name = +literal("John") // EvalPE<String>
val age =
+DIGIT.oneOrMore() // EvalPE<List<Char>>
.joinToString().mapPe { it.toInt() } // EvalPE<Int>
value { Person(name.get, age.get) }
} // EvalPE<Person>
} | 0 | Kotlin | 0 | 6 | 4d05b7f82d63edb01588de7846316be1ff2cbfc7 | 645 | kpeg | Apache License 2.0 |
app/src/main/java/com/onixen/audioplayer/views/fragments/TracksListFragment.kt | Onixen | 699,858,385 | false | {"Kotlin": 35183} | package com.onixen.audioplayer.views.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.onixen.audioplayer.R
import com.onixen.audioplayer.databinding.TracksListFragmentBinding
import com.onixen.audioplayer.model.MediaPlayer
import com.onixen.audioplayer.views.adapters.TracksAdapter
class TracksListFragment: Fragment(R.layout.tracks_list_fragment) {
private var _binding: TracksListFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = TracksListFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val tracksList = mutableListOf<MediaPlayer>().apply {
add(MediaPlayer(requireContext(), R.raw.blue_light))
}
binding.recyclerTracksView.adapter = TracksAdapter(tracksList) { bind, player ->
openPlayerFragment(bind.previewCard.transitionName, bind.previewCard, player)
}
}
private fun openPlayerFragment(transitionName: String, view: View, player: MediaPlayer) {
requireActivity().supportFragmentManager
.beginTransaction()
.addSharedElement(view, transitionName)
.replace(R.id.fragmentContainer, PlayerFragment.getInstance(player))
.commit()
}
companion object {
private const val TAG = "tracks_list_fragment"
private var instance: TracksListFragment? = null
fun getInstance(): TracksListFragment {
return if (instance == null) {
instance = TracksListFragment()
instance as TracksListFragment
} else {
instance as TracksListFragment
}
}
}
} | 0 | Kotlin | 0 | 0 | dbadc0f4b7e43c9e6ba65cf4c4f0653351aa9d9a | 2,086 | player-wave-bar | Apache License 2.0 |
core/src/main/java/dev/sunnyday/core/runtime/util.kt | SunnyDayDev | 178,215,276 | false | null | package dev.sunnyday.core.runtime
/**
* Created by Aleksandr Tcikin (SunnyDay.Dev) on 2019-03-28.
* mail: [email protected]
*/
inline fun <F: Any, S: Any, T> zipIfNonNil(f: F?, s: S?, zipper: (F, S) -> T): T? {
val fNonNil = f ?: return null
val sNonNil = s ?: return null
return zipper(fNonNil, sNonNil)
}
inline fun <T> T.applyIf(predicate: (T) -> Boolean, action: T.() -> Unit): T =
if (predicate(this)) apply(action) else this
inline fun <T> T.applyIf(predicate: Boolean, action: T.() -> Unit): T = applyIf({ predicate }, action)
inline fun <T> create(block: () -> T): T = block()
@Suppress("NOTHING_TO_INLINE")
inline fun noop() = Unit | 0 | Kotlin | 0 | 0 | ec79bad3cc61ecb2e0b2fa651caa6f73ccf39b33 | 665 | core | MIT License |
remote/src/main/kotlin/io/github/gmvalentino8/github/sample/remote/models/CodeMinusScanningMinusAlertMinusDismissedMinusReasonApiModel.kt | wasabi-muffin | 462,369,263 | false | {"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812} | /**
* GitHub v3 REST API
*
* GitHub's v3 REST API.
*
* The version of the OpenAPI document: 1.1.4
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package io.github.gmvalentino8.github.sample.remote.models
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* **Required when the state is dismissed.** The reason for dismissing or closing the alert. Can be one of: `false positive`, `won't fix`, and `used in tests`.
*
* Values: `null`,falsePositive,wonQuoteTFix,usedInTests
*/
@Serializable
enum class CodeMinusScanningMinusAlertMinusDismissedMinusReasonApiModel(val value: kotlin.String) {
@SerialName(value = "null")
`null`("null"),
@SerialName(value = "false positive")
falsePositive("false positive"),
@SerialName(value = "won't fix")
wonQuoteTFix("won't fix"),
@SerialName(value = "used in tests")
usedInTests("used in tests");
/**
* Override toString() to avoid using the enum variable name as the value, and instead use
* the actual value defined in the API spec file.
*
* This solves a problem when the variable name and its value are different, and ensures that
* the client sends the correct enum values to the server always.
*/
override fun toString(): String = value
companion object {
/**
* Converts the provided [data] to a [String] on success, null otherwise.
*/
fun encode(data: Any?): kotlin.String? = if (data is CodeMinusScanningMinusAlertMinusDismissedMinusReasonApiModel) "$data" else null
/**
* Returns a valid [CodeMinusScanningMinusAlertMinusDismissedMinusReasonApiModel] for [data], null otherwise.
*/
fun decode(data: Any?): CodeMinusScanningMinusAlertMinusDismissedMinusReasonApiModel? = data?.let {
val normalizedData = "$it".lowercase()
values().firstOrNull { value ->
it == value || normalizedData == "$value".lowercase()
}
}
}
}
| 0 | Kotlin | 0 | 1 | 2194a2504bde08427ad461d92586497c7187fb40 | 2,231 | github-sample-project | Apache License 2.0 |
common/src/main/kotlin/com/scurab/kuproxy/matcher/RequestMatcher.kt | jbruchanov | 359,263,583 | false | null | package com.scurab.kuproxy.matcher
import com.scurab.kuproxy.comm.IRequest
interface RequestMatcher {
fun isMatching(real: IRequest, stored: IRequest): Boolean
}
| 0 | Kotlin | 0 | 1 | 2e10d85e7e318850679be3a21fe4406645f88811 | 168 | kuproxy | Apache License 2.0 |
Pictures.kts | tiwiz | 363,271,795 | false | null | #!/usr/bin/env kscript
@file:DependsOn("com.squareup.okhttp3:okhttp:4.9.1")
@file:DependsOn("com.fasterxml.jackson.module:jackson-module-kotlin:2.12.2")
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.introspect.VisibilityChecker
import com.fasterxml.jackson.module.kotlin.KotlinModule
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.time.LocalDateTime
val EARTH_CAM_URL =
"https://www.earthcam.com/cams/common/gethofitems.php?camera=208d600d317dc6ae2fb4bd0ca3d4746c&length=25"
data class Response(
@JsonProperty("hofdata")
val images: List<Image>
)
data class Image(
@JsonProperty("image_source")
val imageSource: String,
val description: String,
@JsonProperty("date_added")
val unixTimestamp: String
)
/**
* Output
**/
data class Storage(
val images: List<Livecam>
)
data class Livecam(
val image: String,
val description: String,
val timestamp: String
)
val client = OkHttpClient()
val mapper: ObjectMapper = ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY))
.registerModule(KotlinModule())
fun getImages(): Response {
val request: Request = Request.Builder()
.url(EARTH_CAM_URL)
.build()
client.newCall(request).execute().use { response ->
val json = response.body!!.string()
return mapper.readValue(json, Response::class.java)
}
}
fun Image.livecam() =
Livecam(
image = imageSource,
description = description,
timestamp = unixTimestamp
)
val file = File("livecams.json")
val log = File("livecams.log")
fun String.fromJson() = mapper.readValue(file, Response::class.java)
fun String.fromFile() = mapper.readValue(file, Storage::class.java)
val newImages = getImages().images.map { it.livecam() }
fun List<Livecam>.prepare() =
takeLast(50).sortedByDescending { it.timestamp.toLong() }
fun log(message: String) {
log.printWriter().use { writer ->
writer.println("$message@${LocalDateTime.now()}")
}
}
if (file.exists()) {
val json = file.readText()
val oldData = json.fromFile().images.toMutableList()
oldData.removeAll(newImages)
oldData.addAll(newImages)
if (oldData != newImages) {
file.delete()
mapper.writerWithDefaultPrettyPrinter().writeValue(file, Storage(oldData.prepare()))
println("Upgrading content with new pictures")
log("New data added (${oldData.size - newImages.size} images)")
} else {
println("No new images")
log("No new images")
}
} else {
println("Creating new file livecams.json")
mapper.writerWithDefaultPrettyPrinter().writeValue(file, Storage(newImages.prepare()))
log("New data added (${newImages.size} images)")
}
| 0 | Kotlin | 0 | 2 | 183dd1f6fd03856f97af651382d16ef5f3d789ef | 3,095 | robactions | MIT License |
app/src/main/java/com/kryptkode/template/app/di/application/AppModule.kt | trizzi | 261,194,267 | true | {"Kotlin": 29901} | package com.kryptkode.template.app.di.application
import android.content.Context
import android.content.SharedPreferences
import com.kryptkode.template.BuildConfig
import com.kryptkode.template.app.data.dispatchers.AppDispatchers
import com.kryptkode.template.app.data.local.prefs.AppPrefs
import com.kryptkode.template.app.data.local.prefs.PreferencesManagerImpl
import com.kryptkode.template.app.data.local.room.AppDb
import com.kryptkode.template.app.data.schedulers.AppSchedulers
import com.kryptkode.template.app.utils.Constants.APP_PREFS
import com.securepreferences.SecurePreferences
import dagger.Module
import dagger.Provides
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
/**
* Created by kryptkode on 2/19/2020.
*/
@Module
class AppModule {
@ApplicationScope
@Provides
fun providePrefs(sharedPreferences: SharedPreferences): AppPrefs {
return PreferencesManagerImpl(sharedPreferences)
}
@Provides
@ApplicationScope
fun provideSharedPrefs(context: Context): SharedPreferences {
return if (BuildConfig.DEBUG) context.getSharedPreferences(
APP_PREFS,
Context.MODE_PRIVATE
) else SecurePreferences(context, APP_PREFS, APP_PREFS)
}
@ApplicationScope
@Provides
fun provideAppDb(context: Context): AppDb {
return AppDb.getInstance(context)
}
@ApplicationScope
@Provides
fun provideAppDispatchers(): AppDispatchers {
return AppDispatchers(Dispatchers.IO, Dispatchers.Default, Dispatchers.Main)
}
@ApplicationScope
@Provides
fun provideAppSchedulers(): AppSchedulers {
return AppSchedulers(
Schedulers.computation(),
Schedulers.io(),
AndroidSchedulers.mainThread()
)
}
}
| 0 | null | 0 | 0 | 358647b896fbd522469e25dd52cad121a8bf0722 | 1,872 | android-template-single-module | Apache License 2.0 |
app/src/main/java/id/teman/app/domain/model/order/OrderEstimationResponseSpec.kt | RifqiFadhell | 681,462,989 | false | null | package id.teman.app.domain.model.order
import android.os.Parcelable
import com.google.android.gms.maps.model.LatLng
import kotlinx.parcelize.Parcelize
@Parcelize
data class OrderEstimationResponseSpec(
val distance: String,
val totalPrice: Double,
val paymentBreakdown: List<OrderPaymentSpec>,
val originAddress: String,
val destinationAddress: String,
val originLatLng: LatLng,
val destinationLatLng: LatLng,
val paymentMethod: String,
val notes: String,
val pin: String? = null,
val receiverName: String? = null,
val receiverPhoneNumber: String? = null,
val packageType: String? = null,
val packageWeight: Int? = null,
val insurance: Int? = null,
) : Parcelable | 0 | Kotlin | 0 | 0 | 4414ca5c417e7ca0cebd341becec901335e77c6a | 726 | Teman-App-Mobile | Apache License 2.0 |
commonMain/src/main/java/com/rayliu/commonmain/data/api/BookSearchApi.kt | YuanLiou | 111,275,765 | false | null | package com.rayliu.commonmain.data.api
import com.rayliu.commonmain.BuildConfig
import io.ktor.client.*
import io.ktor.client.request.*
import com.rayliu.commonmain.data.dto.NetworkCrawerResult
class BookSearchApi(
private val httpClient: HttpClient
) : BookSearchService {
private val url = BuildConfig.HOST_URL + "searches"
private val searchQuery = "?q="
override suspend fun postBooks(keyword: String): NetworkCrawerResult {
return httpClient.post(url + searchQuery + keyword)
}
override suspend fun postBooks(stores: List<String>, keyword: String): NetworkCrawerResult {
val storesString = stores.joinToString("&bookstores[]=", prefix = "&bookstores[]=")
return httpClient.post(url + searchQuery + keyword + storesString)
}
override suspend fun getSearchSnapshot(searchId: String): NetworkCrawerResult {
val snapshotUrl = url + "/"
return httpClient.get(snapshotUrl + searchId)
}
} | 2 | Kotlin | 3 | 32 | 0a310fe534fe04be6bf1316f97cd40ef6e6386ef | 968 | TaiwanEbookSearch | MIT License |
adaptive-lib/adaptive-browser/src/jsMain/kotlin/hu/simplexion/adaptive/html/div.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 963434, "CSS": 47382, "Java": 16814, "HTML": 2759, "JavaScript": 896} | /*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.adaptive.html
import hu.simplexion.adaptive.base.Adaptive
import hu.simplexion.adaptive.base.AdaptiveAdapter
import hu.simplexion.adaptive.base.AdaptiveFragment
import hu.simplexion.adaptive.css.AdaptiveCssStyle
import hu.simplexion.adaptive.dom.AdaptiveDOMNodeFragment
import hu.simplexion.adaptive.base.manualImplementation
import hu.simplexion.adaptive.base.structural.AdaptiveAnonymous
import kotlinx.browser.document
import org.w3c.dom.Node
fun Adaptive.div(vararg styles : AdaptiveCssStyle, builder : Adaptive.() -> Unit) {
manualImplementation(AdaptiveDiv::class, styles, builder)
}
class AdaptiveDiv(
adapter: AdaptiveAdapter<Node>,
parent : AdaptiveFragment<Node>,
index : Int
) : AdaptiveDOMNodeFragment(adapter, parent, index, 2, false) {
override val receiver = document.createElement("div")
private val styles get() = getStyles(0)
private val builder get() = getFragmentFactory(1)
override fun genBuild(parent: AdaptiveFragment<Node>, declarationIndex: Int): AdaptiveFragment<Node> =
AdaptiveAnonymous(adapter, parent, declarationIndex, 0, builder).also { it.create() }
override fun genPatchInternal() {
if (firstTimeInit) {
addClass(styles)
}
}
} | 0 | Kotlin | 0 | 0 | f3550c330c1b66014e922b30c8a8586d6e9d31d8 | 1,401 | adaptive | Apache License 2.0 |
components/virtual-node/cpk-write-service-impl/src/main/kotlin/net/corda/cpk/write/impl/services/db/impl/DBCpkStorage.kt | corda | 346,070,752 | false | null | package net.corda.cpk.write.impl.services.db.impl
import net.corda.cpk.write.impl.services.db.CpkStorage
import net.corda.libs.cpi.datamodel.CpkFile
import net.corda.libs.cpi.datamodel.repository.CpkFileRepositoryImpl
import net.corda.orm.utils.transaction
import net.corda.v5.crypto.SecureHash
import org.slf4j.LoggerFactory
import javax.persistence.EntityManagerFactory
// Consider moving following queries in here to be Named queries at entities site so that we save an extra Integration test
class DBCpkStorage(private val entityManagerFactory: EntityManagerFactory) : CpkStorage {
companion object {
val logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
private val cpkFileRepository = CpkFileRepositoryImpl()
}
override fun getAllCpkFileIds(fileChecksumsToExclude: Collection<SecureHash>): List<SecureHash> {
return entityManagerFactory.createEntityManager().transaction { em ->
cpkFileRepository.findAll(em, fileChecksumsToExclude).map { it.fileChecksum }
}
}
override fun getCpkFileById(fileChecksum: SecureHash): CpkFile {
return entityManagerFactory.createEntityManager().transaction {
cpkFileRepository.findById(it, fileChecksum)
}
}
}
| 127 | Kotlin | 11 | 34 | aedf118b542a571efdf0ac07496e35935866b85f | 1,264 | corda-runtime-os | Apache License 2.0 |
bot/connector-rest/src/main/kotlin/RestConnectorProvider.kt | kchiron | 192,942,545 | true | {"Kotlin": 3816372, "TypeScript": 606849, "HTML": 212373, "CSS": 63959, "JavaScript": 4142, "Shell": 3046} | /*
* Copyright (C) 2017 VSCT
*
* 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 ai.tock.bot.connector.rest
import ai.tock.bot.connector.Connector
import ai.tock.bot.connector.ConnectorConfiguration
import ai.tock.bot.connector.ConnectorProvider
import ai.tock.bot.connector.ConnectorType
import ai.tock.bot.connector.ConnectorTypeConfiguration
import ai.tock.shared.resourceAsString
/**
* The [RestConnector] provider.
*/
internal object RestConnectorProvider : ConnectorProvider {
override val connectorType: ConnectorType get() = ConnectorType.rest
override fun connector(connectorConfiguration: ConnectorConfiguration): Connector {
return RestConnector(
connectorConfiguration.connectorId,
connectorConfiguration.path,
createRequestFilter(connectorConfiguration)
)
}
override fun check(connectorConfiguration: ConnectorConfiguration): List<String> =
super.check(connectorConfiguration) +
listOfNotNull(
if (connectorConfiguration.ownerConnectorType == null)
"rest connector must have an owner connector type"
else null
)
override fun configuration(): ConnectorTypeConfiguration =
ConnectorTypeConfiguration(
ConnectorType.rest,
ConnectorTypeConfiguration.commonSecurityFields(),
resourceAsString("/test.svg")
)
}
internal class RestConnectorProviderService : ConnectorProvider by RestConnectorProvider | 0 | Kotlin | 0 | 0 | 0f06c44cd851dded24177ff8e0c53b6fc6fa4dd0 | 2,042 | tock | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.