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
src/main/kotlin/com.raworkstudio.spring/models/History.kt
AlburIvan
86,746,456
false
{"Gradle": 2, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 12, "Java": 1, "XML": 1, "JAR Manifest": 1, "JSON": 1}
package com.raworkstudio.spring.models import com.raworkstudio.spring.configurations.BuildSystemEnum /** * Created by Ivan on 4/1/2017. */ public data class History( var artifact: String = "", var url: String = "", var preference: Int = 0 ) fun History.getArtifactFQN(build: BuildSystemEnum) { ///artifact/com.jakewharton/butterknife-annotations } fun History.getPackageName(): String { return (this.url.replace("/artifact/", "").replace("/", ".")) } fun History.isPreferedOver(history: History): Boolean { return (this.preference > history.preference) }
1
null
1
1
9bd46e6a6caf751d46e6169243b98b8a9f53b1a1
599
MavenRepoShell
Apache License 2.0
src/main/kotlin/com/example/BookMutationResolver.kt
aldrinm
283,971,771
false
null
package com.example import graphql.kickstart.tools.GraphQLMutationResolver import javax.inject.Singleton import javax.transaction.Transactional @Singleton open class BookMutationResolver(val bookRepository: BookRepository) : GraphQLMutationResolver { @Transactional open fun createBook(title: String): Book { val book = Book(title, 43) val savedBook = bookRepository.save(book) return savedBook } }
0
Kotlin
0
0
ba6bab27ac4e4e38c96c0f725cd234e6cd96f2d4
440
micronaut-kotlin-flyway
MIT License
defitrack-protocols/src/main/java/io/defitrack/protocol/sushiswap/contract/MasterChefV2PoolInfo.kt
decentri-fi
426,174,152
false
{"Kotlin": 1038532, "Java": 1948, "Dockerfile": 909}
package io.defitrack.protocol.sushiswap.contract import java.math.BigInteger class MasterChefV2PoolInfo( val accTokenPerShare: BigInteger, val lastRewardBlock: BigInteger, val allocPoint: BigInteger, )
53
Kotlin
7
9
e65843453e4c44f5c2626870ceb923eb7ab3c4d0
215
defi-hub
MIT License
core/designsystem/src/main/java/br/com/bit/guardian/core/designsystem/extension/BoxExtensions.kt
nascimentodiego
738,913,578
false
{"Kotlin": 224617, "Shell": 10858}
package br.com.bit.guardian.core.designsystem.extension import androidx.compose.foundation.layout.BoxWithConstraintsScope import androidx.compose.ui.unit.dp fun BoxWithConstraintsScope.isWidthCompact() = this.maxWidth < 600.dp fun BoxWithConstraintsScope.isWidthMedium() = this.maxWidth > 400.dp && this.maxWidth < 840.dp fun BoxWithConstraintsScope.isWidthExpanded() = this.maxWidth > 840.dp fun BoxWithConstraintsScope.isHeightCompact() = this.maxHeight < 480.dp fun BoxWithConstraintsScope.isHeightMedium() = this.maxHeight > 480.dp && this.maxHeight < 900.dp fun BoxWithConstraintsScope.isHeightExpanded() = this.maxHeight > 900.dp
8
Kotlin
0
1
d6ac121cc605c449f1ec2262fe85356a1dc60a61
639
guardian
MIT License
Barlom-Foundation-JVM/src/main/kotlin/i/barlom/infrastructure/dxl/scanning/DxlScanner.kt
martin-nordberg
82,682,055
false
null
// // (C) Copyright 2019 <NAME> // Apache 2.0 License // package i.barlom.infrastructure.dxl.scanning import i.barlom.infrastructure.dxl.scanning.EDxlTokenType.* import i.barlom.infrastructure.dxl.scanning.StringTokenizer.Companion.END_OF_INPUT_CHAR //--------------------------------------------------------------------------------------------------------------------- /** * Scanner for L-Zero code. Orchestrates the given [input] tokenizer to produce the individual tokens of a string * of raw L-Zero code. */ internal class DxlScanner( private val input: StringTokenizer ) { /** * Reads the next token from the input. */ fun scan(): DxlToken { var nextChar = input.lookAhead() // Ignore whitespace. while (isWhitespace(nextChar)) { nextChar = input.advanceAndLookAhead() } // Consume the one character after marking the start of a token. input.markAndAdvance() return when (nextChar) { // Single character punctuation tokens '&' -> input.extractTokenFromMark(AMPERSAND) '*' -> input.extractTokenFromMark(ASTERISK) '@' -> input.extractTokenFromMark(AT) '\\' -> input.extractTokenFromMark(BACKSLASH) '^' -> input.extractTokenFromMark(CARET) ':' -> input.extractTokenFromMark(COLON) ',' -> input.extractTokenFromMark(COMMA) '.' -> input.extractTokenFromMark(DOT) '=' -> input.extractTokenFromMark(EQUALS) '!' -> input.extractTokenFromMark(EXCLAMATION) '>' -> input.extractTokenFromMark(GREATER_THAN) '#' -> input.extractTokenFromMark(HASH) '{' -> input.extractTokenFromMark(LEFT_BRACE) '[' -> input.extractTokenFromMark(LEFT_BRACKET) '(' -> input.extractTokenFromMark(LEFT_PARENTHESIS) '?' -> input.extractTokenFromMark(QUESTION_MARK) '}' -> input.extractTokenFromMark(RIGHT_BRACE) ']' -> input.extractTokenFromMark(RIGHT_BRACKET) ')' -> input.extractTokenFromMark(RIGHT_PARENTHESIS) ';' -> input.extractTokenFromMark(SEMICOLON) '~' -> input.extractTokenFromMark(TILDE) // "<-" or "<" '<' -> if (input.lookAhead() == '-') input.advanceAndExtractTokenFromMark(LEFT_ARROW) else input.extractTokenFromMark(LESS_THAN) // "->", "--", "-|", or "-" '-' -> when (input.lookAhead()) { '>' -> input.advanceAndExtractTokenFromMark(RIGHT_ARROW) '-' -> input.advanceAndExtractTokenFromMark(DOUBLE_DASH) '|' -> input.advanceAndExtractTokenFromMark(LEFT_LINE_BRACKET) else -> input.extractTokenFromMark(DASH) } // "|-" or "|" '|' -> when (input.lookAhead()) { '-' -> input.advanceAndExtractTokenFromMark(RIGHT_LINE_BRACKET) else -> input.extractTokenFromMark(VERTICAL_LINE) } // documentation or "/" '/' -> when (input.lookAhead()) { '*' -> scanDocumentation() else -> input.extractTokenFromMark(SLASH) } // String literal '"' -> scanStringLiteral() // Character literal '\'' -> scanCharacterLiteral() // Identifier enclosed in back ticks '`' -> scanQuotedIdentifier() // UUID literal '%' -> scanUuid() // End of input sentinel END_OF_INPUT_CHAR -> input.extractTokenFromMark(END_OF_INPUT) // Miscellaneous else -> when { // Scan an identifier. isIdentifierStart(nextChar) -> scanIdentifier() // Scan a numeric literal (integer or floating point). isDigit(nextChar) -> scanNumericLiteral() // Error - nothing else it could be. else -> input.extractTokenFromMark(INVALID_CHARACTER) } } } //// /** * @return true if the given [character] can be the first character of an identifier. */ private fun isDigit(character: Char) = "0123456789".contains(character) /** * @return true if the given [character] can be part of an identifier (after its first character). */ private fun isIdentifierPart(character: Char) = isIdentifierStart(character) || isDigit(character) /** * @return true if the given [character] can be the first character of an identifier. */ private fun isIdentifierStart(character: Char) = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_".contains(character) /** * @return true if the given [character] is whitespace. */ private fun isWhitespace(character: Char) = " \t\r\n".contains(character) /** * Scans a character literal token after its opening "'" character has been marked and consumed in the tokenizer. */ private fun scanCharacterLiteral(): DxlToken { var nextChar = input.lookAhead() while (nextChar != '\'') { if (nextChar == '\n' || nextChar == END_OF_INPUT_CHAR) { return input.extractTokenFromMark(UNTERMINATED_CHARACTER_LITERAL) } nextChar = input.advanceAndLookAhead() } return input.advanceAndExtractTokenFromMark(CHARACTER_LITERAL) } /** * Scans a block of documentation after its opening '/' character has been marked and consumed in * the tokenizer and the '*' character has been recognized. */ private fun scanDocumentation(): DxlToken { // "*" input.advance() var nextChar = input.lookAhead() while (true) { if (nextChar == END_OF_INPUT_CHAR) { return input.extractTokenFromMark(UNTERMINATED_DOCUMENTATION) } input.advance() if (nextChar == '*' && input.lookAhead() == '/') { return input.advanceAndExtractTokenFromMark(DOCUMENTATION) } nextChar = input.lookAhead() } } /** * Scans a floating point literal after marking the first digit and consuming up until (but not including) the * first character seen that distinguishes it from an integer literal. */ private fun scanFloatingPointLiteral(): DxlToken { var nextChar = input.lookAhead() if (nextChar == '.') { nextChar = input.advanceAndLookAhead() while (isDigit(nextChar) || '_' == nextChar) { nextChar = input.advanceAndLookAhead() } } if (nextChar == 'e' || nextChar == 'E') { nextChar = input.advanceAndLookAhead() if (nextChar == '-' || nextChar == '+') { nextChar = input.advanceAndLookAhead() } while (isDigit(nextChar) || '_' == nextChar) { nextChar = input.advanceAndLookAhead() } } if (nextChar == 'd' || nextChar == 'D' || nextChar == 'f' || nextChar == 'F') { input.advance() } return input.extractTokenFromMark(FLOATING_POINT_LITERAL) } /** * Scans an identifier after its first character has been marked and consumed. */ private fun scanIdentifier(): DxlToken { while (isIdentifierPart(input.lookAhead())) { input.advance() } when (input.extractedTokenText()) { "alias" -> return input.extractTokenFromMark(ALIAS) "false" -> return input.extractTokenFromMark(BOOLEAN_LITERAL) "true" -> return input.extractTokenFromMark(BOOLEAN_LITERAL) } return input.extractTokenFromMark(IDENTIFIER) } /** * Scans a numerical literal (integer or floating point) after its first numeric digit has been marked and consumed. */ private fun scanNumericLiteral(): DxlToken { var nextChar = input.lookAhead() while (isDigit(nextChar) || '_' == nextChar) { nextChar = input.advanceAndLookAhead() } if (FLOATING_POINT_STARTERS.contains(nextChar)) { return scanFloatingPointLiteral() } // TODO: hexadecimal // TODO: binary if (nextChar == 'l' || nextChar == 'L') { input.advance() } return input.extractTokenFromMark(INTEGER_LITERAL) } /** * Scans a backtick-quoted identifier after the open "`" character has been marked and consumed. */ private fun scanQuotedIdentifier(): DxlToken { var nextChar = input.lookAhead() var invalidChar = false; while (nextChar != '`') { if (nextChar == '\n' || nextChar == END_OF_INPUT_CHAR) { return input.extractTokenFromMark(UNTERMINATED_QUOTED_IDENTIFIER) } if (".:[]{}<>\\/".contains(nextChar)) { invalidChar = true } nextChar = input.advanceAndLookAhead() } if (invalidChar) { return input.advanceAndExtractTokenFromMark(INVALID_QUOTED_IDENTIFIER) } return input.advanceAndExtractTokenFromMark(IDENTIFIER) } /** * Scans a string literal after the opening double quote character has been marked and consumed. */ private fun scanStringLiteral(): DxlToken { var nextChar = input.lookAhead() while (nextChar != '"') { if (nextChar == '\n' || nextChar == END_OF_INPUT_CHAR) { return input.extractTokenFromMark(UNTERMINATED_STRING_LITERAL) } nextChar = input.advanceAndLookAhead() } return input.advanceAndExtractTokenFromMark(STRING_LITERAL) } /** * Scans a UUID after the initial '%' character has been consumed. */ private fun scanUuid(): DxlToken { val uuidChars = "abcdefABCDEF1234567890" fun readUuidChars(nChars: Int): Boolean { for (i in 1..nChars) { val nextChar = input.lookAhead() if (!uuidChars.contains(nextChar)) { return false } input.advance() } return true } fun readChar(ch: Char): Boolean { val nextChar = input.lookAhead() if (nextChar == ch) { input.advance() return true } return false } fun readDash() = readChar('-') fun readPercent() = readChar('%') if (!readUuidChars(1)) { return input.extractTokenFromMark(PERCENT) } val scanned = readUuidChars(7) && readDash() && readUuidChars(4) && readDash() && readUuidChars(4) && readDash() && readUuidChars(4) && readDash() && readUuidChars(12) && readPercent() if (scanned) { return input.extractTokenFromMark(UUID_LITERAL) } while (readUuidChars(1) || readDash()) { // keep consuming } readPercent() return input.extractTokenFromMark(INVALID_UUID_LITERAL) } //// companion object { /** Characters that distinguish a floating point literal from an integer literal. */ private val FLOATING_POINT_STARTERS = setOf('.', 'd', 'D', 'e', 'E', 'f', 'F') } } //---------------------------------------------------------------------------------------------------------------------
0
Kotlin
0
0
337b46f01f6eec6dfb3b86824c26f1c103e9d9a2
11,939
ZZ-Barlom
Apache License 2.0
app/src/main/java/com/developer/allef/boilerplateapp/extensions/InlineDebug.kt
allefsousa
255,496,215
false
null
package com.developer.allef.boilerplateapp.extensions import android.os.Handler import br.com.redcode.base.utils.Constants inline fun delay(crossinline code: () -> Unit) = delay(Constants.ONE_SECOND_IN_MILLISECONDS, code) inline fun delay(time: Long, crossinline code: () -> Unit) { try { Handler().postDelayed({ code() }, time) } catch (e: Exception) { e.printStackTrace() } }
0
Kotlin
0
0
2e0eadd25d26450516f4ad7cbc9e911594906ae7
408
Material-Boilerplate
MIT License
core/src/main/kotlin/org/datadozer/search/ErrorHandler.kt
DataDozer
71,779,605
false
{"Gradle": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 36, "INI": 2, "Java Properties": 1, "Protocol Buffer": 2, "ANTLR": 4, "Java": 1}
package org.datadozer.search import org.antlr.v4.runtime.* import org.antlr.v4.runtime.misc.ParseCancellationException import org.datadozer.addKeyValue import org.datadozer.models.OperationMessage import org.datadozer.models.OperationStatus import org.datadozer.toException /* * Licensed to DataDozer under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. DataDozer licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ class OperationMessageErrorStrategy : DefaultErrorStrategy() { /** Instead of recovering from exception `e`, re-throw it wrapped * in a [ParseCancellationException] so it is not caught by the * rule function catches. Use [Exception.getCause] to get the * original [RecognitionException]. */ override fun recover(recognizer: Parser, e: RecognitionException?) { var context: ParserRuleContext? = recognizer.context while (context != null) { context.exception = e context = context.getParent() } throw ParseCancellationException(e) } /** Make sure we don't attempt to recover from problems in subrules. */ override fun sync(recognizer: Parser) {} /** * Returns a new operation message for the parsing errors */ private fun getOperationMessage(errorType: String, line: Int, charPositionInLine: Int, offendingToken: String, expectedTokens: String, underlineError: String, helpText: String): OperationMessage { val error = """Query parsing error: $errorType at $line:$charPositionInLine Expecting token:$expectedTokens Found token:$offendingToken $underlineError $helpText """ return OperationMessage.newBuilder() .setMessage(error) .addKeyValue("line_no", line) .addKeyValue("character_position", charPositionInLine) .addKeyValue("offending_token", offendingToken) .addKeyValue("expected_token", expectedTokens) .addKeyValue("underline_error", underlineError) .addKeyValue("help_text", helpText) .addKeyValue("error_type", errorType) .setStatus(OperationStatus.FAILURE) .build() } private fun reportErrorUsingOperationMessage(recognizer: Parser, errorType: String) { val offendingToken = getTokenErrorDisplay(recognizer.currentToken) val expectedTokens = getExpectedTokens(recognizer).toString(recognizer.vocabulary) val line = recognizer.currentToken.line val charPositionInLine = recognizer.currentToken.charPositionInLine val underlineError = underlineError(recognizer, recognizer.currentToken, line, charPositionInLine) val helpText = getHelpTextForToken(expectedTokens) throw getOperationMessage(errorType, line, charPositionInLine, offendingToken, expectedTokens, underlineError, helpText) .toException() } /** * This is called by [.reportError] when the exception is a * [NoViableAltException]. * * @see .reportError * * * @param recognizer the parser instance * @param e the recognition exception */ override fun reportNoViableAlternative(recognizer: Parser, e: NoViableAltException) { reportErrorUsingOperationMessage(recognizer, "No viable alternative") } /** * This is called by [.reportError] when the exception is an * [InputMismatchException]. * * @see .reportError * * * @param recognizer the parser instance * @param e the recognition exception */ override fun reportInputMismatch(recognizer: Parser, e: InputMismatchException) { reportErrorUsingOperationMessage(recognizer, "Input mismatch") } /** * This method is called to report a syntax error which requires the * insertion of a missing token into the input stream. At the time this * method is called, the missing token has not yet been inserted. When this * method returns, {@code recognizer} is in error recovery mode. * * <p>This method is called when {@link #singleTokenInsertion} identifies * single-token insertion as a viable recovery strategy for a mismatched * input error.</p> * * <p>The default implementation simply returns if the handler is already in * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to * enter error recovery mode, followed by calling * {@link Parser#notifyErrorListeners}.</p> * * @param recognizer the parser instance */ override fun reportMissingToken(recognizer: Parser) { reportErrorUsingOperationMessage(recognizer, "Missing token") } /** * This method is called to report a syntax error which requires the removal * of a token from the input stream. At the time this method is called, the * erroneous symbol is current `LT(1)` symbol and has not yet been * removed from the input stream. When this method returns, * `recognizer` is in error recovery mode. * * * This method is called when [.singleTokenDeletion] identifies * single-token deletion as a viable recovery strategy for a mismatched * input error. * * * The default implementation simply returns if the handler is already in * error recovery mode. Otherwise, it calls [.beginErrorCondition] to * enter error recovery mode, followed by calling * [Parser.notifyErrorListeners]. * * @param recognizer the parser instance */ override fun reportUnwantedToken(recognizer: Parser) { reportErrorUsingOperationMessage(recognizer, "Unwanted token") } /** * Underline the point at which the error occurs in the input string. * This is useful for the end user as it makes it easy to find the errors. */ private fun underlineError(recognizer: Recognizer<*, *>?, offendingToken: Token, line: Int, charPositionInLine: Int): String { val tokens = recognizer?.inputStream as CommonTokenStream val input = tokens.tokenSource.inputStream.toString() val lines = input.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val errorLine = lines[line - 1] val sb = StringBuilder() val widthOfLineNumber = when { line < 10 -> 1 line < 100 -> 2 else -> 3 } sb.appendln("$line| $errorLine") for (i in 0 until charPositionInLine + widthOfLineNumber) { sb.append(" ") } val start = offendingToken.startIndex val stop = offendingToken.stopIndex for (i in 0 until widthOfLineNumber + 4) { sb.append(" ") } if (start >= 0 && stop >= 0) { if (start > stop) { for (i in stop until start) { sb.append("^") } } else { for (i in start..stop) { sb.append("^") } } } return sb.toString() } }
1
null
1
1
ef48d3a8fe0b8a2f7fdb0b4e4eeffa70fd6c2fc4
8,116
DataDozer
Apache License 2.0
analysis/analysis-api/testData/symbols/singleSymbolByPsi/destructuring/entryInScriptDestructuringDeclaration.kts
JetBrains
3,432,266
false
null
// LOOK_UP_FOR_ELEMENT_OF_TYPE: KtDestructuringDeclarationEntry // DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE data class X(val a: Int, val b: Int) val (<expr>a</expr>, b) = X(1, 2)
184
null
5691
48,625
bb25d2f8aa74406ff0af254b2388fd601525386a
176
kotlin
Apache License 2.0
kmqtt-broker/src/commonMain/kotlin/socket/udp/UDPSocket.kt
davidepianca98
235,132,697
false
{"Kotlin": 524141, "Dockerfile": 3673}
package socket.udp expect class UDPSocket { fun send(data: UByteArray, address: String, port: Int) fun read(): UDPReadData? }
2
Kotlin
19
92
eff347bc03c4093a974731d0974e5592bde5bb49
137
KMQTT
MIT License
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/kopsideclaration/KoPsiDeclarationForLocationAndTextTest.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.core.declaration.kopsideclaration import com.lemonappdev.konsist.TestSnippetProvider import org.amshove.kluent.assertSoftly import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test class KoPsiDeclarationForLocationAndTextTest { @Test fun `location-with-text`() { // given val projectPath = getSnippetFile("location-with-text") .declarations() .first() .projectFilePath val sut = getSnippetFile("location-with-text") .functions() .first() // then val declaration = "Declaration:\nfun sampleFunction() {\n}" assertSoftly(sut.locationWithText) { startsWith("Location: /") shouldBeEqualTo true contains(projectPath) shouldBeEqualTo true endsWith(declaration) shouldBeEqualTo true } } @Test fun `location-with-single-digit`() { // given val sut = getSnippetFile("location-with-single-digit") .functions() .first() // then sut.location shouldBeEqualTo "${sut.filePath}:3:1" } @Test fun `location-with-double-digit`() { // given val sut = getSnippetFile("location-with-double-digit") .functions(includeNested = true) .first() // then sut.location shouldBeEqualTo "${sut.filePath}:10:25" } @Test fun `text`() { // given val sut = getSnippetFile("text") .namedDeclarations() .first() // then sut .text .shouldBeEqualTo( """ fun sampleFunction() { "SampleText" } """.trimIndent(), ) } private fun getSnippetFile(fileName: String) = TestSnippetProvider.getSnippetKoScope("core/declaration/kopsideclaration/snippet/forlocationandtext/", fileName) }
9
Kotlin
0
5
2c029ca448d24acad1cc0473e69b78130be86193
1,987
konsist
Apache License 2.0
webview/src/desktopMain/kotlin/com/multiplatform/webview/web/CefRequestExt.kt
KevinnZou
685,404,698
false
{"Kotlin": 143529, "Shell": 807}
package com.multiplatform.webview.web import com.multiplatform.webview.setting.WebSettings import dev.datlag.kcef.KCEFResourceRequestHandler import org.cef.browser.CefBrowser import org.cef.browser.CefFrame import org.cef.browser.CefRequestContext import org.cef.network.CefRequest internal fun createModifiedRequestContext(settings: WebSettings): CefRequestContext { return CefRequestContext.createContext { browser, frame, request, isNavigation, isDownload, requestInitiator, disableDefaultHandling -> object : KCEFResourceRequestHandler( getGlobalDefaultHandler(browser, frame, request, isNavigation, isDownload, requestInitiator, disableDefaultHandling), ) { override fun onBeforeResourceLoad( browser: CefBrowser?, frame: CefFrame?, request: CefRequest?, ): Boolean { if (request != null) { settings.customUserAgentString?.let(request::setUserAgentString) } return super.onBeforeResourceLoad(browser, frame, request) } } } } internal fun CefRequest.setUserAgentString(userAgent: String) { setHeaderByName("User-Agent", userAgent, true) }
51
Kotlin
63
495
ab2ea169c57fd5fcdf386249cbc2ef14f7f3f197
1,246
compose-webview-multiplatform
Apache License 2.0
src/main/kotlin/no/nav/helse/sporenstreks/kvittering/KvitteringSender.kt
navikt
249,433,776
false
null
package no.nav.helse.sporenstreks.kvittering interface KvitteringSender { fun send(kvittering: Kvittering) }
4
Kotlin
0
2
d6ff76bfa9e17c426087a220209687bc37683346
114
sporenstreks
MIT License
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjeningstartinnlesning/start/StartInnlesningService.kt
navikt
585,136,142
false
null
package no.nav.pensjon.opptjening.omsorgsopptjeningstartinnlesning.start import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Service class StartInnlesningService(val repository: StartHistorikkRepository, val omsorgsArbeidClient: OmsorgsArbeidClient) { companion object { private val logger = LoggerFactory.getLogger(StartInnlesningService::class.java) } fun startInnlesning(ar: String) { val localDateTime = LocalDateTime.now() val timestamp = localDateTime.format(DateTimeFormatter.ISO_DATE_TIME) logger.info("Starter innlesing for år: $ar, timestamp: $timestamp") val startHistorikk = StartHistorikk() startHistorikk.kjoringsAr = ar startHistorikk.kjoringTimesamp = localDateTime omsorgsArbeidClient.startInnlesning(ar, timestamp) repository.save(startHistorikk) } fun startInnlesningHistorikk(): List<StartHistorikk> = repository.findAll() }
0
Kotlin
0
0
6c27dbd52f4ac7d1a9a475d5624cad8ced6eda2e
1,041
omsorgsopptjening-start-innlesning
MIT License
NewsApp/app/src/main/java/com/mustk/newsapp/ui/viewmodel/SearchViewModel.kt
mustafakamber
804,916,194
false
{"Kotlin": 164466}
package com.mustk.newsapp.ui.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.mustk.newsapp.data.datasource.NewsDataSource import com.mustk.newsapp.data.model.News import com.mustk.newsapp.shared.Constant.SEARCH_THRESHOLD_LENGTH import com.mustk.newsapp.shared.Constant.TIME_OUT_MILLIS import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SearchViewModel @Inject constructor(private val repository: NewsDataSource) : BaseViewModel() { private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> get() = _loading private val _initMessage = MutableLiveData<Boolean>() val initMessage: LiveData<Boolean> get() = _initMessage private val _notFoundMessage = MutableLiveData<Boolean>() val notFoundMessage: LiveData<Boolean> get() = _notFoundMessage private val _recyclerView = MutableLiveData<Boolean>() val recyclerView: LiveData<Boolean> get() = _recyclerView private val _newsList = MutableLiveData<List<News>>() val newsList: LiveData<List<News>> get() = _newsList private val _searchText = MutableStateFlow("") private val searchText = _searchText.asStateFlow() init { initState() observeSearchTextChanges() } private fun setInitMessageVisibility(boolean: Boolean) { _initMessage.value = boolean } private fun setNotFoundMessageVisibility(boolean: Boolean) { _notFoundMessage.value = boolean } private fun setRecyclerViewVisibility(boolean: Boolean) { _recyclerView.value = boolean } private fun setSearchLoadingBarVisibility(boolean: Boolean) { _loading.value = boolean } private fun setNewsList(news: List<News>) { _newsList.value = news } fun onSearchTextChange(text: String) { checkEmptyQuery(text) } private fun initState() { setRecyclerViewVisibility(false) setNotFoundMessageVisibility(false) setSearchLoadingBarVisibility(false) setInitMessageVisibility(true) } private fun loadingState() { setRecyclerViewVisibility(false) setNotFoundMessageVisibility(false) setInitMessageVisibility(false) setSearchLoadingBarVisibility(true) } private fun resultFoundState() { setNotFoundMessageVisibility(false) setInitMessageVisibility(false) setSearchLoadingBarVisibility(false) setRecyclerViewVisibility(true) } private fun resultNotFoundState() { setInitMessageVisibility(false) setSearchLoadingBarVisibility(false) setRecyclerViewVisibility(false) setNotFoundMessageVisibility(true) } private fun checkEmptyQuery(text: String) { if (text.trim().isEmpty()) { initState() } else { _searchText.value = text.lowercase() } } @OptIn(FlowPreview::class) private fun observeSearchTextChanges() { viewModelScope.launch { searchText .debounce(TIME_OUT_MILLIS) .distinctUntilChanged() .filter { it.length > SEARCH_THRESHOLD_LENGTH } .collectLatest { fetchSearchNewsListFromAPI(it) } } } private fun fetchSearchNewsListFromAPI(newsKey: String) { loadingState() safeRequest( response = { repository.searchNews(newsKey) }, successStatusData = { searchData -> if (searchData.data.isEmpty()) { resultNotFoundState() } else { resultFoundState() setNewsList(searchData.data) } }) } }
0
Kotlin
0
0
ae635d1614706b1f0f35ca0554f57a4f7d0e98b6
4,253
NewsApp
Apache License 2.0
ui/script/src/main/kotlin/me/gegenbauer/catspy/script/executor/AdbShellExecutor.kt
Gegenbauer
609,809,576
false
{"Kotlin": 652879}
package me.gegenbauer.catspy.script.executor import com.malinskiy.adam.AndroidDebugBridgeClientFactory import com.malinskiy.adam.request.device.Device import com.malinskiy.adam.request.shell.v2.ShellCommandRequest import com.malinskiy.adam.request.shell.v2.ShellCommandResult import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import me.gegenbauer.catspy.concurrency.GIO import me.gegenbauer.catspy.script.model.Script class AdbShellExecutor( override val script: Script, override val dispatcher: CoroutineDispatcher = Dispatchers.GIO ) : ScriptExecutor { private val adbClient = AndroidDebugBridgeClientFactory().run { build() } override fun execute(device: Device): Flow<ShellCommandResult> = flow { val response = adbClient.execute( request = ShellCommandRequest(script.sourceCode), serial = device.serial ) emit(response) } override fun cancel() { } }
0
Kotlin
1
7
70d905761d3cb0cb2e5ee9b80ceec72fca46ee52
1,054
CatSpy
Apache License 2.0
data/src/main/java/team/msg/data/dto/user/request/getUserInfo/GetUserInfoRequest.kt
GSM-MSG
637,641,666
false
null
package team.msg.data.dto.user.request.getUserInfo import team.msg.domain.model.user.request.GetUserInfo.GetUserInfoRequestModel data class GetUserInfoRequest( val keyword: String ) fun GetUserInfoRequestModel.asGetUserInfoRequest() = GetUserInfoRequest( keyword = keyword )
0
Kotlin
0
10
782ebaa545a6aa2f21b5cb91efbd4371c4875d65
286
Hi-v2-Android
MIT License
main/src/main/java/com/quxianggif/user/adapter/UserFeedAdapter.kt
guolindev
167,902,491
false
null
/* * Copyright (C) guolin, Suzhou Quxiang Inc. Open source codes for study only. * Do not use for commercial purpose. * * 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.quxianggif.user.adapter import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.quxianggif.R import com.quxianggif.common.adapter.SimpleListFeedAdapter import com.quxianggif.core.extension.dp2px import com.quxianggif.core.model.UserFeed import com.quxianggif.user.ui.UserHomePageActivity /** * 用户个人主页的适配器。 * * @author guolin * @since 17/7/23 */ class UserFeedAdapter(override var activity: UserHomePageActivity, feedList: MutableList<UserFeed>, maxImageWidth: Int, layoutManager: RecyclerView.LayoutManager) : SimpleListFeedAdapter<UserFeed, UserHomePageActivity>(activity, feedList, maxImageWidth, layoutManager) { override var isLoadFailed: Boolean = false get() = activity.isLoadFailed override var isNoMoreData: Boolean = false get() = activity.isNoMoreData override fun bindFeedHolder(holder: SimpleListFeedAdapter.FeedViewHolder, position: Int) { setupFirstItemMarginTop(holder.cardView, position) super.bindFeedHolder(holder, position) } override fun bindRefeedHolder(holder: SimpleListFeedAdapter.RefeedViewHolder, position: Int) { setupFirstItemMarginTop(holder.cardView, position) super.bindRefeedHolder(holder, position) } override fun createFeedHolder(parent: ViewGroup): SimpleListFeedAdapter.FeedViewHolder { val view = LayoutInflater.from(activity).inflate(R.layout.user_feed_item, parent, false) val holder = SimpleListFeedAdapter.FeedViewHolder(view) initBaseFeedHolder(holder) return holder } override fun createRefeedHolder(parent: ViewGroup): SimpleListFeedAdapter.RefeedViewHolder { val view = LayoutInflater.from(activity).inflate(R.layout.user_refeed_item, parent, false) val holder = SimpleListFeedAdapter.RefeedViewHolder(view) initBaseFeedHolder(holder) return holder } override fun onLoad() { activity.onLoad() } private fun setupFirstItemMarginTop(cardView: CardView, position: Int) { val params = if (position == 0) { val layoutParams = cardView.layoutParams as RecyclerView.LayoutParams layoutParams.topMargin = dp2px(35f) layoutParams } else { val layoutParams = cardView.layoutParams as RecyclerView.LayoutParams layoutParams.topMargin = dp2px(10f) layoutParams } cardView.layoutParams = params } companion object { private const val TAG = "UserFeedAdapter" } }
30
null
692
3,448
26227595483a8f2508f23d947b3fe99721346e0f
3,332
giffun
Apache License 2.0
plugin/src/test/fixtures/sources/ktlint/no-error/ValidClass.kt
GradleUp
256,683,183
false
null
data class ValidClass(val prop1: String, val prop2: Int)
1
Groovy
4
61
ef49300f72dd9f731bc6469955be3fc08f401560
57
static-analysis-plugin
Apache License 2.0
compiler/ir/serialization.common/src/org/jetbrains/kotlin/backend/common/serialization/signature/IdSignatureSerializer.kt
android
263,405,600
true
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.common.serialization.signature import org.jetbrains.kotlin.backend.common.serialization.DeclarationTable import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.util.IdSignature import org.jetbrains.kotlin.ir.util.KotlinMangler import org.jetbrains.kotlin.ir.util.render import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptVoid import org.jetbrains.kotlin.name.FqName open class IdSignatureSerializer(val mangler: KotlinMangler.IrMangler) : IdSignatureComputer { override fun computeSignature(declaration: IrDeclaration): IdSignature? { return if (mangler.run { declaration.isExported() }) { composePublicIdSignature(declaration) } else null } private fun composeSignatureForDeclaration(declaration: IrDeclaration): IdSignature { return if (mangler.run { declaration.isExported() }) { composePublicIdSignature(declaration) } else composeFileLocalIdSignature(declaration) } private var localIndex: Long = 0 private var scopeIndex: Int = 0 lateinit var table: DeclarationTable fun reset() { localIndex = 0 scopeIndex = 0 } private inner class PublicIdSigBuilder : IdSignatureBuilder<IrDeclaration>(), IrElementVisitorVoid { override fun accept(d: IrDeclaration) { d.acceptVoid(this) } private fun collectFqNames(declaration: IrDeclarationWithName) { declaration.parent.acceptVoid(this) classFqnSegments.add(declaration.name.asString()) } override fun visitElement(element: IrElement) = error("Unexpected element ${element.render()}") override fun visitPackageFragment(declaration: IrPackageFragment) { packageFqn = declaration.fqName } override fun visitClass(declaration: IrClass) { collectFqNames(declaration) setExpected(declaration.isExpect) } override fun visitSimpleFunction(declaration: IrSimpleFunction) { val property = declaration.correspondingPropertySymbol if (property != null) { hashIdAcc = mangler.run { declaration.signatureMangle } property.owner.acceptVoid(this) classFqnSegments.add(declaration.name.asString()) } else { hashId = mangler.run { declaration.signatureMangle } collectFqNames(declaration) } setExpected(declaration.isExpect) } override fun visitConstructor(declaration: IrConstructor) { hashId = mangler.run { declaration.signatureMangle } collectFqNames(declaration) setExpected(declaration.isExpect) } override fun visitProperty(declaration: IrProperty) { hashId = mangler.run { declaration.signatureMangle } collectFqNames(declaration) setExpected(declaration.isExpect) } override fun visitTypeAlias(declaration: IrTypeAlias) { collectFqNames(declaration) } override fun visitEnumEntry(declaration: IrEnumEntry) { collectFqNames(declaration) } } private val publicSignatureBuilder = PublicIdSigBuilder() private fun composeContainerIdSignature(container: IrDeclarationParent): IdSignature { if (container is IrPackageFragment) return IdSignature.PublicSignature(container.fqName, FqName.ROOT, null, 0) if (container is IrDeclaration) return table.signatureByDeclaration(container) error("Unexpected container ${container.render()}") } fun composePublicIdSignature(declaration: IrDeclaration): IdSignature { assert(mangler.run { declaration.isExported() }) { "${declaration.render()} expected to be exported" } return publicSignatureBuilder.buildSignature(declaration) } fun composeFileLocalIdSignature(declaration: IrDeclaration): IdSignature { assert(!mangler.run { declaration.isExported() }) return table.privateDeclarationSignature(declaration) { when (declaration) { is IrValueDeclaration -> IdSignature.ScopeLocalDeclaration(scopeIndex++, declaration.name.asString()) is IrField -> { val p = declaration.correspondingPropertySymbol?.let { composeSignatureForDeclaration(it.owner) } ?: composeContainerIdSignature(declaration.parent) IdSignature.FileLocalSignature(p, ++localIndex) } is IrSimpleFunction -> { val p = declaration.correspondingPropertySymbol?.let { composeSignatureForDeclaration(it.owner) } ?: composeContainerIdSignature(declaration.parent) IdSignature.FileLocalSignature(p, ++localIndex) } else -> IdSignature.FileLocalSignature(composeContainerIdSignature(declaration.parent), ++localIndex) } } } }
0
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
5,378
kotlin
Apache License 2.0
modules/common/src/main/java/com/sygic/maps/module/common/delegate/ApplicationComponentDelegate.kt
Sygic
156,541,755
false
{"Kotlin": 1008397, "Java": 117204}
/* * Copyright (c) 2019 Sygic a.s. All rights reserved. * * This project is licensed under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.sygic.maps.module.common.delegate import androidx.fragment.app.Fragment import com.sygic.maps.module.common.di.ApplicationModulesComponent import com.sygic.maps.module.common.di.DaggerApplicationModulesComponent import com.sygic.maps.module.common.di.module.AppModule private var applicationModulesComponent: ApplicationModulesComponent? = null object ApplicationComponentDelegate { fun getComponent(fragment: Fragment): ApplicationModulesComponent = applicationModulesComponent?.let { it } ?: DaggerApplicationModulesComponent .builder() .appModule(AppModule(fragment)) .build() .also { applicationModulesComponent = it } }
4
Kotlin
3
22
ca385eca585f67014926c4aa539c0088e11ceed2
1,891
sygic-maps-kit-android
MIT License
chat/src/main/java/cn/wildfire/imshat/discovery/download/WebActivity.kt
SKYNET-DAO
470,424,807
false
null
package cn.wildfire.imshat.discovery.download import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Handler import android.text.TextUtils import android.view.View import android.webkit.* import android.widget.LinearLayout import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import cn.wildfire.imshat.discovery.util.AndroidInterface import com.just.agentweb.AgentWeb import com.just.agentweb.NestedScrollAgentWebView import com.orhanobut.logger.Logger import com.vondear.rxtool.RxFileTool import org.bitcoinj.wallet.Wallet import java.io.File import cn.wildfire.imshat.kit.WfcBaseActivity import cn.wildfire.imshat.kit.utils.Path.FileUtils import cn.wildfire.imshat.wallet.JsonUtil import cn.wildfire.imshat.wallet.viewmodel.WalletViewModel import cn.wildfirechat.imshat.R import com.afollestad.materialdialogs.MaterialDialog import com.android.base.LanguageUtil import com.just.agentweb.DefaultWebClient import com.just.agentweb.WebViewClient import io.ipfs.api.IPFS import kotlinx.android.synthetic.main.activity_net_test.* import java.net.URI class WebActivity : WfcBaseActivity() { private var mAgentWeb: AgentWeb? = null private var webLayout: LinearLayout? = null private var ipfsModel: IPFSModel? = null private var indexhtmlpath: String? = null private var walletViewModel: WalletViewModel? = null private var wallet: Wallet? = null private var sharedPreferences: SharedPreferences? = null override fun contentLayout(): Int { return R.layout.activity_webview1 } override fun afterViews() { ipfsModel = intent.getSerializableExtra("model") as IPFSModel sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE) walletViewModel = ViewModelProviders.of(this).get(WalletViewModel::class.java) webLayout = findViewById(R.id.lin_web) val webView = NestedScrollAgentWebView(this) // setting(webView) webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null) mAgentWeb = AgentWeb.with(this) .setAgentWebParent(webLayout!!, LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW) .setWebView(webView) .setWebViewClient(object : WebViewClient(){}) .createAgentWeb() .go("") walletViewModel?.walletLoadLiveData?.observe(this, Observer { this.wallet=it initData() }) walletViewModel?.walletLoadLiveData?.loadWallet() } private fun initData() { val files = RxFileTool.listFilesInDir(Constants.PLUGIN_DIR + "/" + ipfsModel!!.sign) for (item in files) { Logger.e("-------file----->" + item.name) if (item.name == "index.html") indexhtmlpath = item.path } Logger.e("-------indexhtmlpath--->$indexhtmlpath") loadIndexPage(indexhtmlpath) } private fun loadIndexPage(path: String?) { mAgentWeb?.urlLoader?.loadUrl( File(path).toURI().toString()) // mAgentWeb?.jsInterfaceHolder?.addJavaObject("Android",this) mAgentWeb?.jsInterfaceHolder?.addJavaObject("Android", AndroidInterface(mAgentWeb!!, this,this.wallet!!)) // } fun setting(webView: WebView?) { webView?.settings?.apply { javaScriptEnabled = true useWideViewPort = true setSupportZoom(true) builtInZoomControls = true displayZoomControls = false cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK allowFileAccess = true loadsImagesAutomatically = true defaultTextEncodingName = "utf-8" domStorageEnabled = true databaseEnabled = true setAppCacheEnabled(true) setGeolocationEnabled(true) saveFormData = true setNeedInitialFocus(true) loadWithOverviewMode = true layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL setSupportMultipleWindows(false) javaScriptCanOpenWindowsAutomatically = false allowContentAccess = true allowFileAccess = true allowFileAccessFromFileURLs = true allowUniversalAccessFromFileURLs = true loadsImagesAutomatically = true // blockNetworkImage = App.getSp(SettingConstants.IMG, false) blockNetworkLoads = false setSupportZoom(true) builtInZoomControls = false displayZoomControls = true defaultTextEncodingName = "UTF-8" defaultFontSize = 16 defaultFixedFontSize = 16 minimumFontSize = 8 minimumLogicalFontSize = 8 textZoom = 100 standardFontFamily = "sans-serif" serifFontFamily = "serif" sansSerifFontFamily = "sans-serif" fixedFontFamily = "monospace" cursiveFontFamily = "cursive" fantasyFontFamily = "fantasy" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mediaPlaybackRequiresUserGesture = true } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { offscreenPreRaster = false } } } companion object { fun loadUrl(context: Context, model: IPFSModel) { val intent = Intent(context, WebActivity::class.java) intent.putExtra("model", model) context.startActivity(intent) } } override fun onPause() { mAgentWeb?.webLifeCycle?.onPause() super.onPause() } override fun onResume() { mAgentWeb?.webLifeCycle?.onResume() super.onResume() } override fun onDestroy() { mAgentWeb?.webLifeCycle?.onDestroy() super.onDestroy() } }
1
null
1
1
905c1be47b379e87d1f5e1625841b7422c27a682
6,478
SKYCHAT
MIT License
app/src/main/java/com/danielceinos/todolist/features/recipeslist/RecipesListFragment.kt
danielceinos
255,063,143
false
{"Gradle": 12, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 11, "Batchfile": 1, "Java": 1, "Kotlin": 45, "INI": 2, "Proguard": 3, "XML": 20, "YAML": 1}
package com.danielceinos.todolist.features.recipeslist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.MergeAdapter import com.danielceinos.todolist.databinding.FragmentRecipesListBinding import com.danielceinos.todolist.di.viewModel import com.danielceinos.todolist.features.base.BaseFragment import com.danielceinos.todolist.features.recipeslist.FooterAdapter.FooterState import com.hoopcarpool.fluxy.Result /** * A simple [Fragment] subclass. */ class RecipesListFragment : BaseFragment() { private val viewModel: RecipesListViewModel by viewModel() private lateinit var binding: FragmentRecipesListBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = FragmentRecipesListBinding.inflate(inflater).also { binding = it }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recipesAdapter = RecipesAdapter({ findNavController().navigate(RecipesListFragmentDirections.actionListFragmentToDetailFragment(it.id, it.title)) }, { viewModel.markFavorite(it.id) }) val footerAdapter = FooterAdapter { viewModel.loadRecipes() } binding.recipesRecyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) binding.recipesRecyclerView.adapter = MergeAdapter(recipesAdapter, footerAdapter) viewModel.getLiveData().observe { when (it) { is Result.Success -> { recipesAdapter.submitList(it.value.recipes) footerAdapter.state = if (it.value.cached) FooterState.ERROR else FooterState.LOADED } is Result.Loading -> footerAdapter.state = FooterState.LOADING is Result.Failure -> footerAdapter.state = FooterState.ERROR is Result.Empty -> { } } } } }
1
null
1
1
708e523296bd130f190cf4f7c89707ac774dd797
2,274
RecipesTestApp
MIT License
app/src/main/java/com/qlang/eyepetizer/ui/dialog/TipsDialog.kt
qlang122
309,645,125
false
null
package com.qlang.eyepetizer.ui.dialog import android.app.Dialog import android.content.Context import android.widget.TextView import com.libs.dialog.CustomViewDialog import com.qlang.eyepetizer.R /** * @author Created by qlang on 2018/7/11. */ object TipsDialog { fun show(context: Context, content: String, onOk: ((Dialog) -> Unit)? = null, onCancel: ((Dialog) -> Unit)? = null, title: String? = null, okBtnStr: String? = null, cancelBtnStr: String? = null, cancelable: Boolean = true, touchOutsideCancelable: Boolean = false): Dialog { val dialog = CustomViewDialog.newInstance(context, R.layout.dialog_tips_affirm, cancelable, touchOutsideCancelable) { view, dialog -> val tvTitle = view.findViewById<TextView>(R.id.tv_tipdialog_title) val tvContent = view.findViewById<TextView>(R.id.tv_tipdialog_content) val btnCancel = view.findViewById<TextView>(R.id.btn_dialog_cancel) val btnOk = view.findViewById<TextView>(R.id.btn_dialog_ok) title?.let { if (it.isNotEmpty()) tvTitle.text = it } tvContent.text = content okBtnStr?.let { if (it.isNotEmpty()) btnOk.text = it } cancelBtnStr?.let { if (it.isNotEmpty()) btnCancel.text = it } btnOk.setOnClickListener { if (onOk == null) dialog.cancel() else onOk?.invoke(dialog) } btnCancel.setOnClickListener { if (onCancel == null) dialog.cancel() else onCancel?.invoke(dialog) } } dialog.show() return dialog } }
1
null
3
2
3eefe4b5734aeb58994ff1af7a1850c7b7740e64
1,551
EyepetizerTv
Apache License 2.0
app/src/main/java/com/qlang/eyepetizer/ui/dialog/TipsDialog.kt
qlang122
309,645,125
false
null
package com.qlang.eyepetizer.ui.dialog import android.app.Dialog import android.content.Context import android.widget.TextView import com.libs.dialog.CustomViewDialog import com.qlang.eyepetizer.R /** * @author Created by qlang on 2018/7/11. */ object TipsDialog { fun show(context: Context, content: String, onOk: ((Dialog) -> Unit)? = null, onCancel: ((Dialog) -> Unit)? = null, title: String? = null, okBtnStr: String? = null, cancelBtnStr: String? = null, cancelable: Boolean = true, touchOutsideCancelable: Boolean = false): Dialog { val dialog = CustomViewDialog.newInstance(context, R.layout.dialog_tips_affirm, cancelable, touchOutsideCancelable) { view, dialog -> val tvTitle = view.findViewById<TextView>(R.id.tv_tipdialog_title) val tvContent = view.findViewById<TextView>(R.id.tv_tipdialog_content) val btnCancel = view.findViewById<TextView>(R.id.btn_dialog_cancel) val btnOk = view.findViewById<TextView>(R.id.btn_dialog_ok) title?.let { if (it.isNotEmpty()) tvTitle.text = it } tvContent.text = content okBtnStr?.let { if (it.isNotEmpty()) btnOk.text = it } cancelBtnStr?.let { if (it.isNotEmpty()) btnCancel.text = it } btnOk.setOnClickListener { if (onOk == null) dialog.cancel() else onOk?.invoke(dialog) } btnCancel.setOnClickListener { if (onCancel == null) dialog.cancel() else onCancel?.invoke(dialog) } } dialog.show() return dialog } }
1
null
3
2
3eefe4b5734aeb58994ff1af7a1850c7b7740e64
1,551
EyepetizerTv
Apache License 2.0
graphecule-client/src/main/kotlin/graphecule/client/builder/GraphRequestBuilderClassBuilder.kt
josesamuel
259,990,102
false
null
/* * Copyright (C) 2020 <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 graphecule.client.builder import com.squareup.kotlinpoet.* import graphecule.client.model.ClassInfo import graphecule.client.model.FieldInfo import graphecule.client.model.GraphModel import graphecule.client.model.TypeKind import graphecule.common.HttpRequestAdapter import java.io.File /** * Builder for inner Request.Builder */ internal class GraphRequestBuilderClassBuilder( parentPackageName: String, outputLocation: File, classInfoToBuild: ClassInfo, graphModel: GraphModel, private val classBuilder: TypeSpec.Builder, private val outerClassBuilder: TypeSpec.Builder ) : AbstractClassBuilder(parentPackageName, outputLocation, classInfoToBuild, graphModel) { override fun build() { writeInnerGraphRequestBuilder() } /** * Builds the inner Builder and its fetch/invoke methods */ private fun writeInnerGraphRequestBuilder() { val messageSuffix = if (classInfoToBuild == graphModel.mutationClass) "Use any of the \"invoke\" methods to specify which operations needs to be performed, and " else "Use any of the \"fetch\" methods to specify which parameters needs to be fetched, and " var companionBuilder: TypeSpec.Builder? = null if (classInfoToBuild == graphModel.mutationClass) { companionBuilder = TypeSpec.companionObjectBuilder() } val requestBuilder = TypeSpec.classBuilder("Builder") .addKdoc("Builder class to build [${classInfoToBuild.name}.${classInfoToBuild.name}$innerRequestClassNameSuffix].\n\n") .addKdoc(messageSuffix) .addKdoc(" use [build] method to build an instance of [${classInfoToBuild.name}.${classInfoToBuild.name}$innerRequestClassNameSuffix]") .addModifiers(KModifier.PUBLIC) .addProperty( PropertySpec .builder("fieldsRequested", StringBuilder::class) .addModifiers(KModifier.PRIVATE) .initializer("StringBuilder(\" { __typename \")") .build() ) val message2 = if (classInfoToBuild == graphModel.mutationClass) "All operations that marked to be performed by calling the \"invoke\" methods\n" else "All fields that marked to be fetched by calling the \"fetch\" methods\n" val message3 = if (classInfoToBuild == graphModel.mutationClass) "performed" else "invoked" requestBuilder.addFunction( FunSpec.builder("build") .addKdoc("Returns an instance of [${classInfoToBuild.name}.${classInfoToBuild.name}$innerRequestClassNameSuffix].\n\n") .addKdoc(message2) .addKdoc(" on this [Builder] instance can be $message3 using the returned [${classInfoToBuild.name}.${classInfoToBuild.name}$innerRequestClassNameSuffix]") .returns(ClassName("", "${classInfoToBuild.name}$innerRequestClassNameSuffix")) .addStatement("fieldsRequested.append(\" } \")") .addStatement("val requestString = fieldsRequested.toString()") .addStatement("fieldsRequested.clear()") .addStatement("return·${classInfoToBuild.name}$innerRequestClassNameSuffix(requestString)").build() ) addFetchMethods(requestBuilder, companionBuilder) classBuilder.addType(requestBuilder.build()) if (companionBuilder != null) { outerClassBuilder.addType(companionBuilder.build()) } } /** * Add all the fetch methods */ private fun addFetchMethods(classBuilder: TypeSpec.Builder, companionBuilder: TypeSpec.Builder?) { val methodName = if (classInfoToBuild == graphModel.mutationClass) "invoke" else "fetch" classInfoToBuild.fields?.forEach { fieldInfo -> val fetchName = fieldInfo.name var fieldEffectiveType = fieldInfo.fieldType if (fieldEffectiveType.kind == TypeKind.LIST) { fieldEffectiveType = fieldInfo.fieldType.subType!! } if (fieldEffectiveType.kind != TypeKind.UNION) { addFetchMethod( classBuilder, companionBuilder, "$methodName${fetchName.capitalize()}", fieldEffectiveType.name, fieldInfo, false ) } if (fieldEffectiveType.kind in arrayOf(TypeKind.UNION, TypeKind.INTERFACE)) { graphModel.classMap[fieldEffectiveType.name]?.childClasses?.forEach { addFetchMethod( classBuilder, companionBuilder, "$methodName${fetchName.capitalize()}As$it", it, fieldInfo, true ) } } } } /** * Adds the fetch method for the given name */ private fun addFetchMethod(classBuilder: TypeSpec.Builder, companionBuilder: TypeSpec.Builder?, fetchName: String, fetchAs: String, fieldInfo: FieldInfo, isExtensionFetch: Boolean) { val fetchBuilder = FunSpec .builder(fetchName) .addKdoc("Returns a [Builder] that can build a [${classInfoToBuild.name}$innerRequestClassNameSuffix] that fetches the field [${fieldInfo.name}] as [$fetchAs]\n") .returns(ClassName("", "Builder")) val companionCallParamList = if (companionBuilder != null) StringBuilder() else null val companionFetchBuilder = if (companionBuilder != null) FunSpec.builder(fetchName).addModifiers(KModifier.SUSPEND) else null companionFetchBuilder?.addKdoc("Invoke the mutation operation \"${fieldInfo.name}\"\n")?.returns(getType(fieldInfo.fieldType)) var fieldEffectiveType = fieldInfo.fieldType.kind if (fieldEffectiveType == TypeKind.LIST) { fieldEffectiveType = fieldInfo.fieldType.subType!!.kind } var requestBuilderAdded = false if (fieldEffectiveType in arrayOf(TypeKind.OBJECT, TypeKind.INTERFACE, TypeKind.UNION)) { requestBuilderAdded = true fetchBuilder.addParameter("request", ClassName("", "${getPackageNameForClass(fetchAs)}.${fetchAs}.${fetchAs}$innerRequestClassNameSuffix")) fetchBuilder.addKdoc( "@param request [$fetchAs.$fetchAs$innerRequestClassNameSuffix] that specifies which fields should be fetched from [%T]. \n", ClassName(getPackageNameForClass(fetchAs), fetchAs) ) companionFetchBuilder?.addParameter("request", ClassName("", "${getPackageNameForClass(fetchAs)}.${fetchAs}.${fetchAs}$innerRequestClassNameSuffix")) ?.addKdoc( "@param request [$fetchAs.$fetchAs$innerRequestClassNameSuffix] that specifies which fields should be fetched from the result [%T]. \n", ClassName(getPackageNameForClass(fetchAs), fetchAs) ) companionCallParamList?.append("request") } fieldInfo.fieldArgs?.forEachIndexed { index, argInfo -> if (index == 0) { fetchBuilder.addStatement("val argsRequested = StringBuilder()") } if (!companionCallParamList.isNullOrEmpty()) { companionCallParamList.append(", ") } companionCallParamList?.append(argInfo.name) val argBuilder = ParameterSpec.builder(argInfo.name, getType(argInfo.fieldType)) val companionArgBuilder = if (companionFetchBuilder != null) ParameterSpec.builder(argInfo.name, getType(argInfo.fieldType)) else null if (argInfo.fieldType.isNullable) { fetchBuilder.beginControlFlow("if (${escapeIfKeyword(argInfo.name)} != null )") } fetchBuilder.addStatement("argsRequested.append(\"${argInfo.name}·:·\")") if (!argInfo.defaultValue.isNullOrEmpty()) { when (argInfo.fieldType.kind) { TypeKind.STRING, TypeKind.ID -> { argBuilder.defaultValue("%S", argInfo.defaultValue) companionArgBuilder?.defaultValue("%S", argInfo.defaultValue) } TypeKind.INT, TypeKind.FLOAT, TypeKind.BOOLEAN -> { argBuilder.defaultValue(argInfo.defaultValue!!) companionArgBuilder?.defaultValue(argInfo.defaultValue!!) } TypeKind.ENUM -> { argBuilder.defaultValue("${argInfo.fieldType.name}.${argInfo.defaultValue?.toUpperCase()?.removeQuotes()}") companionArgBuilder?.defaultValue("${argInfo.fieldType.name}.${argInfo.defaultValue?.toUpperCase()?.removeQuotes()}") } else -> { //println("Ignoring default for arg ${argInfo.name} ${argInfo.defaultValue}") } } } else if (argInfo.fieldType.isNullable) { argBuilder.defaultValue("null") companionArgBuilder?.defaultValue("null") } when (argInfo.fieldType.kind) { TypeKind.STRING, TypeKind.ID -> { fetchBuilder.addStatement("argsRequested.append(\"\\\"\${${escapeIfKeyword(argInfo.name)}.toString()}\\\"\")·") } else -> { fetchBuilder.addStatement("argsRequested.append(${escapeIfKeyword(argInfo.name)}.toString())") } } fetchBuilder.addStatement("argsRequested.append(\" \")") if (argInfo.fieldType.isNullable) { fetchBuilder.endControlFlow() } fetchBuilder.addParameter(argBuilder.build()) companionFetchBuilder?.addParameter(companionArgBuilder!!.build()) if (!argInfo.description.isNullOrEmpty()) { fetchBuilder.addKdoc("@param ${argInfo.name} %S\n", argInfo.description) companionFetchBuilder?.addKdoc("@param ${argInfo.name} %S\n", argInfo.description) } } if (!fieldInfo.fieldArgs.isNullOrEmpty()) { fetchBuilder.beginControlFlow("val argString = if (argsRequested.isNotEmpty())") fetchBuilder.addStatement("\" ( \${argsRequested.toString()} ) \"") fetchBuilder.endControlFlow() fetchBuilder.beginControlFlow("else") fetchBuilder.addStatement("\"\"") fetchBuilder.endControlFlow() fetchBuilder.addStatement("fieldsRequested.append(\"·${fieldInfo.name}·\$argString\")") } else { fetchBuilder.addStatement("fieldsRequested.append(\"·${fieldInfo.name}·\")") } if (requestBuilderAdded) { if (isExtensionFetch) { fetchBuilder.addStatement("fieldsRequested.append(\"·{·...·on·$fetchAs·\")") } fetchBuilder.addStatement("fieldsRequested.append(request.requestString)") if (isExtensionFetch) { fetchBuilder.addStatement("fieldsRequested.append(\" } \")") } } fetchBuilder.addStatement("return this") classBuilder.addFunction(fetchBuilder.build()) companionBuilder?.let { companionFetchBuilder?.addParameter( ParameterSpec.builder("httpRequestAdapter", HttpRequestAdapter::class.asTypeName().copy(true)) .defaultValue("null") .build() ) ?.addStatement("return·${classInfoToBuild.name}$innerRequestClassNameSuffix.Builder().$fetchName(${companionCallParamList?.toString()}).build().invoke(httpRequestAdapter).${fieldInfo.name}") it.addFunction(companionFetchBuilder!!.build()) } } }
1
Kotlin
1
2
82bd348f06a84eccf946541a1683f32f509cfe5a
12,393
graphecule
Apache License 2.0
doppel/src/main/java/makes/flint/doppel/state/BackgroundOnlyState.kt
Flinted
95,310,288
false
null
package makes.flint.doppel.doppelState.state import android.graphics.drawable.Drawable import android.view.View import makes.flint.doppel.backgroundproviders.drawables.DoppelAnimatable /** * BackgroundOnlyState */ class BackgroundOnlyState(view: View, private val background: Drawable ) : BaseViewState<View>(view), ViewState<View> { private val originalBackground = view.background override fun doppel() { super.doppel() originalBackground ?: return val view = view.get() ?: return view.background = background (view.background as? DoppelAnimatable)?.start(view) } override fun restore() { super.doppel() originalBackground ?: return val view = view.get() ?: return (view.background as? DoppelAnimatable)?.stop(view) view.background = originalBackground } }
1
null
1
1
6c777b8af1c9fe15d668f641cd38928d0fcd2a61
892
Doppel
Apache License 2.0
app/src/main/java/com/muzzley/model/webview/WebviewMessage.kt
habitio
191,952,436
false
null
package com.muzzley.model.webview import com.google.gson.JsonElement class WebviewMessage ( val cid: String? = null, val rcid: String? = null, val data: Data? = null ){ class Data ( val h: H? = null, val a: String? = null, val m: String? = null, val s: Boolean? = null, val d: D? = null ){ class H ( val ch: String? = null ) class D ( val type: String? = null, val value: JsonElement? = null, val componentId: String? = null, val io: String? = null, val profile: String? = null, val channel: String? = null, val component: String? = null, val property: String? = null, val data: JsonElement? = null, val ruleUnit: JsonElement? = null ) } }
1
null
1
1
57174e1ca5e0d72ebc01d0750e278fc493b44e42
877
habit-whitelabel-app-android
MIT License
urbanairship-feature-flag/src/test/java/com/urbanairship/featureflag/EvaluationOptionsTest.kt
urbanairship
58,972,818
false
{"Java": 4021541, "Kotlin": 1676659, "Python": 10137, "Shell": 661}
package com.urbanairship.featureflag import androidx.test.ext.junit.runners.AndroidJUnit4 import com.urbanairship.json.jsonMapOf import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class EvaluationOptionsTest { @Test fun testParse() { val json = jsonMapOf( "disallow_stale_value" to true, "ttl" to 1800000 ) val fromJson = EvaluationOptions.fromJson(json) assert(fromJson?.disallowStaleValues == true) assert(fromJson?.ttl == 1800000.toULong()) } }
2
Java
124
106
c6d288c430f1f6860c3e45083fdf55889ecfe11d
562
android-library
Apache License 2.0
native/swift/sir/tree-generator/src/org/jetbrains/kotlin/sir/tree/generator/model/Element.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.sir.tree.generator.model import org.jetbrains.kotlin.generators.tree.* import org.jetbrains.kotlin.sir.tree.generator.BASE_PACKAGE class Element(name: String, override val propertyName: String) : AbstractElement<Element, Field, Implementation>(name) { override var kDoc: String? = null override val fields: MutableSet<Field> = mutableSetOf() override val params: MutableList<TypeVariable> = mutableListOf() override val elementParents: MutableList<ElementRef<Element>> = mutableListOf() override val otherParents: MutableList<ClassRef<*>> = mutableListOf() override var visitorParameterName: String = safeDecapitalizedName override var kind: ImplementationKind? = null override val namePrefix: String get() = "Sir" override val packageName: String get() = BASE_PACKAGE override val element: Element get() = this override val nullable: Boolean get() = false override val args: Map<NamedTypeParameterRef, TypeRef> get() = emptyMap() operator fun Field.unaryPlus(): Field { fields.add(this) return this } }
178
null
5729
47,397
a47dcc227952c0474d27cc385021b0c9eed3fb67
1,369
kotlin
Apache License 2.0
imageviewplus/src/main/java/com/sailflorve/imageviewplus/util/ViewUtil.kt
SailFlorve
202,099,160
false
null
package com.sailflorve.imageviewplus.util import android.content.Context import android.graphics.* import android.net.Uri import android.util.Log import android.view.View import android.widget.ImageView import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import java.io.FileNotFoundException import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt object ViewUtil { private const val TAG = "ViewUtil" @JvmStatic fun getDistance(p1: PointF, p2: PointF): Float { return sqrt((p2.x - p1.x.toDouble()).pow(2.0) + (p2.y - p1.y.toDouble()).pow(2.0)).toFloat() } @JvmStatic fun getBmpFromDrawable(context: Context, @DrawableRes resId: Int): Bitmap { return BitmapFactory.decodeResource(context.resources, resId) } /** * 获得正好适合于给定宽高的Bitmap * * @param src 原Bitmap * @return 缩放后的Bitmap */ @JvmStatic fun getScaledBitmap(src: Bitmap, srcW: Int, srcH: Int): Bitmap { Log.d(TAG, "getScaledBitmap: $srcW$srcH") if (src.width == srcW && src.height < srcH || src.height == srcH && src.width < srcW) { return src } val ratio = when { src.width >= src.height -> { srcW / src.width.toFloat() } src.height >= src.width -> { srcH / src.height.toFloat() } else -> { return getScaledBitmap(src, 1f) } } Log.d(TAG, "getScaledBitmap: $ratio") return getScaledBitmap(src, ratio) } @JvmStatic fun getScaledBitmap(src: Bitmap, ratio: Float): Bitmap { val matrix = Matrix() matrix.postScale(ratio, ratio) return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true) } /** * 判断x,y是否在View上。 */ @JvmStatic fun checkPointInView(v: View, x: Float, y: Float): Boolean { return (x > v.x && x < v.x + v.width && y > v.y && y < v.y + v.height) } /** * 使某View始终处于另一个View之内。 * * @param out 外面的View * @param inside 在里面的View */ @JvmStatic fun keepViewIn(out: View, inside: View) { //Right if (inside.x + inside.width > out.right) { inside.x = out.right - inside.width.toFloat() } if (inside.y + inside.height > out.bottom) { inside.y = out.bottom - inside.height.toFloat() } if (inside.x < out.x) { inside.x = out.x } if (inside.y < out.y) { inside.y = out.y } } /** * Bitmap的像素数与ImageView所占像素不一致时,计算两者之间的缩放。 */ @JvmStatic fun getRatioOfImageViewAndBitmap(iv: ImageView, bm: Bitmap): Float { return if (iv.width >= iv.height) { bm.width / iv.width.toFloat() } else { bm.height / iv.height.toFloat() } } /** * 计算ViewGroup中的点相对于Bitmap的坐标 * * @param imageView 包含Bitmap的ImageView * @param bitmap ImageView中的Bitmap * @param point 点在父布局的坐标 * @return 点在bitmap中的坐标 */ @JvmStatic fun getPointInBitmap(imageView: ImageView, bitmap: Bitmap, point: PointF): PointF { return getPointInBitmap(imageView, bitmap, point.x, point.y) } @JvmStatic fun getPointInBitmap(imageView: ImageView, bitmap: Bitmap, x: Float, y: Float): PointF { val xToIv = x - imageView.left val yToIv = y - imageView.top val ratio = getRatioOfImageViewAndBitmap(imageView, bitmap) return PointF(xToIv * ratio, yToIv * ratio) } /** * 根据两根手指的坐标,设置View的Pivot。 */ @JvmStatic fun setPivot(view: View, pointer1: PointF, pointer2: PointF) { var newX = (abs(pointer1.x + pointer2.x) / 2 - view.left) newX = if (newX > 0) newX else 0f var newY = (abs(pointer1.y + pointer2.y) / 2 - view.top) newY = if (newY > 0) newY else 0f view.pivotX = newX view.pivotY = newY } @JvmStatic fun getBitmapFromUri(context: Context, uri: Uri?): Bitmap? { try { val inputStream = context.contentResolver.openInputStream(uri!!) return BitmapFactory.decodeStream(inputStream) } catch (e: FileNotFoundException) { e.printStackTrace() } return null } @JvmStatic fun drawLine(canvas: Canvas, lines: List<List<PointF>>?, width: Float, @ColorInt color: Int) { val paint = Paint() if (lines == null || lines.isEmpty()) { return } paint.strokeCap = Paint.Cap.ROUND paint.strokeWidth = width paint.color = color for (pointList in lines) { for (i in 0 until pointList.size - 1) { canvas.drawLine( pointList[i].x, pointList[i].y, pointList[i + 1].x, pointList[i + 1].y, paint ) } } } }
1
null
1
4
745a15018ec40fe8fc60f5e2cf6fef6173112302
5,046
ImageViewPlus
Apache License 2.0
storio-sqlite-annotations-processor/src/main/kotlin/com/pushtorefresh/storio/sqlite/annotations/processor/introspection/StorIOSQLiteColumnMeta.kt
gautamjain
88,312,661
false
{"INI": 9, "Markdown": 6, "Shell": 2, "Batchfile": 1, "Java": 431, "Kotlin": 30, "Proguard": 1, "Java Properties": 1}
package com.pushtorefresh.storio.sqlite.annotations.processor.introspection import com.pushtorefresh.storio.common.annotations.processor.introspection.JavaType import com.pushtorefresh.storio.common.annotations.processor.introspection.StorIOColumnMeta import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteColumn import javax.lang.model.element.Element class StorIOSQLiteColumnMeta( enclosingElement: Element, element: Element, fieldName: String, javaType: JavaType, storIOColumn: StorIOSQLiteColumn) : StorIOColumnMeta<StorIOSQLiteColumn>( enclosingElement, element, fieldName, javaType, storIOColumn)
1
null
1
1
da7a1f541369e072214d39ec57ffd6ca69d85ccf
697
storio
Apache License 2.0
AnidroApp/app/src/main/java/app/anidro/renderers/SingleFrameTimeNormalizer.kt
luboganev
754,639,369
false
{"Text": 1, "Git Attributes": 1, "Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "JSON": 1, "Proguard": 1, "XML": 41, "Kotlin": 37, "Java": 25}
package app.anidro.renderers import app.anidro.models.TimedSegment import java.util.* /** * This time normalizer removes all pauses and sets all segments durations to null. * It practically makes sure that the [FixedFrameRateRenderer] renders a single * frame with the whole drawing in it. */ class SingleFrameTimeNormalizer : DrawingTimeNormalizer { private var normalizedSegments = mutableListOf<TimedSegment>() override val normalizedDuration: Long get() = 0 override val normalizedDrawing: List<TimedSegment> get() = normalizedSegments override fun normalizeDrawing(segments: List<TimedSegment>) { normalizedSegments.clear() for (segment in segments) { segment.adjustStartTimestamp(0) segment.adjustDuration(0) normalizedSegments.add(segment) } } }
0
Java
0
0
91900638ed3f465f6b4cfeb887e9ec08f26d53ce
857
anidro-open-source
MIT License
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/UserWebsiteSummaryTest.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * 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 org.openapitools.client.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import org.openapitools.client.models.UserWebsiteSummary class UserWebsiteSummaryTest : ShouldSpec() { init { // uncomment below to create an instance of UserWebsiteSummary //val modelInstance = UserWebsiteSummary() // to test the property `website` - Website with path or domain only should("test website") { // uncomment below to test the property //modelInstance.website shouldBe ("TODO") } // to test the property `status` - Status of the verification process should("test status") { // uncomment below to test the property //modelInstance.status shouldBe ("TODO") } // to test the property `verifiedAt` - UTC timestamp when the verification happened - sometimes missing should("test verifiedAt") { // uncomment below to test the property //modelInstance.verifiedAt shouldBe ("TODO") } } }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
1,348
pinterest-sdk
MIT License
chat-sdk-core-ui/src/main/java/sdk/chat/ui/activities/preview/ChatPreviewActivity.kt
chat-sdk
77,952,416
false
null
package sdk.chat.ui.activities.preview import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.ImageButton import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.viewpager2.widget.ViewPager2 import com.lassi.common.utils.KeyUtils import com.lassi.data.media.MiMedia import io.reactivex.Completable import org.pmw.tinylog.Logger import sdk.chat.core.dao.Keys import sdk.chat.core.dao.Thread import sdk.chat.core.session.ChatSDK import sdk.chat.core.ui.ThemeProvider import sdk.chat.ui.R import sdk.chat.ui.activities.BaseActivity import sdk.guru.common.DisposableMap import java.io.File open class ChatPreviewActivity: BaseActivity() { open var viewPager2: ViewPager2? = null open var adapter: PreviewPagerAdapter? = null open var addButton: ImageButton? = null open var sendButton: ImageButton? = null open var deleteButton: ImageButton? = null open var exitButton: ImageButton? = null open var positionText: TextView? = null open val dm = DisposableMap() open var threadEntityID: String? = null override fun getLayout(): Int { return R.layout.activity_chat_media_preview } open val receiveData = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { it -> if (it.resultCode == Activity.RESULT_OK) { it.data?.let { addFromIntent(it) } } } open fun addFromIntent(intent: Intent) { val selectedMedia = intent.getSerializableExtra(KeyUtils.SELECTED_MEDIA) as ArrayList<MiMedia> if (!selectedMedia.isNullOrEmpty()) { adapter?.let { ad -> ad.addMedia(selectedMedia) viewPager2?.currentItem = ad.itemCount - 1 } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) updateThread(savedInstanceState) adapter = PreviewPagerAdapter(this) viewPager2 = findViewById(R.id.viewPager) addButton = findViewById(R.id.addButton) sendButton = findViewById(R.id.sendButton) deleteButton = findViewById(R.id.deleteButton) exitButton = findViewById(R.id.exitButton) positionText = findViewById(R.id.positionText) viewPager2?.adapter = adapter viewPager2?.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback() { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { super.onPageScrolled(position, positionOffset, positionOffsetPixels) updatePage() } override fun onPageSelected(position: Int) { super.onPageSelected(position) } override fun onPageScrollStateChanged(state: Int) { super.onPageScrollStateChanged(state) } }) exitButton?.setOnClickListener(View.OnClickListener { finish() }) deleteButton?.setOnClickListener(View.OnClickListener { viewPager2?.let { adapter?.removeItemAtIndex(it.currentItem) updatePage() } }) sendButton?.setOnClickListener(View.OnClickListener { adapter?.let { it -> val thread = ChatSDK.db().fetchEntityWithEntityID(threadEntityID, Thread::class.java) if (thread != null) { for(item in it.media) { var completables = ArrayList<Completable>() item.path?.let { path -> val file = File(path) if (item.duration > 0) { if (ChatSDK.videoMessage() != null && threadEntityID != null) { Logger.debug("Send video"); completables.add(ChatSDK.videoMessage().sendMessageWithVideo(file, thread)) } } else { if (ChatSDK.imageMessage() != null && threadEntityID != null) { Logger.debug("ImageSend: Send image"); completables.add(ChatSDK.imageMessage().sendMessageWithImage(file, thread)) } } } Completable.merge(completables).subscribe(this) } } } finish() }) val provider = ChatSDK.feather().instance( ThemeProvider::class.java ) provider?.applyTheme(sendButton, "chat-preview-send-button") addButton?.setOnClickListener { view: View? -> adapter?.let { if (!it.isVideo()) { val intent = LassiLauncher.launchImagePicker(this) receiveData.launch(intent) } else { val intent = LassiLauncher.launchVideoPicker(this) receiveData.launch(intent) } } } savedInstanceState?.let { val mediaArray = it.getParcelableArrayList<MiMedia>("media") adapter?.addMedia(mediaArray) } addFromIntent(intent) } open fun updateThread(bundle: Bundle?) { var bundle = bundle if (bundle == null) { bundle = intent.extras } if (bundle != null && bundle.containsKey(Keys.IntentKeyThreadEntityID)) { threadEntityID = bundle.getString(Keys.IntentKeyThreadEntityID) } if (threadEntityID == null) { finish() } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) updateThread(intent.extras) addFromIntent(intent) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // Get the items adapter?.let { outState.putParcelableArrayList("media", it.media) } } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) val mediaArray = savedInstanceState.getParcelableArrayList<MiMedia>("media") adapter?.addMedia(mediaArray) } open fun updatePage() { adapter?.let { val count = it.itemCount if (it.itemCount == 0) { positionText?.setText("") } else { val current = (viewPager2?.currentItem ?: 0) + 1 positionText?.setText("$current/$count") } deleteButton?.visibility = if(count > 0) View.VISIBLE else View.INVISIBLE sendButton?.visibility = if(count > 0) View.VISIBLE else View.INVISIBLE } } }
7
null
623
1,600
0fb1a17494128e05a0fa14ca62c2b07bb9111f6d
7,024
chat-sdk-android
Apache License 2.0
app/src/main/java/com/singletondev/bipalogi_chat_revision/utils/SdCardChecked.kt
Leviaran
142,282,712
false
{"Gradle": 3, "Markdown": 1, "Java Properties": 2, "Shell": 1, "Text": 30, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 3, "XML": 38, "Kotlin": 49, "INI": 2}
package com.singletondev.bipalogi_chat_revision.utils import android.content.Context import android.os.Environment import io.reactivex.Observable /** * Created by Randy Arba on 10/28/17. * This apps contains Bipalogi_Chat_Revision * @email [email protected] * @github https://github.com/Leviaran */ class SdCardChecked { companion object { fun isSdCardAvalaible(context: Context) : Boolean = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED fun isSdCardAvalaibleObservable(context: Context): Observable<Boolean> = Observable.just(SdCardChecked.Companion.isSdCardAvalaible(context)) } }
1
null
1
1
ee27f44b33826f04dc0f3d3b07d7e8a92c4d4c55
671
Bipalogi_App
MIT License
app/build/generated/source/navigation-args/debug/ru/iteco/fmhandroid/ui/NewsControlPanelFragmentDirections.kt
nickolichev
682,017,741
false
{"Gradle": 3, "Markdown": 2, "Java Properties": 4, "Shell": 2, "Text": 13, "Ignore List": 3, "Batchfile": 2, "INI": 6, "JSON": 139, "Proguard": 1, "XML": 241, "Java": 231, "Kotlin": 72, "Unix Assembly": 1, "SQL": 2, "Motorola 68K Assembly": 4}
package ru.iteco.fmhandroid.ui import android.os.Bundle import android.os.Parcelable import androidx.navigation.ActionOnlyNavDirections import androidx.navigation.NavDirections import java.io.Serializable import java.lang.UnsupportedOperationException import kotlin.Int import kotlin.Suppress import ru.iteco.fmhandroid.R import ru.iteco.fmhandroid.`enum`.FragmentsTags import ru.iteco.fmhandroid.dto.NewsFilterArgs import ru.iteco.fmhandroid.dto.NewsWithCategory public class NewsControlPanelFragmentDirections private constructor() { private data class ActionNewsControlPanelFragmentToFilterNewsFragment( public val fragmentName: FragmentsTags ) : NavDirections { public override fun getActionId(): Int = R.id.action_newsControlPanelFragment_to_filterNewsFragment @Suppress("CAST_NEVER_SUCCEEDS") public override fun getArguments(): Bundle { val result = Bundle() if (Parcelable::class.java.isAssignableFrom(FragmentsTags::class.java)) { result.putParcelable("fragmentName", this.fragmentName as Parcelable) } else if (Serializable::class.java.isAssignableFrom(FragmentsTags::class.java)) { result.putSerializable("fragmentName", this.fragmentName as Serializable) } else { throw UnsupportedOperationException(FragmentsTags::class.java.name + " must implement Parcelable or Serializable or must be an Enum.") } return result } } private data class ActionNewsControlPanelFragmentToCreateEditNewsFragment( public val newsItemArg: NewsWithCategory? = null ) : NavDirections { public override fun getActionId(): Int = R.id.action_newsControlPanelFragment_to_createEditNewsFragment @Suppress("CAST_NEVER_SUCCEEDS") public override fun getArguments(): Bundle { val result = Bundle() if (Parcelable::class.java.isAssignableFrom(NewsWithCategory::class.java)) { result.putParcelable("newsItemArg", this.newsItemArg as Parcelable?) } else if (Serializable::class.java.isAssignableFrom(NewsWithCategory::class.java)) { result.putSerializable("newsItemArg", this.newsItemArg as Serializable?) } return result } } private data class ActionNewsControlPanelFragmentToNewsListFragment( public val newsFilterArgs: NewsFilterArgs? ) : NavDirections { public override fun getActionId(): Int = R.id.action_newsControlPanelFragment_to_newsListFragment @Suppress("CAST_NEVER_SUCCEEDS") public override fun getArguments(): Bundle { val result = Bundle() if (Parcelable::class.java.isAssignableFrom(NewsFilterArgs::class.java)) { result.putParcelable("newsFilterArgs", this.newsFilterArgs as Parcelable?) } else if (Serializable::class.java.isAssignableFrom(NewsFilterArgs::class.java)) { result.putSerializable("newsFilterArgs", this.newsFilterArgs as Serializable?) } else { throw UnsupportedOperationException(NewsFilterArgs::class.java.name + " must implement Parcelable or Serializable or must be an Enum.") } return result } } public companion object { public fun actionNewsControlPanelFragmentToFilterNewsFragment(fragmentName: FragmentsTags): NavDirections = ActionNewsControlPanelFragmentToFilterNewsFragment(fragmentName) public fun actionNewsControlPanelFragmentToCreateEditNewsFragment(newsItemArg: NewsWithCategory? = null): NavDirections = ActionNewsControlPanelFragmentToCreateEditNewsFragment(newsItemArg) public fun actionNewsControlPanelFragmentToMainFragment(): NavDirections = ActionOnlyNavDirections(R.id.action_newsControlPanelFragment_to_mainFragment) public fun actionNewsControlPanelFragmentToNewsListFragment(newsFilterArgs: NewsFilterArgs?): NavDirections = ActionNewsControlPanelFragmentToNewsListFragment(newsFilterArgs) public fun actionNewsControlPanelFragmentToAuthFragment(): NavDirections = ActionOnlyNavDirections(R.id.action_newsControlPanelFragment_to_authFragment) public fun actionNewsControlPanelFragmentToAboutFragment(): NavDirections = ActionOnlyNavDirections(R.id.action_newsControlPanelFragment_to_aboutFragment) public fun actionNewsControlPanelFragmentToOurMissionFragment(): NavDirections = ActionOnlyNavDirections(R.id.action_newsControlPanelFragment_to_our_mission_fragment) } }
0
Java
0
0
dd940ec5ef2383dd2954fcbab9a068e46f05d7d8
4,402
DiplomaProject
Apache License 2.0
buildSrc/src/main/kotlin/Configuration.kts
ldwqh0
156,142,517
false
{"Java": 1002418, "Vue": 85133, "Kotlin": 65121, "TypeScript": 29934, "JavaScript": 8511, "HTML": 5379, "CSS": 272}
object Versions { const val project = "2.3.0-SNAPSHOT" const val springBoot = "2.6.13" const val springCloud = "2021.0.4" const val queryDsl = "5.0.0" const val commons_io = "2.11.0" const val jsoup = "1.15.1" const val weixin_java_mp = "4.3.0" const val nimbusds = "9.19" const val guava = "31.1-jre" }
1
Java
4
6
e367c29217622ad05c217b8a790a91d267d46b85
340
dm-parent
Apache License 2.0
tmp/arrays/youTrackTests/6928.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-20872 inline fun (() -> Unit).testReceiver() = this() inline fun testArg(it: (() -> Unit)) = it() fun main(args: Array<String>) { { println("test") }.testReceiver() // not inlined testArg { println("test") } // inlined }
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
248
bbfgradle
Apache License 2.0
idea/testData/quickfix/removeUnused/importObjectFun.kt
AlexeyTsvetkov
17,321,988
false
null
// "Safe delete 'MyObj'" "false" // ACTION: Create test import MyObj.foo object <caret>MyObj { fun foo() {} }
1
null
0
2
72a84083fbe50d3d12226925b94ed0fe86c9d794
115
kotlin
Apache License 2.0
app/src/main/java/com/example/sunnyweather/logic/network/SunnyWeatherNetwork.kt
SuperGRX888
843,532,533
false
{"Kotlin": 3409}
package com.example.sunnyweather.logic.network object SunnyWeatherNetwork { private val placeService = ServiceCreator.create<PlaceService>() }
0
Kotlin
0
0
c737aba997c777e3d98c442c8ffba6c9e0cf99b9
147
SunnyWeather
Apache License 2.0
db/src/test/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/db/MapInntektsmeldingDokumentTest.kt
navikt
495,713,363
false
{"Kotlin": 737297, "Shell": 279, "Dockerfile": 68}
package no.nav.helsearbeidsgiver.inntektsmelding.db import no.nav.helsearbeidsgiver.felles.inntektsmelding.felles.models.Ferie import no.nav.helsearbeidsgiver.felles.inntektsmelding.felles.models.Inntekt import no.nav.helsearbeidsgiver.felles.inntektsmelding.felles.models.Periode import no.nav.helsearbeidsgiver.felles.test.mock.GYLDIG_INNSENDING_REQUEST import no.nav.helsearbeidsgiver.utils.test.date.januar import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import java.math.BigDecimal class MapInntektsmeldingDokumentTest { @Test fun testmapInntektsmeldingDokument() { val fulltNavn = "Test Testesen" val arbeidsgiver = "Bedrift A/S" val inntektsmeldingDokument = mapInntektsmeldingDokument(GYLDIG_INNSENDING_REQUEST, fulltNavn, arbeidsgiver) assertNotNull(inntektsmeldingDokument.inntekt) assertEquals(GYLDIG_INNSENDING_REQUEST.inntekt.beregnetInntekt, inntektsmeldingDokument.inntekt?.beregnetInntekt) val periode = Periode(1.januar, 3.januar) val aarsak = Ferie(listOf(periode)) val inntekt = Inntekt(true, BigDecimal.ONE, aarsak, true) val request2 = GYLDIG_INNSENDING_REQUEST.copy(inntekt = inntekt) val dok = mapInntektsmeldingDokument(request2, fulltNavn, arbeidsgiver) assertEquals(inntekt, dok.inntekt) } }
14
Kotlin
0
2
5429c31694c51008188da0c3a79c61e963ad7054
1,416
helsearbeidsgiver-inntektsmelding
MIT License
plugin/src/main/java/com/appunite/firebasetestlabplugin/cloud/CloudTestResultDownloader.kt
gevak1p
270,665,555
true
{"Kotlin": 51345}
package com.appunite.firebasetestlabplugin.cloud import com.appunite.firebasetestlabplugin.FirebaseTestLabPlugin import com.appunite.firebasetestlabplugin.model.ResultTypes import com.appunite.firebasetestlabplugin.utils.asCommand import org.gradle.api.GradleException import org.gradle.api.logging.Logger import java.io.File internal class CloudTestResultDownloader( private val sdk: FirebaseTestLabPlugin.Sdk, private val resultsTypes: ResultTypes, private val gCloudDirectory: File, private val resultsPath: File, private val gCloudBucketName: String, private val logger: Logger) { /** * Get all test results of types resultsTypes */ fun getResults() { if (!resultsTypes.junit && !resultsTypes.logcat && !resultsTypes.video && !resultsTypes.xml) { return } val gCloudFullPath = "$gCloudBucketName/$gCloudDirectory" logger.lifecycle("DOWNLOAD: Downloading results from $gCloudFullPath") prepareDownloadDirectory() downloadTestResults() } private fun prepareDownloadDirectory() { resultsPath.mkdirs() if (!resultsPath.exists()) { throw GradleException("Issue when creating destination dir $gCloudDirectory") } } private fun downloadTestResults() { val excludeQuery = StringBuilder().append(".*\\.txt$|.*\\.apk$") if (!resultsTypes.xml) { excludeQuery.append("|.*\\.xml$") } if (!resultsTypes.xml) { excludeQuery.append("|.*\\.results$") } if (!resultsTypes.logcat) { excludeQuery.append("|.*\\logcat$") } if (!resultsTypes.video) { excludeQuery.append("|.*\\.mp4$") } excludeQuery.append("|.*\\.txt$").toString() // Download requested files under the results directory using multiple threads (-m) val processCreator = ProcessBuilder(sdk.gsutil.absolutePath, "-m", "rsync", "-x", excludeQuery.toString(), "-r", "gs://$gCloudBucketName/$gCloudDirectory", resultsPath.absolutePath) val process = processCreator.start() process.errorStream.bufferedReader().forEachLine { logger.lifecycle(it) } process.inputStream.bufferedReader().forEachLine { logger.lifecycle(it) } process.waitFor() } fun clearResultsDir() { // Delete all files under the results directory using multiple threads (-m) val processCreator = ProcessBuilder(sdk.gsutil.absolutePath, "-m", "rm", "gs://$gCloudBucketName/$gCloudDirectory/**") val process = processCreator.start() process.errorStream.bufferedReader().forEachLine { logger.lifecycle(it) } process.inputStream.bufferedReader().forEachLine { logger.lifecycle(it) } process.waitFor() } }
0
Kotlin
0
0
35fc215a5a8c71ce294fa3399f00f9ab53f4158d
2,900
FirebaseTestLab-Android
Apache License 2.0
app/src/main/java/com/airy/juju/di/AppModule.kt
AiryMiku
174,809,394
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 1, "Kotlin": 112, "XML": 76, "Java": 1}
package com.airy.juju.di import dagger.Module /** * Created by Airy on 2019-09-03 * Mail: <EMAIL> * Github: AiryMiku */ @Module class AppModule
0
Kotlin
1
1
3b0a2035373f9e6dfdf985c5b71c30dcce414273
151
JuJu_Android
MIT License
app/src/main/java/com/example/app/ui/category/CategoryViewModel.kt
phliopox
566,218,116
false
{"Kotlin": 54585}
package com.example.app.ui.category import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.app.model.Category import com.example.app.repository.category.CategoryRepository import com.example.app.ui.common.Event import kotlinx.coroutines.launch class CategoryViewModel(private val categoryRepository: CategoryRepository) : ViewModel() { private val _items = MutableLiveData<List<Category>> () val items :LiveData<List<Category>> = _items private val _openCategoryEvent = MutableLiveData<Event<Category>>() val openCategoryEvent :LiveData<Event<Category>> = _openCategoryEvent init{ loadCategory() } fun openCategoryDetail(category : Category){ _openCategoryEvent.value= Event(category) } private fun loadCategory() { //repository 에 데이터 요청 -> 네트워크 통신 -> ui thread(메인 스레드) 에서 요청하면 안된다. ->repository 에서 스레드 분리 후 -> 뷰모델에서 코루틴 스코프 사용! viewModelScope.launch { val categories = categoryRepository.getCategories() _items.value = categories } } }
0
Kotlin
0
0
0cc9e98aea9855f6ce5d4407369db8b188387e07
1,162
shoppi-android
Info-ZIP License
app/src/main/java/com/aamaulana10/moviecompose/feature/home/core/data/remote/HomeRemoteDataSource.kt
aamaulana10
851,107,989
false
{"Kotlin": 45992}
package com.aamaulana10.moviecompose.feature.home.core.data.remote import com.aamaulana10.moviecompose.feature.home.core.domain.model.MovieVideosModel import com.aamaulana10.moviecompose.utils.network.ApiResponse import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn class HomeRemoteDataSource(private val service: HomeService) { fun getPopularMovies(): Flow<ApiResponse<List<MovieVideosModel>>> { return flow { try { val response = service.getPopularMovies() val dataArray = response.results if (dataArray.isNotEmpty()) { emit(ApiResponse.Success(response.results)) } else { emit(ApiResponse.Empty) } } catch (e: Exception) { emit(ApiResponse.Error(e.toString())) } }.flowOn(Dispatchers.IO) } fun getUpcomingMovies(): Flow<ApiResponse<List<MovieVideosModel>>> { return flow { try { val response = service.getUpcomingMovies() val dataArray = response.results if (dataArray.isNotEmpty()) { emit(ApiResponse.Success(response.results)) } else { emit(ApiResponse.Empty) } } catch (e: Exception) { emit(ApiResponse.Error(e.toString())) } }.flowOn(Dispatchers.IO) } fun getNowPlayingMovies(): Flow<ApiResponse<List<MovieVideosModel>>> { return flow { try { val response = service.getNowPlayingMovies() val dataArray = response.results if (dataArray.isNotEmpty()) { emit(ApiResponse.Success(response.results)) } else { emit(ApiResponse.Empty) } } catch (e: Exception) { emit(ApiResponse.Error(e.toString())) } }.flowOn(Dispatchers.IO) } fun getMovieDetail(movieId: String): Flow<ApiResponse<MovieVideosModel>> { return flow { try { val response = service.getMovieDetail(movieId) emit(ApiResponse.Success(response)) } catch (e: Exception) { emit(ApiResponse.Error(e.toString())) } }.flowOn(Dispatchers.IO) } }
0
Kotlin
0
0
5a6c62ea5796e56962044722583494e5e6923965
2,502
movie-compose
MIT License
ui/src/androidMain/kotlin/kiwi/orbit/compose/ui/controls/Tabs.kt
kiwicom
289,355,053
false
null
package kiwi.orbit.compose.ui.controls import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.shape.ZeroCornerSize import androidx.compose.material3.Divider import androidx.compose.material3.TabPosition import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import kiwi.orbit.compose.ui.OrbitTheme import kiwi.orbit.compose.ui.controls.internal.OrbitElevations import kiwi.orbit.compose.ui.controls.internal.OrbitPreviews import kiwi.orbit.compose.ui.controls.internal.Preview import kiwi.orbit.compose.ui.foundation.ProvideMergedTextStyle @Composable public fun TabRow( selectedTabIndex: Int, modifier: Modifier = Modifier, indicator: @Composable (tabPositions: List<TabPosition>) -> Unit = @Composable { tabPositions -> TabIndicator( Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex]), ) }, tabs: @Composable () -> Unit, ) { OrbitElevations { androidx.compose.material3.TabRow( selectedTabIndex = selectedTabIndex, modifier = modifier, containerColor = OrbitTheme.colors.surface.main, contentColor = contentColorFor(OrbitTheme.colors.surface.main), indicator = indicator, divider = { Divider() }, tabs = tabs, ) } } @Composable public fun Tab( selected: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, text: @Composable () -> Unit, ) { androidx.compose.material3.Tab( selected = selected, onClick = onClick, modifier = modifier, enabled = enabled, selectedContentColor = OrbitTheme.colors.content.normal, unselectedContentColor = OrbitTheme.colors.content.normal, interactionSource = interactionSource, text = { ProvideMergedTextStyle(OrbitTheme.typography.bodyNormalMedium) { text() } }, ) } @Composable public fun TabIndicator( modifier: Modifier = Modifier, color: Color = OrbitTheme.colors.primary.normal, ) { Box( modifier .fillMaxWidth() .height(2.dp) .background( color = color, shape = OrbitTheme.shapes.small.copy( bottomStart = ZeroCornerSize, bottomEnd = ZeroCornerSize, ), ), ) } @OrbitPreviews @Composable internal fun TabsPreview() { Preview { var i by rememberSaveable { mutableIntStateOf(1) } TabRow(selectedTabIndex = i) { Tab(selected = i == 0, onClick = { i = 0 }) { Text("Tab A") } Tab(selected = i == 1, onClick = { i = 1 }) { Text("Tab B") } Tab(selected = i == 2, onClick = { i = 2 }) { Text("Tab C") } } } }
23
null
21
97
6d4026eef9fa059388c50cd9e9760d593c3ad6ac
3,599
orbit-compose
MIT License
src/datastructure/graphs/RootenOranges.kt
minielectron
332,678,510
false
null
package datastructure.graphs /** * You are given an m x n grid where each cell can have one of three values: ● 0 representing an empty cell, ● 1 representing a fresh orange, * or ● 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. * Return the minimum number of minutes that must elapse until no cell has a fresh orange. * If this is impossible, return -1. * * Example 1 Input: grid = [[2,1,1],[1,1,0],[0,1,1]] * Output: 4 * * Example 2 Input: grid = [[2,1,1],[0,1,1],[1,0,1]] * Output: -1 Explanation: * * The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally * */ import java.util.LinkedList import java.util.Queue fun orangesRotting(grid: Array<IntArray>): Int { val rows = grid.size val cols = grid[0].size // Define four possible directions (up, down, left, right) val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) // Initialize a queue to perform BFS val queue: Queue<kotlin.Pair<Int, Int>> = LinkedList() // Initialize variables to keep track of time and fresh oranges var minutes = 0 var freshOranges = 0 // Enqueue all rotten oranges and count fresh oranges // This step also ensure to handle multiple rotten oranges at same time. for (i in 0 until rows) { for (j in 0 until cols) { if (grid[i][j] == 2) { queue.offer(Pair(i, j)) } else if (grid[i][j] == 1) { freshOranges++ } } } // Perform BFS while (queue.isNotEmpty()) { val size = queue.size for (i in 0 until size) { val (x, y) = queue.poll() for (direction in directions) { val newX = x + direction[0] val newY = y + direction[1] if (newX in 0 until rows && newY in 0 until cols && grid[newX][newY] == 1) { grid[newX][newY] = 2 freshOranges-- queue.offer(Pair(newX, newY)) } } } minutes++ } // If there are still fresh oranges left, it's impossible to rot them all return if (freshOranges == 0) minutes else -1 } fun main() { val grid1 = arrayOf( intArrayOf(2, 1, 1), intArrayOf(1, 1, 0), intArrayOf(0, 1, 2) ) val grid2 = arrayOf( intArrayOf(2, 1, 1), intArrayOf(0, 1, 1), intArrayOf(1, 0, 1) ) println(orangesRotting(grid1)) // Output: 4 println(orangesRotting(grid2)) // Output: -1 } fun printMatrix(matrix: Array<IntArray>){ for (i in matrix.indices) { for (j in matrix[i].indices) { print("${matrix[i][j]} \t") } println() } }
1
null
1
1
f2aaff0a995071d6e188ee19f72b78d07688a672
2,883
data-structure-and-coding-problems
Apache License 2.0
src/test/kotlin/dev/rudge/domain/service/RiskEvaluationServiceTest.kt
Rudge
378,707,043
false
null
package dev.rudge.domain.service import dev.rudge.domain.entities.UserInformationFactory import io.mockk.clearAllMocks import io.mockk.mockk import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class RiskEvaluationServiceTest { private val autoRiskScoreService = mockk<AutoRiskScoreService>(relaxed = true) private val disabilityRiskScoreService = mockk<DisabilityRiskScoreService>(relaxed = true) private val homeRiskScoreService = mockk<HomeRiskScoreService>(relaxed = true) private val lifeRiskScoreService = mockk<LifeRiskScoreService>(relaxed = true) private val riskEvaluationService = RiskEvaluationService( autoRiskScoreService, disabilityRiskScoreService, homeRiskScoreService, lifeRiskScoreService ) @BeforeEach fun before() { clearAllMocks() } @Test fun `given an user information with age less than 0 when calculate risk should throws exception`() { val userInformation = UserInformationFactory.sample(age = -1) assertThrows<IllegalArgumentException>( "Invalid age, must be equal or greater than 0!" ) { riskEvaluationService.calculate(userInformation) } } @Test fun `given an user information with number of dependents less than 0 when calculate risk should throws exception`() { val userInformation = UserInformationFactory.sample(dependents = -1) assertThrows<IllegalArgumentException>( "Invalid dependents, must be equal or greater than 0!" ) { riskEvaluationService.calculate(userInformation) } } @Test fun `given an user information with income less than 0 when calculate risk should throws exception`() { val userInformation = UserInformationFactory.sample(income = -1) assertThrows<IllegalArgumentException>( "Invalid income, must be equal or greater than 0!" ) { riskEvaluationService.calculate(userInformation) } } @Test fun `given an user information without risk answers when calculate risk should throws exception`() { val userInformation = UserInformationFactory.sample(riskQuestions = emptyList()) assertThrows<IllegalArgumentException>( "Invalid risk answers, must have 3 answers!" ) { riskEvaluationService.calculate(userInformation) } } }
0
Kotlin
0
0
c8701939656066c40e1da55f9c899a56a6a0088d
2,525
insurance-advisor-service
MIT License
src/main/kotlin/io/github/josemiguelmelo/lnd/bolt11/model/Bolt11.kt
josemiguelmelo
837,419,612
false
{"Kotlin": 38320}
package io.github.josemiguelmelo.lnd.bolt11.model data class Bolt11( val hrp: HumanReadablePart, val data: Bolt11Data, val checksum: String, )
0
Kotlin
0
0
fd6957380d5ca8fe2260fa0e07ae17a6a3e62675
156
bolt11-util
MIT License
sdk-scrapper/src/main/kotlin/io/github/wulkanowy/sdk/scrapper/exams/Exam.kt
wulkanowy
138,756,468
false
null
package io.github.wulkanowy.sdk.scrapper.exams import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import java.util.Date @JsonClass(generateAdapter = true) data class Exam( @Json(name = "DataModyfikacji") val entryDate: Date, @Json(name = "Nazwa") val subject: String, @Json(name = "Rodzaj") val type: String, @Json(name = "Opis") val description: String, @Json(name = "Pracownik") val teacher: String ) { @Transient lateinit var date: Date @Transient lateinit var teacherSymbol: String }
9
Kotlin
4
18
57680ecb3fa0ddf352ab1c5c53a00f260e5d6c9c
569
sdk
Apache License 2.0
services/csm.cloud.project.statistics/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/common/extensions/EventStreamGeneratorExtensions.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2022 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.common.extensions import com.bosch.pt.csm.cloud.common.extensions.toEpochMilli import com.bosch.pt.csm.cloud.common.messages.AggregateIdentifierAvro import com.bosch.pt.csm.cloud.common.test.event.EventStreamGenerator import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitDayCardG2 import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitTask import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitTaskSchedule import com.bosch.pt.csm.cloud.projectmanagement.task.messages.DayCardEventEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.DayCardReasonNotDoneEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.DayCardStatusEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskScheduleSlotAvro import java.time.LocalDate fun EventStreamGenerator.submitTaskScheduleWithDayCardsG2( taskName: String, dayCards: Map<LocalDate, Pair<DayCardStatusEnumAvro, DayCardReasonNotDoneEnumAvro?>>, scheduleStart: LocalDate? = dayCards.keys.minOrNull(), scheduleEnd: LocalDate? = dayCards.keys.maxOrNull(), ) { var counter = 0 val slots = dayCards .mapValues { status -> submitDayCardG2UntilState( name = "$taskName-daycard-$counter", taskName = taskName, dayCardStatus = status.value.first, notDoneReason = status.value.second) .also { counter += 1 } } .mapValues { entry -> TaskScheduleSlotAvro.newBuilder() .setDate(entry.key.toEpochMilli()) .setDayCard(getByReference(entry.value)) .build() } .values .toList() submitTaskSchedule( asReference = "$taskName-schedule", aggregateModifications = { it.task = getByReference(taskName) it.start = scheduleStart?.toEpochMilli() it.end = scheduleEnd?.toEpochMilli() it.slots = slots }) } fun EventStreamGenerator.submitDayCardsInDifferentWeeks( startDateWeekOne: LocalDate, differenceInWeeks: Long ) { val startDateWeekTwo = startDateWeekOne.plusWeeks(differenceInWeeks) val dayCards = mapOf( startDateWeekOne to Pair(DayCardStatusEnumAvro.DONE, null), startDateWeekOne.plusDays(1) to Pair(DayCardStatusEnumAvro.APPROVED, null), startDateWeekOne.plusDays(2) to Pair(DayCardStatusEnumAvro.NOTDONE, null), startDateWeekOne.plusDays(3) to Pair(DayCardStatusEnumAvro.OPEN, null), startDateWeekTwo to Pair(DayCardStatusEnumAvro.DONE, null), startDateWeekTwo.plusDays(1) to Pair(DayCardStatusEnumAvro.APPROVED, null), startDateWeekTwo.plusDays(2) to Pair(DayCardStatusEnumAvro.NOTDONE, null), startDateWeekTwo.plusDays(3) to Pair(DayCardStatusEnumAvro.OPEN, null)) submitTaskScheduleWithDayCardsG2("task-1", dayCards) } fun EventStreamGenerator.submitDayCardsInSameWeek(startDate: LocalDate) { val dayCards = mapOf( startDate to Pair(DayCardStatusEnumAvro.DONE, null), startDate.plusDays(1) to Pair(DayCardStatusEnumAvro.APPROVED, null), startDate.plusDays(2) to Pair(DayCardStatusEnumAvro.NOTDONE, null), startDate.plusDays(3) to Pair(DayCardStatusEnumAvro.OPEN, null)) submitTaskScheduleWithDayCardsG2("task-1", dayCards) } fun EventStreamGenerator.submitDayCardsWithState( startDate: LocalDate, state: DayCardStatusEnumAvro ) { val dayCards = mapOf( startDate to Pair(state, null), startDate.plusDays(1) to Pair(state, null), startDate.plusDays(2) to Pair(state, null)) submitTaskScheduleWithDayCardsG2("task-1", dayCards) } fun EventStreamGenerator.submitDayCardsForDifferentTasks(startDate: LocalDate) { submitTask(asReference = "another-task") { it.craft = getByReference("craft-1") it.assignee = getByReference("participant-fm-a") } val dayCardsOfTask = mapOf( startDate to Pair(DayCardStatusEnumAvro.APPROVED, null), startDate.plusDays(1) to Pair(DayCardStatusEnumAvro.NOTDONE, null), startDate.plusDays(2) to Pair(DayCardStatusEnumAvro.OPEN, null)) submitTaskScheduleWithDayCardsG2("task-1", dayCardsOfTask) submitTaskScheduleWithDayCardsG2( "another-task", mapOf(Pair(startDate, Pair(DayCardStatusEnumAvro.DONE, null)))) } fun EventStreamGenerator.submitScheduleWithDayCards( taskName: String, startDate: LocalDate ): AggregateIdentifierAvro { val dayCards = mapOf( startDate.plusDays(1) to Pair(DayCardStatusEnumAvro.OPEN, null), startDate.plusDays(3) to Pair(DayCardStatusEnumAvro.DONE, null)) submitTaskScheduleWithDayCardsG2(taskName, dayCards, startDate, startDate.plusWeeks(1)) return getByReference("$taskName-daycard-0") } private fun EventStreamGenerator.submitDayCardForOpenStatus( name: String, taskName: String, ) { submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.CREATED) { it.status = DayCardStatusEnumAvro.OPEN it.task = getByReference(taskName) } } private fun EventStreamGenerator.submitDayCardsForNotDoneStatus( name: String, taskName: String, notDoneReason: DayCardReasonNotDoneEnumAvro? ) { submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.CREATED) { it.status = DayCardStatusEnumAvro.OPEN it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.COMPLETED) { it.status = DayCardStatusEnumAvro.DONE it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.CANCELLED) { it.status = DayCardStatusEnumAvro.NOTDONE it.task = getByReference(taskName) it.reason = notDoneReason ?: DayCardReasonNotDoneEnumAvro.BAD_WEATHER } } private fun EventStreamGenerator.submitDayCardsForDoneStatus(name: String, taskName: String) { submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.CREATED) { it.status = DayCardStatusEnumAvro.OPEN it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.COMPLETED) { it.status = DayCardStatusEnumAvro.DONE it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.RESET) { it.status = DayCardStatusEnumAvro.OPEN it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.COMPLETED) { it.status = DayCardStatusEnumAvro.DONE it.task = getByReference(taskName) } } private fun EventStreamGenerator.submitDayCardsForApprovedStatus(name: String, taskName: String) { submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.CREATED) { it.status = DayCardStatusEnumAvro.OPEN it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.COMPLETED) { it.status = DayCardStatusEnumAvro.DONE it.task = getByReference(taskName) } submitDayCardG2(asReference = name, eventType = DayCardEventEnumAvro.APPROVED) { it.status = DayCardStatusEnumAvro.APPROVED it.task = getByReference(taskName) } } private fun EventStreamGenerator.submitDayCardG2UntilState( name: String = "dayCard", taskName: String = "task", dayCardStatus: DayCardStatusEnumAvro = DayCardStatusEnumAvro.OPEN, notDoneReason: DayCardReasonNotDoneEnumAvro? ): String { when (dayCardStatus) { DayCardStatusEnumAvro.OPEN -> submitDayCardForOpenStatus(name, taskName) DayCardStatusEnumAvro.NOTDONE -> submitDayCardsForNotDoneStatus(name, taskName, notDoneReason) DayCardStatusEnumAvro.DONE -> submitDayCardsForDoneStatus(name, taskName) DayCardStatusEnumAvro.APPROVED -> submitDayCardsForApprovedStatus(name, taskName) else -> error("Unknown day card event") } return name }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
8,238
bosch-pt-refinemysite-backend
Apache License 2.0
common/src/main/kotlin/com/veosps/game/event/EventBus.kt
veos-rs
454,076,880
false
{"Kotlin": 332503}
package com.veosps.game.event import com.veosps.game.event.action.EventAction import com.veosps.game.event.action.EventActionBuilder import com.veosps.game.util.BeanScope import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component import kotlin.reflect.KClass @Component @Scope(BeanScope.SCOPE_SINGLETON) class EventBus( val events: MutableMap<KClass<out Event>, MutableList<EventAction<*>>> = mutableMapOf() ) : Map<KClass<out Event>, List<EventAction<*>>> by events { @Suppress("UNCHECKED_CAST") inline fun <reified T : Event> publish(event: T): Boolean { val events = (events[event::class] as? List<EventAction<T>>) ?: return false val filtered = events.filter { it.where(event) } filtered.forEach { it.then(event) } return filtered.isNotEmpty() } inline fun <reified T : Event> subscribe(): EventActionBuilder<T> = EventActionBuilder(events.computeIfAbsent(T::class) { mutableListOf() }) }
0
Kotlin
0
0
5eb4bae27294af3a88b626e037bcb92e9e097f34
1,018
main-game
MIT License
app/src/main/java/liou/rayyuan/ebooksearchtaiwan/utils/Utils.kt
xaosbear
217,012,373
true
{"Kotlin": 166659, "Shell": 1776}
package liou.rayyuan.ebooksearchtaiwan.utils object Utils { @JvmStatic fun getDefaultSort(): List<DefaultStoreNames> { return listOf(DefaultStoreNames.READMOO, DefaultStoreNames.KOBO, DefaultStoreNames.BOOK_WALKER, DefaultStoreNames.BOOK_COMPANY, DefaultStoreNames.TAAZE, DefaultStoreNames.PLAY_STORE, DefaultStoreNames.PUBU, DefaultStoreNames.HYREAD) } }
0
Kotlin
0
0
9163ae72abd8c971bca15c5e2e040f93cf489a8f
490
TaiwanEbookSearch
MIT License
app/src/main/java/com/falcon/restaurants/domain/interactor/meal/FetchAndUpsertMealUseCase.kt
muhammed-ahmad
407,126,448
false
{"Kotlin": 133604}
package com.falcon.restaurants.domain.interactor.meal import com.falcon.restaurants.domain.model.Meal import com.falcon.restaurants.domain.repository.MealRepository import io.reactivex.Completable import javax.inject.Inject import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers class FetchAndUpsertMealUseCase @Inject constructor ( private val fetchMealsUseCase: FetchMealsUseCase, private val upsertMealsUseCase: UpsertMealsUseCase ) { fun execute(): Completable { return Completable.defer { fetchMealsUseCase.execute().flatMapCompletable { meals -> upsertMealsUseCase.execute(meals) } } } }
0
Kotlin
1
3
8796dcedbd5598b9e591ab702e6445e478ce4662
730
restaurants
MIT License
app/src/main/java/com/kpstv/vpn/ui/screens/Server.kt
reyadrahman
391,898,449
true
{"Java": 413767, "Kotlin": 126801, "AIDL": 15424, "Ruby": 1132}
package com.kpstv.vpn.ui.screens import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.coil.rememberCoilPainter import com.google.accompanist.insets.navigationBarsPadding import com.google.accompanist.insets.statusBarsPadding import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshIndicator import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.kpstv.vpn.R import com.kpstv.vpn.data.db.repository.VpnLoadState import com.kpstv.vpn.data.models.VpnConfiguration import com.kpstv.vpn.extensions.utils.FlagUtils import com.kpstv.vpn.ui.components.* import com.kpstv.vpn.ui.theme.CommonPreviewTheme import com.kpstv.vpn.ui.theme.dotColor import com.kpstv.vpn.ui.theme.goldenYellow @OptIn(ExperimentalAnimationApi::class) @Composable fun ServerScreen( vpnState: VpnLoadState, onBackButton: () -> Unit = {}, onRefresh: () -> Unit = {}, onImportButton: () -> Unit = {}, onPremiumClick: () -> Unit = {}, isPremiumUnlocked: Boolean = false, onItemClick: (VpnConfiguration) -> Unit ) { val swipeRefreshState = rememberSwipeRefreshState(vpnState is VpnLoadState.Loading) SwipeRefresh( modifier = Modifier .fillMaxSize(), state = swipeRefreshState, onRefresh = onRefresh, swipeEnabled = (vpnState is VpnLoadState.Completed), indicator = { state, trigger -> SwipeRefreshIndicator( state = state, refreshTriggerDistance = trigger + 20.dp, backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onSecondary, refreshingOffset = 80.dp ) } ) { val freeServerIndex = vpnState.configs.indexOfFirst { !it.premium } BoxWithConstraints(modifier = Modifier.fillMaxSize()) { LazyColumn( modifier = Modifier .padding(horizontal = 20.dp) ) { itemsIndexed(vpnState.configs) { index, item -> if (index == 0) { Spacer( modifier = Modifier .statusBarsPadding() .height(80.dp) ) ServerHeader(title = stringResource(R.string.premium_server), premium = true) Spacer(modifier = Modifier.height(15.dp)) } if (index == freeServerIndex) { Spacer(modifier = Modifier.height(15.dp)) ServerHeader(title = stringResource(R.string.free_server)) Spacer(modifier = Modifier.height(10.dp)) } CommonItem( config = item, isPremiumUnlocked = isPremiumUnlocked, onPremiumClick = onPremiumClick, onClick = onItemClick ) if (index == vpnState.configs.size - 1) { Spacer( modifier = Modifier .navigationBarsPadding() .height(80.dp) ) } } } Header(title = stringResource(R.string.choose_server), onBackButton = onBackButton) Footer( modifier = Modifier.align(Alignment.BottomCenter), onImportButton = onImportButton ) } } } @Composable private fun Footer(modifier: Modifier = Modifier, onImportButton: () -> Unit) { Column( modifier = modifier.then( Modifier .background(color = MaterialTheme.colors.background.copy(alpha = 0.93f)) .navigationBarsPadding() ) ) { Divider(color = MaterialTheme.colors.primaryVariant, thickness = 1.dp) Spacer(modifier = Modifier.height(10.dp)) ThemeButton( onClick = onImportButton, modifier = Modifier .padding(horizontal = 20.dp) .height(55.dp) .clip(RoundedCornerShape(10.dp)) .align(Alignment.CenterHorizontally), text = stringResource(R.string.import_open_vpn) ) Spacer(modifier = Modifier.height(10.dp)) } } @Composable private fun ServerHeader(title: String, premium: Boolean = false) { Row { Text( text = title, style = MaterialTheme.typography.h4.copy(fontSize = 20.sp), color = MaterialTheme.colors.onSecondary ) if (premium) { Spacer(modifier = Modifier.width(7.dp)) Image( painter = painterResource(R.drawable.ic_crown), modifier = Modifier.align(Alignment.CenterVertically), contentDescription = "Premium" ) } } } @Composable private fun CommonItem( config: VpnConfiguration, isPremiumUnlocked: Boolean, onPremiumClick: () -> Unit = {}, onClick: (VpnConfiguration) -> Unit = {} ) { Spacer(modifier = Modifier.height(5.dp)) Row( modifier = Modifier .border( width = 1.5.dp, color = if (config.premium) goldenYellow else dotColor.copy(alpha = 0.7f), shape = RoundedCornerShape(10.dp) ) .height(65.dp) .clickable( onClick = { if (config.premium && !isPremiumUnlocked) { onPremiumClick() } else { onClick.invoke(config) } }, ) .padding(5.dp) .fillMaxWidth() ) { if (config.countryFlagUrl.isNotEmpty()) { Image( painter = rememberCoilPainter( FlagUtils.getOrNull(config.country) ?: config.countryFlagUrl, fadeIn = true ), modifier = Modifier .padding(5.dp) .requiredWidthIn(max = 40.dp) .fillMaxHeight() .scale(1f), contentDescription = "Country flag", contentScale = ContentScale.Fit ) } else { Spacer(modifier = Modifier.width(50.dp)) } Spacer(modifier = Modifier.width(10.dp)) Column( modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) ) { Row(modifier = Modifier.fillMaxWidth()) { Text( text = config.country, style = MaterialTheme.typography.h4.copy(fontSize = 20.sp), overflow = TextOverflow.Ellipsis, maxLines = 1 ) Text( text = stringResource(R.string.server_ip, config.ip), modifier = Modifier .padding(start = 7.dp) .weight(1f) .align(Alignment.CenterVertically), style = MaterialTheme.typography.h5.copy(fontSize = 15.sp), color = MaterialTheme.colors.onSecondary ) } Spacer(modifier = Modifier.height(1.dp)) Text( text = stringResource( R.string.server_subtitle, config.sessions, config.upTime, config.speed ), style = MaterialTheme.typography.subtitle2, color = MaterialTheme.colors.onSurface, overflow = TextOverflow.Ellipsis, maxLines = 1, ) } } Spacer(modifier = Modifier.height(5.dp)) } @Preview(showBackground = true) @Composable fun PreviewServerScreen() { CommonPreviewTheme { ServerScreen(vpnState = VpnLoadState.Loading(), onItemClick = {}) } } @Preview(showBackground = true) @Composable fun PreviewCommonItem() { CommonPreviewTheme { CommonItem( config = createTestConfiguration(), isPremiumUnlocked = true ) } } @Preview(showBackground = true) @Composable fun PreviewCommonItemPremium() { CommonPreviewTheme { CommonItem( config = createTestConfiguration().copy(premium = true), isPremiumUnlocked = false ) } } private fun createTestConfiguration() = VpnConfiguration.createEmpty().copy( country = "United States", countryFlagUrl = "", ip = "192.168.1.1", sessions = "61 sessions", upTime = "89 days", speed = "73.24" )
0
null
0
0
d5d7779f6db8329f260e92a96258eaf69853309c
8,523
Gear-VPN
Apache License 2.0
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/transactions/mvp/TransactionsView.kt
willjgriff
79,726,997
false
null
package com.github.willjgriff.ethereumwallet.ui.screens.transactions.mvp import com.github.willjgriff.ethereumwallet.ethereum.transactions.model.DomainTransaction /** * Created by williamgriffiths on 11/04/2017. */ interface TransactionsView { fun addTransaction(transaction: DomainTransaction) fun clearTransactions() fun displayRangeDialog() }
0
Kotlin
1
12
3e8b894606df7fd5595078971ca0883cbf78badf
362
android-ethereum-wallet
Apache License 2.0
kradle-plugin/src/main/kotlin/net/bnb1/kradle/config/dsl/jvm/CheckstyleDsl.kt
mrkuz
400,078,467
false
{"Kotlin": 420504, "Java": 15648, "Smarty": 1822, "Shell": 695}
package net.bnb1.kradle.config.dsl.jvm import net.bnb1.kradle.blueprints.jvm.CheckstyleProperties import net.bnb1.kradle.dsl.Value class CheckstyleDsl(properties: CheckstyleProperties) { val version = Value(properties.version) { properties.version = it } val configFile = Value(properties.configFile) { properties.configFile = it } }
1
Kotlin
2
81
bb9969dd3d496119e2b0f47df453373d8b452d35
345
kradle
MIT License
src/test/kotlin/com/deffence1776/validationspec/samples/ComplexObjectValidationSample.kt
deffence1776
144,439,633
false
null
package com.deffence1776.validationspec.samples import com.deffence1776.validationspec.defineSpecs //Value Object With private field class UserId(private val value: String) { companion object { //public val. define spec at companion object to access private properties val spec = defineSpecs<UserId> { shouldBe("user id length rule") { value.length == 5 }.errorMessage { "user id's length should be 5" } } } } //Value Object With private field class UserName(private val value: String) { companion object { val spec = defineSpecs<UserName> { shouldBe("user name length rule") { value.length in 1..10 }.errorMessage { "username's length should be in 1..10" } } } } //Immutable Entity class User(private val userId: UserId, private val userName: UserName) { init{ //you can define assertion spec.assert(this) } companion object { //define spec for innerValue val spec = defineSpecs<User> { fieldNames("userId") { confirm({ userId }, UserId.spec ) } fieldNames("userName") { confirm({ userName }, UserName.spec) } } } //you can define validate method fun validate()=spec.validateAll(this) } fun main(args: Array<String>) { val user = User(UserId("abc"), UserName("12345678901")) val result = User.spec.validateAll(user) //or //val result = user.validate() println(result) }
0
Kotlin
0
0
ad0941ac042542007e420c799ea11c579c7238ba
1,530
kotlin-validationSpec
Apache License 2.0
atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt
input-output-hk
564,174,099
false
{"Kotlin": 533762, "Gherkin": 1987, "ANTLR": 1440, "JavaScript": 375}
package io.iohk.atala.prism.walletsdk.castor.did.prismdid import io.iohk.atala.prism.apollo.secp256k1.Secp256k1Lib import io.iohk.atala.prism.protos.CompressedECKeyData import io.iohk.atala.prism.protos.KeyUsage import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo import io.iohk.atala.prism.walletsdk.domain.models.CastorError import io.iohk.atala.prism.walletsdk.domain.models.Curve import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey import pbandk.ByteArr import kotlin.jvm.Throws class PrismDIDPublicKey { private val apollo: Apollo val id: String val usage: Usage val keyData: PublicKey constructor(apollo: Apollo, id: String, usage: Usage, keyData: PublicKey) { this.apollo = apollo this.id = id this.usage = usage this.keyData = keyData } @Throws(CastorError.InvalidPublicKeyEncoding::class) constructor(apollo: Apollo, proto: io.iohk.atala.prism.protos.PublicKey) { this.apollo = apollo this.id = proto.id this.usage = proto.usage.fromProto() this.keyData = when (proto.keyData) { is io.iohk.atala.prism.protos.PublicKey.KeyData.CompressedEcKeyData -> { Secp256k1PublicKey(proto.keyData.value.data.array) } else -> { throw CastorError.InvalidPublicKeyEncoding("prism", "secp256k1") } } } fun toProto(): io.iohk.atala.prism.protos.PublicKey { val compressedPublicKey = Secp256k1PublicKey(Secp256k1Lib().compressPublicKey(keyData.getValue())) return io.iohk.atala.prism.protos.PublicKey( id = id, usage = usage.toProto(), keyData = io.iohk.atala.prism.protos.PublicKey.KeyData.CompressedEcKeyData( compressedPublicKey.toProto() ) ) } enum class Usage(val value: String) { MASTER_KEY("masterKey"), ISSUING_KEY("issuingKey"), AUTHENTICATION_KEY("authenticationKey"), REVOCATION_KEY("revocationKey"), CAPABILITY_DELEGATION_KEY("capabilityDelegationKey"), CAPABILITY_INVOCATION_KEY("capabilityInvocationKey"), KEY_AGREEMENT_KEY("keyAgreementKey"), UNKNOWN_KEY("unknownKey") } } fun KeyUsage.fromProto(): PrismDIDPublicKey.Usage { return when (this) { is KeyUsage.MASTER_KEY -> PrismDIDPublicKey.Usage.MASTER_KEY is KeyUsage.ISSUING_KEY -> PrismDIDPublicKey.Usage.ISSUING_KEY is KeyUsage.AUTHENTICATION_KEY -> PrismDIDPublicKey.Usage.AUTHENTICATION_KEY is KeyUsage.REVOCATION_KEY -> PrismDIDPublicKey.Usage.REVOCATION_KEY is KeyUsage.CAPABILITY_DELEGATION_KEY -> PrismDIDPublicKey.Usage.CAPABILITY_DELEGATION_KEY is KeyUsage.CAPABILITY_INVOCATION_KEY -> PrismDIDPublicKey.Usage.CAPABILITY_INVOCATION_KEY is KeyUsage.KEY_AGREEMENT_KEY -> PrismDIDPublicKey.Usage.KEY_AGREEMENT_KEY is KeyUsage.UNKNOWN_KEY -> PrismDIDPublicKey.Usage.UNKNOWN_KEY is KeyUsage.UNRECOGNIZED -> PrismDIDPublicKey.Usage.UNKNOWN_KEY } } fun Secp256k1PublicKey.toProto(): CompressedECKeyData { return CompressedECKeyData( curve = Curve.SECP256K1.value, data = ByteArr(raw) ) } fun PrismDIDPublicKey.Usage.id(index: Int): String { return when (this) { PrismDIDPublicKey.Usage.MASTER_KEY -> "master$index" PrismDIDPublicKey.Usage.ISSUING_KEY -> "issuing$index" PrismDIDPublicKey.Usage.AUTHENTICATION_KEY -> "authentication$index" PrismDIDPublicKey.Usage.REVOCATION_KEY -> "revocation$index" PrismDIDPublicKey.Usage.CAPABILITY_DELEGATION_KEY -> "capabilityDelegation$index" PrismDIDPublicKey.Usage.CAPABILITY_INVOCATION_KEY -> "capabilityInvocation$index" PrismDIDPublicKey.Usage.KEY_AGREEMENT_KEY -> "keyAgreement$index" PrismDIDPublicKey.Usage.UNKNOWN_KEY -> "unknown$index" } } fun PrismDIDPublicKey.Usage.toProto(): KeyUsage { return when (this) { PrismDIDPublicKey.Usage.MASTER_KEY -> KeyUsage.MASTER_KEY PrismDIDPublicKey.Usage.ISSUING_KEY -> KeyUsage.ISSUING_KEY PrismDIDPublicKey.Usage.AUTHENTICATION_KEY -> KeyUsage.AUTHENTICATION_KEY PrismDIDPublicKey.Usage.REVOCATION_KEY -> KeyUsage.REVOCATION_KEY PrismDIDPublicKey.Usage.CAPABILITY_DELEGATION_KEY -> KeyUsage.CAPABILITY_DELEGATION_KEY PrismDIDPublicKey.Usage.CAPABILITY_INVOCATION_KEY -> KeyUsage.CAPABILITY_INVOCATION_KEY PrismDIDPublicKey.Usage.KEY_AGREEMENT_KEY -> KeyUsage.KEY_AGREEMENT_KEY PrismDIDPublicKey.Usage.UNKNOWN_KEY -> KeyUsage.UNKNOWN_KEY } } fun PrismDIDPublicKey.Usage.defaultId(): String { return this.id(0) }
2
Kotlin
0
5
c7cf22e2b564761ca796f94aba4a5a274d5e9803
4,787
atala-prism-wallet-sdk-kmm
Apache License 2.0
app/src/main/java/ar/com/wolox/android/training/ui/example/ExamplePresenter.kt
wolox-training
197,457,700
false
null
package ar.com.wolox.android.training.ui.example import ar.com.wolox.android.training.utils.UserSession import ar.com.wolox.wolmo.core.presenter.BasePresenter import javax.inject.Inject class ExamplePresenter @Inject constructor(private val mUserSession: UserSession) : BasePresenter<IExampleView>() { fun storeUsername(text: String) { mUserSession.username = text view.onUsernameSaved() } }
1
Kotlin
0
0
87b68ca28cb785da86a4c3843a477dbd1e988a2a
420
fs-android
MIT License
links/src/commonMain/kotlin/handler/LinksHandler.kt
splendo
191,371,940
false
{"Kotlin": 6494822, "Swift": 172024, "Shell": 1514}
/* Copyright 2023 Splendo Consulting B.V. The Netherlands 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.splendo.kaluga.links.handler /** * Handler for processing a link */ interface LinksHandler { /** * Checks if a url string is valid * @param url the url string to validate * @return `true` if the url is valid, false otherwise */ fun isValid(url: String): Boolean /** * Processes the query parameters of a url string into a list * @param url the url string to extract the query parameters from * @return a list containing the values of all query parameters of the [url] */ fun extractQueryAsList(url: String): List<Any> }
87
Kotlin
7
315
4094d5625a4cacb851b313d4e96bce6faac1c81f
1,217
kaluga
Apache License 2.0
core/model/src/main/java/org/hxl/model/Character.kt
hexley21
657,343,982
false
null
package org.hxl.model data class Character( val id: Int, val name: String, val gender: String, val starships: Int, var isFavorite: Boolean = false, var filmInfo: FilmInfo = FilmInfo() )
1
Kotlin
0
0
44941d167e70d5bc28a5fcd15be4bd99f250df5e
210
ForceFacts
Apache License 2.0
fuzzer/fuzzing_output/crashing_tests/verified/kt12200.kt457108330.kt
ItsLastDay
102,885,402
false
null
class ThingTemplate { val prop = 0 } class ThingVal(template: ThingTemplate) { val prop = template.prop } class ThingVar(template: ThingTemplate) { var prop = template.prop } fun box(): String { val template = ThingTemplate() val javaClass = (ThingTemplate)?::class.java val field = javaClass.ThingTemplate("prop")!! field.isAccessible = true field.set(template, 1) val thingVal = ThingVal(template) if (thingVal.prop != 1) { return "fail 1" } val thingVar = ThingVar(template) if (thingVar.prop != 1) { return "fail 2" } return "OK" }
2
Kotlin
1
6
56f50fc307709443bb0c53972d0c239e709ce8f2
544
KotlinFuzzer
MIT License
app/src/main/java/com/ali_sajjadi/daneshjooyarapp/mvp/model/ModelMainActivity.kt
alisajjadi751
847,226,122
false
{"Kotlin": 72156}
package com.ali_sajjadi.daneshjooyarapp.mvp.model class ModelMainActivity { }
0
Kotlin
0
0
039cbfa4fb82af9d1b5b94f5ddba018d8caacce3
79
daneshjooyar-App
MIT License
src/main/kotlin/com/soblemprolved/interfaceofourown/model/Bookmark.kt
soblemprolved
385,327,834
false
null
package com.soblemprolved.interfaceofourown.model import java.time.LocalDate data class Bookmark( /** * User associated with the bookmark */ val userReference: UserReference, /** * List of tags associated with the bookmark */ val tags: List<String>, /** * List of collections which the bookmark was added to. */ val collections: List<CollectionReference>, /** * Time at which the bookmark was created. */ val date: LocalDate, /** * Bookmarker's notes in raw HTML. */ val notes: Html, /** * Type of the bookmark. */ val bookmarkType: BookmarkType )
2
Kotlin
0
1
9f0bce62b1b6e0e09daab7904fe2502901d857e9
664
InterfaceOfOurOwn
MIT License
app/src/main/java/com/jiangkang/ktools/ImageActivity.kt
jiangkang
102,488,439
false
null
package com.jiangkang.ktools import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.text.TextUtils import android.view.View import android.webkit.MimeTypeMap import android.widget.EditText import android.widget.VideoView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.jiangkang.hybrid.Khybrid import com.jiangkang.tools.utils.FileUtils import com.jiangkang.tools.utils.ImageUtils import com.jiangkang.tools.utils.LogUtils import com.jiangkang.tools.utils.ToastUtils import com.jiangkang.tools.widget.KDialog import kotlinx.android.synthetic.main.activity_image.* import java.io.File import java.io.IOException class ImageActivity : AppCompatActivity() { private val etMaxWidth: EditText by lazy { findViewById<EditText>(R.id.et_max_width) } private val etMaxHeight: EditText by lazy { findViewById<EditText>(R.id.et_max_height) } private var outputImageFile: File? = null private var outputVideoFile: File? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image) title = "Image" btn_choose_picture_from_album.setOnClickListener { openAlbum() } btn_take_picture.setOnClickListener { onBtnTakePictureClicked() } btn_take_video.setOnClickListener { onBtnTakeVideoClicked() } btn_screen_capture.setOnClickListener { onBtnScreenCaptureClicked() } btn_take_picture_without_compress.setOnClickListener { onBtnTakePictureWithoutCompressClicked() } btn_show_base64_img_in_web.setOnClickListener { onBtnShowBase64ImgInWebClicked() } btn_scale_image_by_max_width_and_height.setOnClickListener { onBtnScaleImageByMaxWidthAndHeightClicked() } btnPrintBitmap.setOnClickListener { onBtnPrintBitmapClicked() } } private fun openAlbum() { val albumIntent = Intent(Intent.ACTION_PICK) albumIntent.type = "image/*" startActivityForResult(albumIntent, REQUEST_OPEN_ALBUM) } override fun onDestroy() { super.onDestroy() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQUEST_OPEN_ALBUM -> if (resultCode == Activity.RESULT_OK) { handleAlbumData(data) } REQUEST_IMAGE_CAPTURE -> if (resultCode == Activity.RESULT_OK) { handleImageCaptureData(data) } REQUEST_CODE_CAPTURE_IMAGE_WITHOUT_COMPRESS -> if (resultCode == Activity.RESULT_OK) { handleImageCaptureWithoutCompress(data) } REQUEST_CODE_TAKE_VIDEO -> if (resultCode == Activity.RESULT_OK) { handleVideoData(data) } else -> { } } } private fun handleVideoData(data: Intent?) { showVideoInDialog(outputVideoFile) } private fun showVideoInDialog(file: File?) { val videoView = VideoView(this) videoView.setVideoPath(file!!.absolutePath) val dialog = AlertDialog.Builder(this) .setView(videoView) .setPositiveButton("播放", null) .setNeutralButton("暂停", null) .setNegativeButton("关闭") { dialog, which -> dialog.dismiss() } .setCancelable(false) .show() dialog.getButton(AlertDialog.BUTTON_POSITIVE) .setOnClickListener { videoView.start() } dialog.getButton(AlertDialog.BUTTON_NEUTRAL) .setOnClickListener { videoView.pause() } } private fun handleImageCaptureWithoutCompress(data: Intent?) { val bitmap = BitmapFactory.decodeFile(outputImageFile!!.absolutePath) //让媒体扫描器扫描 galleryAddPic(outputImageFile) KDialog.showImgInDialog(this, bitmap) } private fun galleryAddPic(file: File?) { val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) val imgUri = Uri.fromFile(file) mediaScanIntent.data = imgUri this.sendBroadcast(mediaScanIntent) } private fun handleImageCaptureData(data: Intent?) { //这张图是thumbnail,清晰度低,当做Icon还可以,但是作为图片显示并不合适 val bitmap = data!!.extras!!["data"] as Bitmap? KDialog.showImgInDialog(this, bitmap) } private fun handleAlbumData(data: Intent?) { val uri = data!!.data val projection = arrayOf( MediaStore.Images.Media.DATA ) val cursor = contentResolver.query( uri!!, projection, null, null, null ) if (cursor != null && cursor.moveToFirst()) { val dataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA) val imagePath = cursor.getString(dataIndex) cursor.close() showBitmap(imagePath) } } private fun showBitmap(imagePath: String) { ToastUtils.showShortToast(imagePath) val bitmap = BitmapFactory.decodeFile(imagePath) KDialog.showImgInDialog(this, bitmap) } private fun onBtnTakePictureClicked() { if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){ openCamera() } else { requestPermissions(arrayOf(Manifest.permission.CAMERA),1111) } } private fun openCamera() { val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) //返回第一个可以处理该Intent的组件 if (cameraIntent.resolveActivity(packageManager) != null) { startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE) } } private fun onBtnTakeVideoClicked() { if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){ takeVideo() } else { requestPermissions(arrayOf(Manifest.permission.CAMERA),1111) } } private fun takeVideo() { val dirVideo = File(Environment.getExternalStorageDirectory(), "ktools/videos/") if (!dirVideo.exists()) { dirVideo.mkdirs() } outputVideoFile = File(dirVideo.absolutePath + System.currentTimeMillis() + ".mp4") if (!outputVideoFile!!.exists()) { try { outputVideoFile!!.createNewFile() } catch (e: IOException) { e.printStackTrace() } } //兼容7.0 val videoUri = FileProvider.getUriForFile( this, BuildConfig.APPLICATION_ID, outputVideoFile!! ) val intent = Intent(MediaStore.ACTION_VIDEO_CAPTURE) //指定输出 intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri) intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1) intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 3000) startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO) } private fun onBtnScreenCaptureClicked() { val decorView = window.decorView decorView.isDrawingCacheEnabled = true decorView.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH decorView.buildDrawingCache() val screen = Bitmap.createBitmap(decorView.drawingCache) KDialog.showImgInDialog(this, screen) } private fun onBtnTakePictureWithoutCompressClicked() { if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){ openCameraWithOutput() } else { requestPermissions(arrayOf(Manifest.permission.CAMERA),1111) } } private fun openCameraWithOutput() { val path = File(Environment.getExternalStorageDirectory(), "ktools").absolutePath if (!File(path).exists()) { File(path).mkdirs() } outputImageFile = File(path, System.currentTimeMillis().toString() + ".png") if (!outputImageFile!!.exists()) { try { outputImageFile!!.createNewFile() } catch (e: IOException) { e.printStackTrace() } } //兼容7.0 val contentUri = FileProvider.getUriForFile( this, BuildConfig.APPLICATION_ID, outputImageFile!! ) LogUtils.d(TAG, "openCameraWithOutput: uri = $contentUri") val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) intent.putExtra(Intent.EXTRA_MIME_TYPES, MimeTypeMap.getSingleton().getMimeTypeFromExtension("png")) //指定输出路径 intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri) if (intent.resolveActivity(packageManager) != null) { startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE_WITHOUT_COMPRESS) } } private fun onBtnShowBase64ImgInWebClicked() { Khybrid().loadUrl(this, FileUtils.getAssetsPath("web/demo_img.html")) } private fun onBtnScaleImageByMaxWidthAndHeightClicked() { val srcBitmap = BitmapFactory.decodeResource(this.resources, R.drawable.demo) var maxWidth = srcBitmap.width var maxHeight = srcBitmap.height if (!TextUtils.isEmpty(etMaxWidth!!.text.toString()) && TextUtils.isDigitsOnly(etMaxWidth!!.text.toString())) { maxWidth = etMaxWidth!!.text.toString().toInt() } if (!TextUtils.isEmpty(etMaxHeight!!.text.toString()) && TextUtils.isDigitsOnly(etMaxHeight!!.text.toString())) { maxHeight = etMaxHeight!!.text.toString().toInt() } val scaledBitmap = ImageUtils.scaleBitmap(srcBitmap, maxWidth, maxHeight) if (scaledBitmap != null) { KDialog.showImgInDialog(this, scaledBitmap) } } private fun onBtnPrintBitmapClicked() { val bitmap = BitmapFactory.decodeResource(resources, R.drawable.demo) ImageUtils.printBitmap(this, bitmap) } companion object { private val TAG = ImageActivity::class.java.simpleName private const val REQUEST_OPEN_ALBUM = 1000 private const val REQUEST_IMAGE_CAPTURE = 1001 private const val REQUEST_CODE_CAPTURE_IMAGE_WITHOUT_COMPRESS = 1002 private const val REQUEST_CODE_TAKE_VIDEO = 1003 } }
0
null
63
160
e1d6cb6fb3d848f5a9d7a27dd77ef403789bfbe5
10,792
KTools
MIT License
app/src/main/java/ua/tiar/aim/ui/components/ShadowIcon.kt
Tiarait
852,875,140
false
{"Kotlin": 384314}
package ua.tiar.aim.ui.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.blur import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun ShadowIcon( modifier: Modifier = Modifier, imageVector: ImageVector, tint: Color = MaterialTheme.colorScheme.onPrimary, contentDescription: String? = null, blur: Dp = 3.dp ) { Box(modifier) { Icon( modifier = Modifier.fillMaxSize() .padding(top = 1.dp, start = 1.dp) .offset(x = 1.dp, y = 1.dp) .blur(blur), imageVector = imageVector, tint = Color.Black, contentDescription = contentDescription + "Shadow" ) Icon( modifier = Modifier.fillMaxSize(), imageVector = imageVector, tint = tint, contentDescription = contentDescription ) } }
0
Kotlin
1
1
90a71e5510b3ce49c70ce43f85ff6aaebbf32adf
1,359
AI-MUSE
Apache License 2.0
src/main/kotlin/com/asymptotik/web/SecurityConfiguration.kt
asymptotik
187,926,131
false
null
package com.asymptotik.web import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.web.csrf.CookieCsrfTokenRepository @Configuration @EnableOAuth2Sso @EnableWebSecurity open class SecurityConfiguration : WebSecurityConfigurerAdapter() { /* @Throws(Exception::class) override fun configure(auth: AuthenticationManagerBuilder?) { } */ @Throws(Exception::class) override fun configure(http: HttpSecurity) { http .antMatcher("/**") .authorizeRequests() .antMatchers("/", "/index**", "/login**", "/webjars/**", "/error**") .permitAll() .anyRequest() .authenticated() .and().logout().logoutSuccessUrl("/").permitAll() .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) } }
0
Kotlin
0
0
2f7d566639e244e54ff91b8c461700db1b855b12
1,343
spring_boot_mvc_starter
MIT License
androidApp/src/main/java/com/aglushkov/wordteacher/androidApp/features/add_article/di/AddArticleModule.kt
soniccat
302,971,014
false
null
package com.aglushkov.wordteacher.di import com.aglushkov.wordteacher.androidApp.di.FragmentComp import com.aglushkov.wordteacher.shared.features.add_article.vm.AddArticleVM import com.aglushkov.wordteacher.shared.features.add_article.vm.AddArticleVMImpl import com.aglushkov.wordteacher.shared.general.TimeSource import com.aglushkov.wordteacher.shared.repository.article.ArticlesRepository import dagger.Module import dagger.Provides @Module class AddArticleModule { @FragmentComp @Provides fun viewModel( articlesRepository: ArticlesRepository, timeSource: TimeSource, state: AddArticleVM.State ): AddArticleVM { return AddArticleVMImpl(articlesRepository, timeSource, state) } }
0
Kotlin
1
1
1defa8e2973da24f0f313e70c1f5a19595c53e5a
737
WordTeacher
MIT License
app/src/main/java/com/smlnskgmail/jaman/randomnotes/components/dialogs/invite/InviteDialog.kt
ketanpatel25
213,889,548
true
{"Kotlin": 39674, "Java": 10825}
package com.smlnskgmail.jaman.randomnotes.components.dialogs.invite import android.content.Context import com.parse.FunctionCallback import com.parse.ParseCloud import com.smlnskgmail.jaman.randomnotes.R import com.smlnskgmail.jaman.randomnotes.components.dialogs.BaseDialog import kotlinx.android.synthetic.main.dialog_invite.* class InviteDialog(context: Context) : BaseDialog(context) { private var inviteCallback: InviteCallback? = null override fun initializeDialog() { dialog_invite_cancel.setOnClickListener { cancel() } dialog_invite_request.setOnClickListener { cancel() share() } dialog_invite_email.requestFocus() } private fun share() { val inviteData = hashMapOf<String, String>() inviteData["email"] = dialog_invite_email.text.toString() ParseCloud.callFunctionInBackground("invite", inviteData, FunctionCallback<Boolean> { success, e -> inviteCallback?.onInviteAction(success) } ) } fun setInviteCallback(inviteCallback: InviteCallback) { this.inviteCallback = inviteCallback } override fun getLayoutResId() = R.layout.dialog_invite }
0
null
0
0
c7b5987efc6ac320fd7c01821ffef5adcf7951f1
1,245
parse-android-test-app
The Unlicense
app/src/main/java/com/playlab/escaperoomtimer/ui/theme/Shape.kt
joaoplay16
568,274,757
false
null
package com.playlab.escaperoomtimer.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(6.dp), medium = RoundedCornerShape(15.dp), large = RoundedCornerShape(25.dp) )
0
Kotlin
2
9
881bc8824e170ff105570f0bce71c8ac57f72da6
320
escape-room-timer
Apache License 2.0
app/src/main/java/de/rauschdo/eschistory/ui/dialog/Dialogs.kt
rauschdo
739,847,191
false
{"Kotlin": 97755}
package de.rauschdo.eschistory.ui.dialog import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import de.rauschdo.eschistory.data.DialogModel import de.rauschdo.eschistory.ui.main.BaseButton import de.rauschdo.eschistory.ui.main.BaseHeader import de.rauschdo.eschistory.ui.main.BaseOutlinedButton import de.rauschdo.eschistory.ui.main.BaseText import de.rauschdo.eschistory.ui.theme.TypeDefinition import de.rauschdo.eschistory.ui.theme.baseCornerShape import de.rauschdo.eschistory.ui.theme.defaultButtonHeight import de.rauschdo.eschistory.ui.theme.heigherOf import de.rauschdo.eschistory.utility.loremIpsum /** * Centralized object to funnel through constructions/variants of Dialogs to display */ object Dialogs { fun sample(onDismissRequest: () -> Unit) = DialogModel( id = "sample", content = { BaseDialogAnimated(onDismissRequest = onDismissRequest) { dialogTransitionHelper -> val dismissClick = { dialogTransitionHelper?.triggerAnimatedDismiss( toExecute = onDismissRequest ) ?: onDismissRequest } Card(shape = baseCornerShape) { Column(modifier = Modifier) { BaseHeader( title = { BaseText( text = loremIpsum(), style = TypeDefinition.titleMedium ) }, actions = { IconButton(onClick = onDismissRequest) { Icon( imageVector = Icons.Filled.Close, contentDescription = "Close" ) } } ) Column( modifier = Modifier .verticalScroll(rememberScrollState()) .weight(weight = 1f, fill = false) ) { val localDensity = LocalDensity.current // Sample scaling buttons (e.g through font/display scaling) var negativeButtonHeight: Dp? by remember { mutableStateOf(null) } var positiveButtonHeight: Dp? by remember { mutableStateOf(null) } var preferedButtonHeight: Dp? by remember { mutableStateOf(null) } preferedButtonHeight = heigherOf( heigh1 = negativeButtonHeight, heigh2 = positiveButtonHeight, fallbackHeight = defaultButtonHeight ) var negativeButtonModifier = Modifier .weight(1f) .onGloballyPositioned { coordinates -> negativeButtonHeight = with(localDensity) { coordinates.size.height.toDp() } } preferedButtonHeight?.let { negativeButtonModifier = negativeButtonModifier.defaultMinSize(minHeight = it) } var positiveButtonModifier = Modifier .weight(1f) .onGloballyPositioned { coordinates -> positiveButtonHeight = with(localDensity) { coordinates.size.height.toDp() } } preferedButtonHeight?.let { positiveButtonModifier = positiveButtonModifier.defaultMinSize(minHeight = it) } BaseText(text = loremIpsum(20), style = TypeDefinition.bodyMedium) Row(modifier = Modifier.padding(top = 16.dp)) { BaseOutlinedButton( modifier = negativeButtonModifier, text = loremIpsum(), onClick = { dismissClick() } ) BaseButton( modifier = positiveButtonModifier, text = loremIpsum(5), onClick = { dismissClick() } ) } } } } } } ) }
0
Kotlin
0
0
5422f0111755d82f3d50e83b885d98f010fe9e33
5,862
ESC-History
MIT License
app/src/main/java/com/kaiwolfram/nozzle/ui/theme/Type.kt
kaiwolfram
559,341,150
false
null
package com.kaiwolfram.nozzle.ui.theme import androidx.compose.material.Typography val Typography = Typography()
0
Kotlin
4
45
fb9213f0f5ed69d5fc8246fa0ba2dc6fa26bf559
115
Nozzle
MIT License
ledger/src/main/kotlin/org/knowledger/ledger/storage/transaction/SUTransactionStorageAdapter.kt
fakecoinbase
282,563,487
false
null
package org.knowledger.ledger.storage.transaction import org.knowledger.ledger.crypto.EncodedPublicKey import org.knowledger.ledger.crypto.Hash import org.knowledger.ledger.crypto.toPublicKey import org.knowledger.ledger.data.adapters.PhysicalDataStorageAdapter import org.knowledger.ledger.database.ManagedSession import org.knowledger.ledger.database.StorageElement import org.knowledger.ledger.database.StorageType import org.knowledger.ledger.results.Outcome import org.knowledger.ledger.results.mapSuccess import org.knowledger.ledger.results.tryOrLoadUnknownFailure import org.knowledger.ledger.service.results.LoadFailure import org.knowledger.ledger.storage.adapters.LedgerStorageAdapter import java.security.PublicKey internal class SUTransactionStorageAdapter( private val physicalDataStorageAdapter: PhysicalDataStorageAdapter ) : LedgerStorageAdapter<HashedTransactionImpl> { override val id: String get() = "Transaction" override val properties: Map<String, StorageType> get() = mapOf( "publicKey" to StorageType.BYTES, "data" to StorageType.LINK, "signature" to StorageType.LINK, "hash" to StorageType.HASH, "index" to StorageType.INTEGER ) override fun store( toStore: HashedTransactionImpl, session: ManagedSession ): StorageElement = session .newInstance(id) .setStorageProperty( "publicKey", toStore.publicKey.encoded ).setLinked( "data", physicalDataStorageAdapter.persist( toStore.data, session ) ).setStorageBytes( "signature", session.newInstance( toStore.signature.bytes ) ).setHashProperty("hash", toStore.hash) .setStorageProperty("index", toStore.index) override fun load( ledgerHash: Hash, element: StorageElement ): Outcome<HashedTransactionImpl, LoadFailure> = tryOrLoadUnknownFailure { val physicalData = element.getLinked("data") physicalDataStorageAdapter.load( ledgerHash, physicalData ).mapSuccess { data -> val publicKey: PublicKey = EncodedPublicKey( element.getStorageProperty("publicKey") ).toPublicKey() val signature = element.getStorageBytes("signature").bytes val hash = element.getHashProperty("hash") val index = element.getStorageProperty<Int>("index") HashedTransactionImpl( publicKey = publicKey, data = data, signature = signature, hash = hash, index = index ) } } }
0
Kotlin
0
0
8bc64987e1ab4d26663064da06393de6befc30ae
2,932
SeriyinslashKnowLedger
MIT License
compiler/testData/codegen/box/fir/delegatedAndDataTogether.kt
JetBrains
3,432,266
false
null
// TARGET_BACKEND: JVM_IR // ISSUE: KT-58926 fun box(): String { val i1 = Impl() val i2 = Impl() val d1 = Data(i1, 1) val d2 = Data(i2, 2) return if (d1 != d2) "FAIL: should be equal" else "OK" } interface AnyNeighbor { override fun equals(other: Any?): Boolean } class Impl : AnyNeighbor { override fun equals(other: Any?): Boolean = true } data class Data(val i: Impl, val j: Int) : AnyNeighbor by i
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
434
kotlin
Apache License 2.0
client/src/main/kotlin/tech/figure/classification/asset/client/domain/execute/UpdateAssetVerifierExecute.kt
FigureTechnologies
490,476,548
false
{"Kotlin": 464227}
package tech.figure.classification.asset.client.domain.execute import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeName import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming import tech.figure.classification.asset.client.domain.execute.base.ContractExecute import tech.figure.classification.asset.client.domain.model.VerifierDetail /** * This class is a reflection of the request body used in the Asset Classification smart contract's update asset * verifier execution route. * * Request usage: * ```kotlin * val execute = UpdateAssetVerifierExecute(assetType, verifier) * val txResponse = acClient.updateAssetVerifier(execute, signer, options) * ``` * * @param assetType The type of asset definition that this verifier belongs to. * @param verifier The verifier definition that will be update. This value will be used in an attempt to find an * existing verifier on the asset definition that matches the verifier's address field. */ @JsonNaming(SnakeCaseStrategy::class) @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) @JsonTypeName("update_asset_verifier") data class UpdateAssetVerifierExecute(val assetType: String, val verifier: VerifierDetail) : ContractExecute
12
Kotlin
0
0
d0eb720d750dc1ece826afab1d461f3b6d40a423
1,356
asset-classification-libs
Apache License 2.0
src/test/kotlin/no/nav/syfo/mocks/PdlMock.kt
navikt
651,411,879
false
{"Kotlin": 180296, "Dockerfile": 202}
package no.nav.syfo.mocks import io.ktor.client.engine.mock.* import io.ktor.client.request.* import io.ktor.http.* import no.nav.syfo.client.pdl.* import no.nav.syfo.testhelper.UserConstants private val PdlResponse = PipPersondataResponse( person = PipPerson( adressebeskyttelse = listOf( PipAdressebeskyttelse( gradering = Gradering.UGRADERT ) ), doedsfall = emptyList(), ), geografiskTilknytning = PipGeografiskTilknytning( gtType = PdlGeografiskTilknytningType.KOMMUNE.name, gtBydel = null, gtKommune = "0301", gtLand = null, ), identer = PipIdenter(emptyList()), ) private val gradertPdlResponse = PipPersondataResponse( person = PipPerson( adressebeskyttelse = listOf( PipAdressebeskyttelse( gradering = Gradering.STRENGT_FORTROLIG, ) ), doedsfall = emptyList(), ), geografiskTilknytning = PipGeografiskTilknytning( gtType = PdlGeografiskTilknytningType.KOMMUNE.name, gtBydel = null, gtKommune = "0301", gtLand = null, ), identer = PipIdenter(emptyList()), ) fun MockRequestHandleScope.getPdlResponse(request: HttpRequestData): HttpResponseData { val personident = request.headers[PdlClient.IDENT_HEADER] return when (personident) { UserConstants.PERSONIDENT_GRADERT -> { respond( content = mapper.writeValueAsString(gradertPdlResponse), status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, "application/json") ) } else -> { respond( content = mapper.writeValueAsString(PdlResponse), status = HttpStatusCode.OK, headers = headersOf(HttpHeaders.ContentType, "application/json") ) } } }
2
Kotlin
0
0
efe8e41bfe3b8fb36498c5997bf0655c5dab7c6f
1,936
istilgangskontroll
MIT License
apps/etterlatte-beregning/src/test/kotlin/avkorting/AvkortingServiceTest.kt
navikt
417,041,535
false
null
package avkorting import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import kotlinx.coroutines.runBlocking import no.nav.etterlatte.avkorting.Avkorting import no.nav.etterlatte.avkorting.AvkortingGrunnlag import no.nav.etterlatte.avkorting.AvkortingRepository import no.nav.etterlatte.avkorting.AvkortingService import no.nav.etterlatte.beregning.Beregning import no.nav.etterlatte.beregning.BeregningService import no.nav.etterlatte.beregning.regler.avkorting import no.nav.etterlatte.beregning.regler.avkortinggrunnlag import no.nav.etterlatte.beregning.regler.behandling import no.nav.etterlatte.beregning.regler.bruker import no.nav.etterlatte.klienter.BehandlingKlient import no.nav.etterlatte.libs.common.behandling.BehandlingType import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.time.YearMonth import java.util.* internal class AvkortingServiceTest { private val behandlingKlient: BehandlingKlient = mockk() private val avkortingRepository: AvkortingRepository = mockk() private val beregningService: BeregningService = mockk() private val service = AvkortingService( behandlingKlient, avkortingRepository, beregningService ) @BeforeEach fun beforeEach() { clearAllMocks() coEvery { behandlingKlient.avkort(any(), any(), any()) } returns true } @AfterEach fun afterEach() { confirmVerified() } @Nested inner class HentAvkorting { @Test fun `Skal hente avkorting`() { val behandlingId = UUID.randomUUID() val avkorting = avkorting() every { avkortingRepository.hentAvkorting(behandlingId) } returns avkorting runBlocking { service.hentAvkorting(behandlingId, bruker) shouldBe avkorting } coVerify { avkortingRepository.hentAvkorting(behandlingId) } } @Test fun `Skal returnere null hvis avkorting ikke finnes`() { val behandlingId = UUID.randomUUID() every { avkortingRepository.hentAvkorting(behandlingId) } returns null val behandling = behandling(behandlingType = BehandlingType.FØRSTEGANGSBEHANDLING) coEvery { behandlingKlient.hentBehandling(behandlingId, bruker) } returns behandling runBlocking { service.hentAvkorting(behandlingId, bruker) shouldBe null } coVerify { avkortingRepository.hentAvkorting(behandlingId) behandlingKlient.hentBehandling(behandlingId, bruker) behandling.behandlingType } } @Test fun `Revurdering skal opprette ny avkorting ved aa kopiere tidligere hvis avkorting ikke finnes fra foer`() { val behandlingId = UUID.randomUUID() val behandling = behandling( behandlingType = BehandlingType.REVURDERING, sak = 123L, virkningstidspunkt = YearMonth.of(2023, 1) ) val forrigeBehandlingId = UUID.randomUUID() val forrigeAvkorting = mockk<Avkorting>() val kopiertAvkorting = mockk<Avkorting>() val beregning = mockk<Beregning>() val beregnetAvkorting = mockk<Avkorting>() val lagretAvkorting = mockk<Avkorting>() every { avkortingRepository.hentAvkorting(behandlingId) } returns null coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { behandlingKlient.hentSisteIverksatteBehandling(any(), any()) } returns forrigeBehandlingId every { avkortingRepository.hentAvkorting(forrigeBehandlingId) } returns forrigeAvkorting every { forrigeAvkorting.kopierAvkorting() } returns kopiertAvkorting every { beregningService.hentBeregningNonnull(any()) } returns beregning every { kopiertAvkorting.beregnAvkorting(any(), any(), any()) } returns beregnetAvkorting every { avkortingRepository.lagreAvkorting(any(), any()) } returns lagretAvkorting coEvery { behandlingKlient.avkort(any(), any(), any()) } returns true runBlocking { service.hentAvkorting(behandlingId, bruker) } coVerify { avkortingRepository.hentAvkorting(behandlingId) behandlingKlient.hentBehandling(behandlingId, bruker) behandlingKlient.hentSisteIverksatteBehandling(behandling.sak, bruker) avkortingRepository.hentAvkorting(forrigeBehandlingId) forrigeAvkorting.kopierAvkorting() beregningService.hentBeregningNonnull(behandlingId) kopiertAvkorting.beregnAvkorting( behandling.behandlingType, behandling.virkningstidspunkt!!.dato, beregning ) avkortingRepository.lagreAvkorting(behandlingId, beregnetAvkorting) behandlingKlient.avkort(behandlingId, bruker, true) } } } @Nested inner class LagreAvkorting { @Test fun `Foerstegangsbehandling skal opprette og beregne ny avkorting hvis ikke finnes fra foer`() { val behandlingId = UUID.randomUUID() val virkningsdato = YearMonth.of(2023, 1) val behandling = behandling( behandlingType = BehandlingType.FØRSTEGANGSBEHANDLING, virkningstidspunkt = virkningsdato ) val nyttGrunnlag = mockk<AvkortingGrunnlag>() val beregning = mockk<Beregning>() val nyAvkorting = mockk<Avkorting>() val beregnetAvkorting = mockk<Avkorting>() val lagretAvkorting = mockk<Avkorting>() every { avkortingRepository.hentAvkorting(any()) } returns null mockkObject(Avkorting.Companion) every { Avkorting.Companion.nyAvkorting() } returns nyAvkorting coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling every { beregningService.hentBeregningNonnull(any()) } returns beregning every { nyAvkorting.beregnAvkortingMedNyttGrunnlag(any(), any(), any(), any()) } returns beregnetAvkorting every { avkortingRepository.lagreAvkorting(any(), any()) } returns lagretAvkorting coEvery { behandlingKlient.avkort(any(), any(), any()) } returns true runBlocking { service.lagreAvkorting(behandlingId, bruker, nyttGrunnlag) shouldBe lagretAvkorting } coVerify(exactly = 1) { behandlingKlient.avkort(behandlingId, bruker, false) avkortingRepository.hentAvkorting(behandlingId) Avkorting.nyAvkorting() behandlingKlient.hentBehandling(behandlingId, bruker) beregningService.hentBeregningNonnull(behandlingId) nyAvkorting.beregnAvkortingMedNyttGrunnlag( nyttGrunnlag, behandling.behandlingType, virkningsdato, beregning ) avkortingRepository.lagreAvkorting(behandlingId, beregnetAvkorting) behandlingKlient.avkort(behandlingId, bruker, true) } } @Test fun `Revurdering skal for eksisterende avkorting skal reberegne og lagre avkorting`() { val behandlingId = UUID.randomUUID() val virkningsdato = YearMonth.of(2023, 1) val behandling = behandling(behandlingType = BehandlingType.REVURDERING, virkningstidspunkt = virkningsdato) val endretGrunnlag = mockk<AvkortingGrunnlag>() val beregning = mockk<Beregning>() val eksisterendeAvkorting = mockk<Avkorting>() val beregnetAvkorting = mockk<Avkorting>() val lagretAvkorting = mockk<Avkorting>() every { avkortingRepository.hentAvkorting(any()) } returns eksisterendeAvkorting coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling every { beregningService.hentBeregningNonnull(any()) } returns beregning every { eksisterendeAvkorting.beregnAvkortingMedNyttGrunnlag(any(), any(), any(), any()) } returns beregnetAvkorting every { avkortingRepository.lagreAvkorting(any(), any()) } returns lagretAvkorting coEvery { behandlingKlient.avkort(any(), any(), any()) } returns true runBlocking { service.lagreAvkorting(behandlingId, bruker, endretGrunnlag) shouldBe lagretAvkorting } coVerify(exactly = 1) { behandlingKlient.avkort(behandlingId, bruker, false) avkortingRepository.hentAvkorting(behandlingId) behandlingKlient.hentBehandling(behandlingId, bruker) beregningService.hentBeregningNonnull(behandlingId) eksisterendeAvkorting.beregnAvkortingMedNyttGrunnlag( endretGrunnlag, behandling.behandlingType, virkningsdato, beregning ) avkortingRepository.lagreAvkorting(behandlingId, beregnetAvkorting) behandlingKlient.avkort(behandlingId, bruker, true) } } @Test fun `Skal feile ved lagring av avkortinggrunnlag hvis behandling er i feil tilstand`() { val behandlingId = UUID.randomUUID() coEvery { behandlingKlient.avkort(behandlingId, bruker, false) } returns false runBlocking { assertThrows<Exception> { service.lagreAvkorting(behandlingId, bruker, avkortinggrunnlag()) } } coVerify { behandlingKlient.avkort(behandlingId, bruker, false) } } } }
8
Kotlin
0
3
5c79aa753584026a360f097f449e677e2f125759
10,332
pensjon-etterlatte-saksbehandling
MIT License
app/src/main/java/com/dreamsoftware/inquize/ui/components/ChatMessageCard.kt
sergio11
189,729,405
false
{"Kotlin": 288983}
package com.dreamsoftware.inquize.ui.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CardColors import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedCard import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.dreamsoftware.brownie.component.BrownieCard import com.dreamsoftware.brownie.component.BrownieText import com.dreamsoftware.brownie.component.BrownieTextTypeEnum /** * Represents the role of a participant in a chat conversation. */ enum class Role { /** * Represents the user sending the message. */ USER, /** * Represents the participant responding to the message. */ RESPONDER } /** * A visually distinct card for a chat message based on the sender's [Role]. * * @param messageContent the text content of the chat message. * @param role the [Role] of the message sender * @param modifier [Modifier] to be applied to the card composable. */ @Composable fun ChatMessageCard(messageContent: String, role: Role, modifier: Modifier = Modifier) { with(MaterialTheme.colorScheme) { val border = remember(role) { BorderStroke(5.dp, if (role == Role.USER) { primaryContainer } else { primaryContainer }) } val shape = remember(role) { RoundedCornerShape(50.dp).run { if (role == Role.USER) { copy(topEnd = CornerSize(0.dp)) } else { copy(topStart = CornerSize(0.dp)) } } } BrownieCard( modifier = modifier, colors = CardDefaults.outlinedCardColors( containerColor = if(role == Role.USER) { primary } else { secondary }, ), border = border, shape = shape, ) { BrownieText( modifier = Modifier.padding(24.dp), type = BrownieTextTypeEnum.BODY_MEDIUM, titleText = messageContent, textColor = if(role == Role.USER) { onPrimary } else { onSecondary } ) } } }
0
Kotlin
0
1
062ac9c8a942148d0008d2043d02db62ff964841
2,695
inquize_android
The Unlicense
src/com/hzh/kotlin/L02/ClassTest.kt
shihuihzh
135,589,087
false
{"Text": 1, "Ignore List": 1, "Kotlin": 23, "Java": 1}
package com.hzh.kotlin.L02 open class Base constructor(name: String) { open val firstName = name.toUpperCase() init { println("Init Base...") } open fun print() { println("test...") } } class Person(override val firstName: String, val lastName: String) : Base(firstName) { init { println("Init Person...") } val size = firstName.length.also { println("name size is: $it") } // secondary constructor constructor() : this("Hello", "kitty") override fun print() { super.print() println("${this.firstName} ${this.lastName}") } inner class InnerPerson { fun print() { [email protected]() println("inner person") } } } //////////////////////////////////////////////////// open class A { open fun a() { println("a") } open fun b() { println("b") } } interface B { fun d() { println("d") } fun e() { println("e") } } class C : A(), B { // override fun a() { // // } // // override fun b() { // // } // } ////////////////////////////////////////////////////////// class Phone { var color = "" set(value) { println("setting color...") field = value //color = value DON'T DO THIS } var name = "" var price = 0.0 var desc: String = "" get() = "name = $name, color = $color, price = $price" private set } fun main(args: Array<String>) { val p = Person("Zhanhao", "Huang") val p2 = Person() val ip = Person().InnerPerson() p.print() p2.print() ip.print() println() // val c = C(); c.a() c.d() // val phone = Phone() phone.color = "red" phone.name = "iPhone" phone.price = 1000.0 //phone.desc = "" println(phone.desc) }
0
Kotlin
0
0
e585386e6f7fd5f403d3b0eed6a311af37c76573
1,897
Kotlin-learning
MIT License
sdk-base/src/main/java/com/mapbox/maps/module/TelemetryEvent.kt
mapbox
330,365,289
false
{"Kotlin": 3982759, "Java": 98572, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2413, "CMake": 1201, "EJS": 1194}
package com.mapbox.maps.module import androidx.annotation.RestrictTo import com.mapbox.common.FeatureTelemetryCounter /** * Feature telemetry event definition. * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) class TelemetryEvent private constructor(private val name: String) { private val counter: FeatureTelemetryCounter? = try { FeatureTelemetryCounter.create(name) } catch (e: Throwable) { null } /** * Static methods. */ companion object { fun create(name: String) = TelemetryEvent("maps-mobile/$name") } /** * Increment feature telemetry event counter. * @suppress */ fun increment() { counter?.increment() } }
181
Kotlin
131
472
2700dcaf18e70d23a19fc35b479bff6a2d490475
689
mapbox-maps-android
Apache License 2.0
dashboard/src/main/java/com/kienht/gapo/dashboard/news_feeds/decoration/FriendRequestDecoration.kt
hantrungkien
263,898,699
false
null
package com.kienht.gapo.dashboard.news_feeds.decoration import android.content.Context import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import htkien.autodimens.R.dimen as autoDimens /** * @author kienht */ class FriendRequestDecoration(context: Context) : RecyclerView.ItemDecoration() { private val _10dp = context.resources.getDimensionPixelSize(autoDimens._10dp) private val _15dp = context.resources.getDimensionPixelSize(autoDimens._15dp) override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val itemPosition = parent.getChildAdapterPosition(view) if (itemPosition == RecyclerView.NO_POSITION) { return } if (itemPosition == 0) { outRect.left = _15dp } if (itemPosition == (parent.adapter?.itemCount ?: 0) - 1) { outRect.right = _15dp } else { outRect.right = _10dp } outRect.top = _10dp outRect.bottom = _10dp } }
0
Kotlin
4
9
32bdbc5f3e2ed9965898be9b892b06cb2da26da7
1,115
Gapo-Dashboard-Demo
Apache License 2.0
android-core/src/main/kotlin/org/mint/android/rule/viewgroup/ViewGroupRules.kt
ing-bank
620,378,707
false
null
package org.mint.android.rule.viewgroup import org.mint.android.Action import org.mint.android.rule.BasicRules import org.mint.android.rule.BasicRules.defaultPrio import org.mint.android.rule.BasicRules.xpred import org.mint.android.rule.GenericRule import org.mint.android.rule.MultiplicativeRule import java.math.BigDecimal object ViewGroupRules { fun scrollingPagerRightRule(): GenericRule = GenericRule( description = "Scroll pager to the right", action = Action.SCROLL_PAGER_TO_RIGHT, pred = xpred( ".[@isViewPager = 'true' and @canScrollRight = 'true' ]", ), prio = defaultPrio, ) fun scrollingPagerLeftRule(): GenericRule = GenericRule( description = "Scroll pager to the left", action = Action.SCROLL_PAGER_TO_LEFT, pred = xpred( ".[@isViewPager = 'true' and @canScrollLeft = 'true' ]", ), prio = defaultPrio, ) // The simple click action cannot be used for widgets contained by RecyclerView or ViewPager, // since it requires an unique resource name for the widget // and the RecyclerView and ViewPager are used to display replicated items. fun replicatedItemSimpleClickDeprioritizeRule(): MultiplicativeRule = MultiplicativeRule( description = "De-prioritized the clicking of individual RecyclerView or ViewPager items with simple click", action = Action.CLICK, pred = xpred(".[ancestor::*[@isRecyclerView = 'true'] or ancestor::*[@isViewPager = 'true'] ]"), prio = BasicRules.fprio(BigDecimal(0.01)), ) }
0
Kotlin
2
4
abf96d311b3ebb1bba2a331a353126c653225be9
1,693
mint
MIT License
src/test/kotlin/com/gildedrose/BackStagePassesTest.kt
jack-bolles
424,172,564
false
null
package com.gildedrose import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class BackStagePassesTest { @Test fun `passes quality falls to zero after the concert`() { val dayZero = listOf( Item("Backstage passes to a TAFKAL80ETC concert", 1, 30), Item("Backstage passes to a TAFKAL80ETC concert", 0, 30), ) val nextDay = listOf( Item("Backstage passes to a TAFKAL80ETC concert", 0, 33), Item("Backstage passes to a TAFKAL80ETC concert", -1, 0), ) assertEquals(nextDay, dayZero.ageFor(1)) } @Test fun `passes quality increases by 2 when there are 10 days or less`() { val dayZero = listOf( Item("Backstage passes to a TAFKAL80ETC concert", 12, 30), Item("Backstage passes to a TAFKAL80ETC concert", 11, 30), Item("Backstage passes to a TAFKAL80ETC concert", 10, 30), ) val nextDay = listOf( Item("Backstage passes to a TAFKAL80ETC concert", 11, 31), Item("Backstage passes to a TAFKAL80ETC concert", 10, 32), Item("Backstage passes to a TAFKAL80ETC concert", 9, 32), ) assertEquals(nextDay, dayZero.ageFor(1)) } @Test fun `passes quality increases by 3 when there are 5 days or less `() { val dayZero = listOf( Item("Backstage passes to a TAFKAL80ETC concert", 7, 30), Item("Backstage passes to a TAFKAL80ETC concert", 6, 30), Item("Backstage passes to a TAFKAL80ETC concert", 5, 30), ) val nextDay = listOf( Item("Backstage passes to a TAFKAL80ETC concert", 6, 32), Item("Backstage passes to a TAFKAL80ETC concert", 5, 33), Item("Backstage passes to a TAFKAL80ETC concert", 4, 33), ) assertEquals(nextDay, dayZero.ageFor(1)) } }
0
Kotlin
0
0
20362811724367e10e60fcf79b8709e60e9b0dde
1,931
GildedRose-Refactoring-Kata-Kotlin
MIT License
src/main/java/wiles/interpreter/interpreters/InterpretFromDeclaration.kt
Alex-Costea
527,241,623
false
null
package wiles.interpreter.interpreters import wiles.interpreter.data.VariableMap import wiles.shared.JSONStatement class InterpretFromDeclaration(statement: JSONStatement, variables: VariableMap, additionalVars: VariableMap) : InterpretFromStatement(statement, variables, additionalVars) { override fun interpret() { if(statement.components.size==3) { val interpretFromExpression = InterpretFromExpression(statement.components[2], variables, additionalVars) interpretFromExpression.interpret() variables[statement.components[1].name] = interpretFromExpression.reference } } }
0
Kotlin
0
0
f5a3264e61b946e266661a7d65d6de191693bca6
642
Wiles
MIT License
core/src/main/kotlin/team/duckie/quackquack/core/component/text.kt
duckie-team
523,387,054
false
null
/* * Designed and developed by Duckie Team 2023. * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/quack-quack-android/blob/2.x.x/LICENSE */ package team.duckie.quackquack.core.component import androidx.annotation.VisibleForTesting import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.ClickableText import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.currentComposer import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap import team.duckie.quackquack.aide.annotation.DecorateModifier import team.duckie.quackquack.core.animation.QuackAnimatedContent import team.duckie.quackquack.core.material.QuackColor import team.duckie.quackquack.core.material.QuackTypography import team.duckie.quackquack.core.material.animatedQuackTextStyleAsState import team.duckie.quackquack.core.runtime.QuackDataModifierModel import team.duckie.quackquack.core.runtime.quackComposed import team.duckie.quackquack.core.runtime.quackMaterializeOf import team.duckie.quackquack.core.util.fastFirstIsInstanceOrNull import team.duckie.quackquack.sugar.material.SugarName import team.duckie.quackquack.sugar.material.SugarToken /** * `Modifier.highlight`에 들어가는 하이라이트 아이템을 [Pair]로 나타냅니다. * * 하이라이트 대상 문자열을 나타내는 `String`과, * 하이라이트 문자열을 눌렀을 때 실행될 `(text: String) -> Unit` 람다로 구성돼 있습니다. * 람다 속 `text` 인자는 클릭된 문자열을 반환합니다. */ public typealias HighlightText = Pair<String, ((text: String) -> Unit)?> @Stable private data class SpanData( val texts: List<String>, val style: SpanStyle, ) : QuackDataModifierModel { private val textArray = texts.toTypedArray() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SpanData) return false if (texts != other.texts) return false if (!textArray.contentEquals(other.texts.toTypedArray())) return false if (style != other.style) return false return true } override fun hashCode(): Int { var result = textArray.contentHashCode() result = 31 * result + style.hashCode() return result } } @Stable private data class HighlightData( val highlights: List<HighlightText>, val span: SpanStyle, ) : QuackDataModifierModel { private val highlightArray = highlights.toTypedArray() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is HighlightData) return false if (highlights != other.highlights) return false if (!highlightArray.contentEquals(other.highlights.toTypedArray())) return false if (span != other.span) return false return true } override fun hashCode(): Int { var result = highlightArray.contentHashCode() result = 31 * result + span.hashCode() return result } } /** * 주어진 텍스트에 [SpanStyle]을 적용합니다. * * @param texts [SpanStyle]을 적용할 텍스트 모음 * @param style 적용할 [SpanStyle] */ @DecorateModifier @Stable public fun Modifier.span( texts: List<String>, style: SpanStyle, ): Modifier { return then(SpanData(texts = texts, style = style)) } /** * 주어진 텍스트에 클릭 가능한 [SpanStyle]을 입힙니다. * * @param highlights 클릭 이벤트를 적용할 텍스트 모음 * @param span 적용할 [SpanStyle] */ @DecorateModifier @Stable public fun Modifier.highlight( highlights: List<HighlightText>, span: SpanStyle = SpanStyle( color = QuackColor.DuckieOrange.value, fontWeight = FontWeight.SemiBold, ), ): Modifier { return then(HighlightData(highlights = highlights, span = span)) } /** * 주어진 텍스트에 클릭 가능한 [SpanStyle]을 입힙니다. * * @param texts 클릭 이벤트를 적용할 텍스트 모음 * @param span 적용할 [SpanStyle] * @param globalOnClick [texts]에 전역으로 적용할 클릭 이벤트 */ @DecorateModifier @Stable public fun Modifier.highlight( texts: List<String>, span: SpanStyle = SpanStyle( color = QuackColor.DuckieOrange.value, fontWeight = FontWeight.SemiBold, ), globalOnClick: (text: String) -> Unit, ): Modifier { return quackComposed { val highlights = remember(texts, globalOnClick) { texts.fastMap { text -> HighlightText(text, globalOnClick) } } then(HighlightData(highlights = highlights, span = span)) } } @VisibleForTesting internal object QuackTextErrors { const val CannotUseSpanAndHighlightAtSameTime = "Modifier.span과 Modifier.highlight는 같이 사용될 수 없습니다." } /** * 텍스트를 그리는 기본적인 컴포저블입니다. * * @param text 그릴 텍스트 * @param typography 텍스트를 그릴 때 사용할 타이포그래피 * @param singleLine 텍스트가 한 줄로 그려질 지 여부. * 텍스트가 주어진 줄 수를 초과하면 [softWrap] 및 [overflow]에 따라 잘립니다. * @param softWrap 텍스트에 softwrap break를 적용할지 여부. * `false`이면 텍스트 글리프가 가로 공간이 무제한인 것처럼 배치됩니다. * 또한 [overflow] 및 [TextAlign]에 예기치 않은 효과가 발생할 수 있습니다. * @param overflow 시각적 overflow를 처리하는 방법 */ @SugarName(SugarName.PREFIX_NAME + SugarName.TOKEN_NAME) @Composable public fun QuackText( modifier: Modifier = Modifier, text: String, @SugarToken typography: QuackTypography, singleLine: Boolean = false, softWrap: Boolean = true, overflow: TextOverflow = TextOverflow.Ellipsis, ) { val (composeModifier, quackDataModels) = currentComposer.quackMaterializeOf(modifier) val spanData = remember(quackDataModels) { quackDataModels.fastFirstIsInstanceOrNull<SpanData>() } val highlightData = remember(quackDataModels) { quackDataModels.fastFirstIsInstanceOrNull<HighlightData>() } if (highlightData != null && spanData != null) { error(QuackTextErrors.CannotUseSpanAndHighlightAtSameTime) } val style = animatedQuackTextStyleAsState(typography).asComposeStyle() val maxLines = if (singleLine) 1 else Int.MAX_VALUE QuackAnimatedContent( modifier = composeModifier, targetState = text, ) { animatedText -> if (spanData != null) { BasicText( modifier = composeModifier, text = rememberSpanAnnotatedString( text = animatedText, spanTexts = spanData.texts, spanStyle = spanData.style, annotationTexts = emptyList(), ), style = style, overflow = overflow, softWrap = softWrap, maxLines = maxLines, ) } else if (highlightData != null) { QuackClickableText( modifier = composeModifier, text = animatedText, highlightData = highlightData, style = style, overflow = overflow, softWrap = softWrap, maxLines = maxLines, ) } else { BasicText( modifier = composeModifier, text = animatedText, style = style, overflow = overflow, softWrap = softWrap, maxLines = maxLines, ) } } } @Composable private fun QuackClickableText( modifier: Modifier, text: String, highlightData: HighlightData, style: TextStyle, softWrap: Boolean, overflow: TextOverflow, maxLines: Int, ) { val highlightTexts = highlightData.highlights.fastMap(Pair<String, *>::first) val annotatedText = rememberSpanAnnotatedString( text = text, spanTexts = highlightTexts, spanStyle = highlightData.span, annotationTexts = highlightTexts, ) ClickableText( modifier = modifier, text = annotatedText, style = style, onClick = { offset -> highlightData.highlights.fastForEach { (text, onClick) -> val annotations = annotatedText.getStringAnnotations( tag = text, start = offset, end = offset, ) if (annotations.isNotEmpty() && onClick != null) { onClick(text) } } }, softWrap = softWrap, overflow = overflow, maxLines = maxLines, ) } /** * 주어진 옵션에 일치하는 span을 추가한 [AnnotatedString]을 계산합니다. * * @param text 원본 텍스트 * @param spanTexts span 처리할 텍스트들 * @param spanStyle span 스타일 */ @Stable @Composable private fun rememberSpanAnnotatedString( text: String, spanTexts: List<String>, spanStyle: SpanStyle, annotationTexts: List<String>, ): AnnotatedString { return remember(text, spanTexts, spanStyle) { buildAnnotatedString { append(text) spanTexts.fastForEach { spanText -> val spanStartIndex = text.indexOf(spanText) if (spanStartIndex != -1) { addStyle( style = spanStyle, start = spanStartIndex, end = spanStartIndex + spanText.length, ) } } annotationTexts.fastForEach { annotationText -> val annotationStartIndex = text.indexOf(annotationText) if (annotationStartIndex != -1) { addStringAnnotation( tag = annotationText, start = annotationStartIndex, end = annotationStartIndex + annotationText.length, annotation = annotationText, ) } } } } }
16
Kotlin
4
37
fb8481e083809c3f63922a380137b48e0a0142e5
9,954
quack-quack-android
MIT License
app/src/main/java/io/github/gmathi/novellibrary/cleaner/WordPressHelper.kt
Guiorgy
233,595,061
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 121, "XML": 173, "Java": 1, "JSON": 2}
package io.github.gmathi.novellibrary.cleaner import android.net.Uri import io.github.gmathi.novellibrary.network.HostNames import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.io.File class WordPressHelper : HtmlHelper() { override fun additionalProcessing(doc: Document) { removeCSS(doc) doc.head()?.getElementsByTag("link")?.remove() var contentElement = doc.body().getElementsByTag("div").firstOrNull { it.hasClass("entry-content") } contentElement?.prepend("<h4>${getTitle(doc)}</h4><br>") do { contentElement?.siblingElements()?.remove() cleanClassAndIds(contentElement) contentElement = contentElement?.parent() } while (contentElement != null && contentElement.tagName() != "body") cleanClassAndIds(contentElement) contentElement?.getElementsByClass("wpcnt")?.remove() contentElement?.getElementById("jp-post-flair")?.remove() } override fun downloadImage(element: Element, file: File): File? { val uri = Uri.parse(element.attr("src")) return if (uri.toString().contains("uploads/avatars")) null else super.downloadImage(element, file) } override fun getLinkedChapters(doc: Document): ArrayList<String> { val links = ArrayList<String>() val otherLinks = doc.getElementsByAttributeValue("itemprop", "articleBody").firstOrNull()?.getElementsByAttributeValueContaining("href", HostNames.WORD_PRESS) if (otherLinks != null && otherLinks.isNotEmpty()) { otherLinks.mapTo(links) { it.attr("href") } } return links } override fun toggleTheme(isDark: Boolean, doc: Document): Document { return super.toggleThemeDefault(isDark, doc) } }
1
null
1
1
4a9e1b66c508430b6024319658bb50eb5a313e64
1,792
NovelLibrary
Apache License 2.0
src/main/kotlin/com/enviableyapper0/sbaserver/SbaServerApplication.kt
EnviableYapper0
517,353,295
false
{"Kotlin": 3043}
package com.enviableyapper0.sbaserver import de.codecentric.boot.admin.server.config.EnableAdminServer import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @EnableAdminServer @SpringBootApplication class SbaServerApplication fun main(args: Array<String>) { runApplication<SbaServerApplication>(*args) }
0
Kotlin
0
0
93bdd047bdb80d81217bbe00d5fbc2ff535bc213
369
SBA_AAD_Example
MIT License
serenity-app/src/main/kotlin/us/nineworlds/serenity/ui/leanback/presenters/VideoContentInfoPresenter.kt
NineWorlds
7,139,471
false
{"Java": 701863, "Kotlin": 293495, "Shell": 2466}
package us.nineworlds.serenity.ui.leanback.presenters import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.content.ContextCompat import androidx.leanback.widget.ImageCardView import androidx.leanback.widget.Presenter import us.nineworlds.serenity.GlideApp import us.nineworlds.serenity.R import us.nineworlds.serenity.common.rest.Types import us.nineworlds.serenity.core.model.VideoCategory import us.nineworlds.serenity.core.model.VideoContentInfo import us.nineworlds.serenity.ui.views.statusoverlayview.StatusOverlayFrameLayout class CategoryVideoPresenter : Presenter() { override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { val statusOverlayView = StatusOverlayFrameLayout(parent.context) statusOverlayView.isFocusable = true statusOverlayView.isFocusableInTouchMode = true statusOverlayView.setBackgroundColor(ContextCompat.getColor(parent.context, android.R.color.transparent)) return CardPresenterViewHolder(statusOverlayView) } override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) { val video = item as VideoCategory val cardHolder = viewHolder as CardPresenterViewHolder cardHolder.bind(video.item) } override fun onUnbindViewHolder(viewHolder: ViewHolder) { val vh = viewHolder as CardPresenterViewHolder vh.reset() } inner class CardPresenterViewHolder(view: View) : Presenter.ViewHolder(view) { val cardView: StatusOverlayFrameLayout = view as StatusOverlayFrameLayout fun reset() { cardView.reset() } fun bind(videoContentInfo: VideoContentInfo) { cardView.tag = videoContentInfo videoContentInfo.imageURL?.let { when(videoContentInfo.type) { Types.EPISODE -> { val imageWidth = view.context.resources.getDimensionPixelSize(R.dimen.episode_image_width) val imageHeight = view.context.resources.getDimensionPixelSize(R.dimen.episode_image_height) cardView.episodeInfo(videoContentInfo) cardView.createImage(videoContentInfo, imageWidth, imageHeight) } else -> { val imageWidth = view.context.resources.getDimensionPixelSize(R.dimen.movie_poster_image_width) val imageHeight = view.context.resources.getDimensionPixelSize(R.dimen.movie_poster_image_height) cardView.createImage(videoContentInfo, imageWidth, imageHeight) } } } cardView.toggleWatchedIndicator(videoContentInfo) } } }
25
Java
65
177
155cfb76bb58f2f06ccac8e3e45151221c59560d
2,777
serenity-android
MIT License
core/src/io/github/advancerman/todd/objects/weapon/SimpleGun.kt
AdvancerMan
278,029,588
false
null
package io.github.advancerman.todd.objects.weapon import com.badlogic.gdx.math.Vector2 import io.github.advancerman.todd.json.JsonFullSerializable import io.github.advancerman.todd.json.SerializationType import io.github.advancerman.todd.launcher.ToddGame import io.github.advancerman.todd.objects.weapon.bullet.Bullet /** * Simple gun without modifications * * * @param handWeaponStyle Style of the weapon * @param power Amount of damage done by attack * @param cooldown Minimum time period between attack end and next attack beginning * @param safeAttackPeriod Time period after attack beginning till actual shot * @param bulletOffset Bullet spawn position relative to unrotated, unflipped hand's position * @param bulletBuilder Would be replaced by bullet json pattern in future releases */ @SerializationType([Weapon::class], "SimpleGun") open class SimpleGun( private val game: ToddGame, handWeaponStyle: Style, override val power: Float, cooldown: Float, safeAttackPeriod: Float, @JsonFullSerializable protected val bulletOffset: Vector2, @JsonFullSerializable protected val bulletBuilder: Bullet.Builder ) : HandWeapon(handWeaponStyle, cooldown, safeAttackPeriod, safeAttackPeriod) { override fun doAttack() { screen.addObject( bulletBuilder.build( game, power, localToStageCoordinates( getDrawablePosition( listOf(handWeaponStyle.handDrawable, handWeaponStyle.weaponDrawable) .mapNotNull { it?.offset } .fold(bulletOffset.cpy()) { v1, v2 -> v1.add(v2) }, 0f // TODO add width if x flipped ) ), if (owner.isDirectedToRight) Vector2(1f, 0f) else Vector2(-1f, 0f), owner ) ) } }
1
Kotlin
0
2
efeb10c60c607d393a26963dc9aa9109dd00bd1c
1,905
todd-kt
MIT License
app/src/main/kotlin/me/dmdev/rxpm/demo/TextSearchPresentationModel.kt
dmdevgo
88,917,532
false
null
package me.dmdev.rxpm.demo import com.jakewharton.rxrelay2.BehaviorRelay import com.jakewharton.rxrelay2.PublishRelay import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.functions.BiFunction import io.reactivex.functions.Consumer import java.util.concurrent.TimeUnit /** * @author <NAME> */ class TextSearchPresentationModel { private val interactor: TextSearchInteractor = TextSearchInteractorImpl() // --- States --- private val foundWords = BehaviorRelay.create<List<String>>() val foundWordState: Observable<List<String>> = foundWords.hide() private val loading = BehaviorRelay.createDefault<Boolean>(false) val loadingState: Observable<Boolean> = loading.hide() val searchButtonEnabledState: Observable<Boolean> = loading.map { !it }.hide() // -------------- // --- UI-events --- private val searchQuery = PublishRelay.create<String>() val searchQueryConsumer: Consumer<String> = searchQuery private val inputTextChanges = PublishRelay.create<String>() val inputTextChangesConsumer: Consumer<String> = inputTextChanges private val searchButtonClicks = PublishRelay.create<Unit>() val searchButtonClicksConsumer: Consumer<Unit> = searchButtonClicks // --------------- private var disposable: Disposable? = null fun onCreate() { val filteredText = inputTextChanges.filter(String::isNotEmpty) val filteredQuery = searchQuery.filter(String::isNotEmpty) val combine = Observable.combineLatest(filteredText, filteredQuery, BiFunction(::SearchParams)) val requestByClick = searchButtonClicks.withLatestFrom(combine, BiFunction<Unit, SearchParams, SearchParams> { _, params: SearchParams -> params }) disposable = requestByClick .filter { !isLoading() } .doOnNext { showProgress() } .delay(3, TimeUnit.SECONDS) // делаем задержку чтобу увидеть прогресс .flatMap { interactor.findWords(it).toObservable() } .observeOn(AndroidSchedulers.mainThread()) .doOnEach { hideProgress() } .subscribe(foundWords) } fun onDestroy() { disposable?.dispose() } private fun isLoading() = loading.value private fun showProgress() = loading.accept(true) private fun hideProgress() = loading.accept(false) }
0
Kotlin
2
10
657e5a7eb3229a11a73c066ffda4eb5bdfc33ce9
2,475
RxPM-Demo
MIT License
compiler/testData/writeFlags/function/deprecatedFlag/topLevelFun.kt
udalov
10,645,710
false
{"Java": 9931656, "Kotlin": 2142480, "JavaScript": 942412, "C++": 613791, "C": 193807, "Objective-C": 22634, "Shell": 12589, "Groovy": 1267}
Deprecated("") fun test() {} // TESTED_OBJECT_KIND: function // TESTED_OBJECTS: _DefaultPackage, test // FLAGS: ACC_DEPRECATED, ACC_PUBLIC, ACC_FINAL, ACC_STATIC
0
Java
1
6
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
163
kotlin-objc-diploma
Apache License 2.0
app/src/main/kotlin/io/github/nuhkoca/libbra/data/enums/Rate.kt
nuhkoca
252,193,036
false
{"Kotlin": 258455, "Shell": 1250, "Java": 620}
/* * Copyright (C) 2020. <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.nuhkoca.libbra.data.enums import androidx.annotation.DrawableRes import io.github.nuhkoca.libbra.R /** * An enum that represents all remote currencies. * * @property resId The drawable id */ enum class Rate(val longName: String, @DrawableRes val resId: Int) { /** * Unknown type for undefined currency, this is to avoid crash for possible future * implementations */ UNKNOWN("Unknown", R.drawable.ic_unknown), /** * Currency type for Australian Dollar */ AUD("Australian Dollar", R.drawable.ic_aud), /** * Currency type for Bulgarian Lev */ BGN("Bulgarian Lev", R.drawable.ic_bgn), /** * Currency type for Brazilian Real */ BRL("Brazilian Real", R.drawable.ic_brl), /** * Currency type for Canadian Dollar */ CAD("Canadian Dollar", R.drawable.ic_cad), /** * Currency type for Swiss Franc */ CHF("Swiss Franc", R.drawable.ic_chf), /** * Currency type for Chinese Yuan */ CNY("Chinese Yuan", R.drawable.ic_cny), /** * Currency type for Czech Koruna */ CZK("Czech Koruna", R.drawable.ic_czk), /** * Currency type for Danish Krone */ DKK("Danish Krone", R.drawable.ic_dkk), /** * Currency type for Euro */ EUR("Euro", R.drawable.ic_eur), /** * Currency type for Pound */ GBP("Pound", R.drawable.ic_gbp), /** * Currency type for Hong Kong Dollar */ HKD("Hong Kong Dollar", R.drawable.ic_hkd), /** * Currency type for Croatian Kuna */ HRK("Croatian Kuna", R.drawable.ic_hrk), /** * Currency type for Hungarian Forint */ HUF("Hungarian Forint", R.drawable.ic_huf), /** * Currency type for Indonesian Rupiah */ IDR("Indonesian Rupiah", R.drawable.ic_idr), /** * Currency type for Israeli New Shekel */ ILS("Israeli New Shekel", R.drawable.ic_ils), /** * Currency type for Indian Rupee */ INR("Indian Rupee", R.drawable.ic_inr), /** * Currency type for Icelandic Króna */ ISK("Icelandic Króna", R.drawable.ic_isk), /** * Currency type for Japanese Yen */ JPY("Japanese Yen", R.drawable.ic_jpy), /** * Currency type for South Korean Won */ KRW("South Korean Won", R.drawable.ic_krw), /** * Currency type for Mexican Peso */ MXN("Mexican Peso", R.drawable.ic_mxn), /** * Currency type for Malaysian Ringgit */ MYR("Malaysian Ringgit", R.drawable.ic_myr), /** * Currency type for Norwegian Krone */ NOK("Norwegian Krone", R.drawable.ic_nok), /** * Currency type for New Zealand Dollar */ NZD("New Zealand Dollar", R.drawable.ic_nzd), /** * Currency type for Philippine Peso */ PHP("Philippine Peso", R.drawable.ic_php), /** * Currency type for Poland Złoty */ PLN("Poland Złoty", R.drawable.ic_pln), /** * Currency type for Romanian Leu */ RON("Romanian Leu", R.drawable.ic_ron), /** * Currency type for Russian Ruble */ RUB("Russian Ruble", R.drawable.ic_rub), /** * Currency type for Swedish Krona */ SEK("Swedish Krona", R.drawable.ic_sek), /** * Currency type for Singapore Dollar */ SGD("Singapore Dollar", R.drawable.ic_sgd), /** * Currency type for Thai Baht */ THB("Thai Baht", R.drawable.ic_thb), /** * Currency type for United States Dollar */ USD("United States Dollar", R.drawable.ic_usd), /** * Currency type for South African Rand */ ZAR("South African Rand", R.drawable.ic_zar) }
1
Kotlin
11
54
ffc089cba24281a3a8a8a1991bea6d4222456a79
4,356
libbra
Apache License 2.0
feature-staking-impl/src/main/java/com/dfinn/wallet/feature_staking_impl/domain/validations/bond/Declarations.kt
finn-exchange
500,972,990
false
null
package com.dfinn.wallet.feature_staking_impl.domain.validations.bond import com.dfinn.wallet.common.validation.ValidationSystem import com.dfinn.wallet.feature_wallet_api.domain.validation.EnoughToPayFeesValidation import com.dfinn.wallet.feature_wallet_api.domain.validation.PositiveAmountValidation typealias BondMoreFeeValidation = EnoughToPayFeesValidation<BondMoreValidationPayload, BondMoreValidationFailure> typealias NotZeroBondValidation = PositiveAmountValidation<BondMoreValidationPayload, BondMoreValidationFailure> typealias BondMoreValidationSystem = ValidationSystem<BondMoreValidationPayload, BondMoreValidationFailure>
0
Kotlin
0
0
6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d
639
dfinn-android-wallet
Apache License 2.0
domain/src/commonMain/kotlin/kosh/domain/models/wc/PairingUri.kt
niallkh
855,100,709
false
{"Kotlin": 1813876, "Swift": 594}
package kosh.domain.models.reown import androidx.compose.runtime.Immutable import arrow.core.Either import arrow.core.raise.either import arrow.core.raise.ensure import kosh.domain.failure.WcFailure import kotlinx.serialization.Serializable import kotlin.jvm.JvmInline @Serializable @JvmInline @Immutable value class PairingUri private constructor(val value: String) { companion object { operator fun invoke(uri: String): Either<WcFailure.PairingUriInvalid, PairingUri> = either { ensure(uri.startsWith("wc:")) { WcFailure.PairingUriInvalid() } ensure(arrayOf("@2", "relay-protocol=irn", "symKey").all { it in uri }) { WcFailure.PairingUriInvalid() } PairingUri(uri) } } }
0
Kotlin
0
3
f48555a563dfee5b07184771a6c94c065765d570
794
kosh
MIT License
app/src/main/java/com/muehlemann/main/contracts/BaseContract.kt
muehlemann
207,129,052
false
null
package com.muehlemann.main.contracts interface BaseContract { interface View { fun showToast(text: String) } interface Presenter<V : View> { fun onViewAttached(view: V) fun onViewDestroyed() } }
0
Kotlin
0
0
cd037bdccc52a52fcb89bee9e89ead5d66ac5ba4
238
habit
MIT License
app/src/main/java/com/muehlemann/main/contracts/BaseContract.kt
muehlemann
207,129,052
false
null
package com.muehlemann.main.contracts interface BaseContract { interface View { fun showToast(text: String) } interface Presenter<V : View> { fun onViewAttached(view: V) fun onViewDestroyed() } }
0
Kotlin
0
0
cd037bdccc52a52fcb89bee9e89ead5d66ac5ba4
238
habit
MIT License
app/src/main/java/com/learn/tindertemplate/myutils/MyConstant.kt
rahulkumarabhishek
394,579,249
false
null
package com.learn.tindertemplate.myutils class MyConstant { companion object { const val BaseUrl: String = "https://randomuser.me/api/0.4/?randomapi" } }
0
Kotlin
0
0
154a3c148250f45f42c2368a17084e5e82d769ce
170
TinderTemplate
Apache License 2.0
app/src/main/java/jdls/one/showmethemovies/main/TVShowsListViewModel.kt
JorgeDLS
206,833,036
false
null
package jdls.one.showmethemovies.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.observers.DisposableSingleObserver import jdls.one.domain.interactor.GetPopularTVShows import jdls.one.domain.model.Movie import jdls.one.domain.model.MovieResults import jdls.one.showmethemovies.state.Resource import jdls.one.showmethemovies.state.ResourceState import java.util.* import javax.inject.Inject open class TVShowsListViewModel @Inject internal constructor( private val getPopularTVShows: GetPopularTVShows ) : ViewModel() { private val moviesLiveData: MutableLiveData<Resource<List<Movie>>> = MutableLiveData() internal var currentPage: Int = 1 internal var totalPages: Int = 1 init { fetchPopularTVShows() } override fun onCleared() { getPopularTVShows.dispose() super.onCleared() } fun getPopularTVShows(): LiveData<Resource<List<Movie>>> { return moviesLiveData } fun fetchPopularTVShows() { moviesLiveData.postValue(Resource(ResourceState.LOADING, null, null)) return getPopularTVShows.execute( GetPopularTVShowsSubscriber(), Pair(Locale.getDefault().toString(), currentPage) ) } fun requestMoreData() { currentPage++ if (currentPage <= totalPages) fetchPopularTVShows() } inner class GetPopularTVShowsSubscriber : DisposableSingleObserver<MovieResults>() { override fun onSuccess(movieResults: MovieResults) { totalPages = movieResults.totalPages moviesLiveData.postValue(Resource(ResourceState.SUCCESS, movieResults.movies, null)) } override fun onError(exception: Throwable) { moviesLiveData.postValue(Resource(ResourceState.ERROR, null, exception.message)) } } }
1
Kotlin
0
1
361852555ab4b1d805ca0a4ad5d66a5caf4d944c
1,784
ShowMeTheMovies
Apache License 2.0
module_pics/src/main/java/com/fxc/pics/pic/network/DataManager.kt
T-Oner
116,654,059
false
null
package com.fxc.pics.pic.network import com.fxc.pics.common.base.BaseApplication import com.fxc.pics.network.isNetworkAvailable import com.fxc.pics.pic.network.RetrofitManager.UNSPLASH_API import com.fxc.pics.pic.network.RetrofitManager.UNSPLASH_WEB import com.fxc.pics.pic.network.entities.PicDetailEntity import com.fxc.pics.pic.network.entities.PicListEntity import com.fxc.pics.pic.network.entities.PicRelatedEntity import com.fxc.pics.pic.network.entities.RandomPicEntity import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers /** * * @author fxc * @date 2018/1/13 */ /** * 获取一张随机图片 */ internal fun getRandomPic(listener: DataSource.Callback<RandomPicEntity>) { if (!isNetworkAvailable(BaseApplication.getApplication())) { listener.onDataError(2) return } val command = RetrofitManager.remount(UNSPLASH_API) rxResponse(command.getRandomPic(), listener) } internal fun getPicList(page: Int, listener: DataSource.Callback<List<PicListEntity>>) { if (!isNetworkAvailable(BaseApplication.getApplication())) { listener.onDataError(2) return } val command = RetrofitManager.remount(UNSPLASH_API) rxResponse(command.listCuratedPhotos(page, 30, "latest"), listener) } internal fun getPhotoDetail(id: String, listener: DataSource.Callback<PicDetailEntity>) { if (!isNetworkAvailable(BaseApplication.getApplication())) { listener.onDataError(2) return } val command = RetrofitManager.remount(UNSPLASH_API) rxResponse(command.getPhotoDetail(id), listener) } internal fun getRelatedPhotos(id: String): Observable<PicRelatedEntity> { // if (!isNetworkAvailable(BaseApplication.getApplication())) { // listener.onDataError(2) // return // } return RetrofitManager.remount(UNSPLASH_WEB) .getRelatedPhotos(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } private fun <T> rxResponse(observable: Observable<T>, callback: DataSource.Callback<T>) { observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : Observer<T> { override fun onComplete() { } override fun onSubscribe(d: Disposable) { } override fun onNext(t: T) { callback.onDataLoaded(t) } override fun onError(e: Throwable) { callback.onDataError(1) } }) }
0
Kotlin
0
4
d01264e7a5fae74c13655a742bed79de674527d0
2,429
Pics
Apache License 2.0