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
weather/src/main/java/ru/androidpiraters/aiweather/presentation/WeatherItemComparator.kt
Luckyss
135,089,769
false
{"Kotlin": 111674}
package ru.androidpiraters.aiweather.presentation import ru.androidpirates.aiweather.presentation.recyclerview.DisplayableItem import ru.androidpirates.aiweather.presentation.recyclerview.ItemComparator class WeatherItemComparator : ItemComparator { override fun areItemsTheSame( item1: DisplayableItem<Any>, item2: DisplayableItem<Any> ): Boolean { return item1.model == item2.model } override fun areContentsTheSame( item1: DisplayableItem<Any>, item2: DisplayableItem<Any> ): Boolean { return item1.model == item2.model } }
0
Kotlin
0
0
e1f4e39a153de104f5983b48b478ae751feaa36d
618
aiweather
Apache License 2.0
blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/user/UserServiceIntegrationTest.kt
rubvardanyan
93,776,768
true
{"Kotlin": 36902}
package com.excref.kotblog.blog.service.user import com.excref.kotblog.blog.service.test.AbstractServiceIntegrationTest import com.excref.kotblog.blog.service.user.domain.UserRole import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration /** * @author Arthur Asatryan * @since 6/8/17 1:21 AM */ @EnableAutoConfiguration class UserServiceIntegrationTest : AbstractServiceIntegrationTest() { //region Dependencies @Autowired private lateinit var userService: UserService //endregion //region Test methods @Test fun testCreate() { // given val email = "biacoder@gmail.com" val password = "you can't even guess me! :P" val role = UserRole.BLOGGER // when val result = userService.create(email, password, role) // then assertThat(result).isNotNull().extracting("email", "password", "role").containsOnly(email, password, role) } @Test fun testExistsForEmail() { // given val email = "biacoder@gmail.com" helper.persistUser(email = email) // when val existsForEmail = userService.existsForEmail(email) assertThat(existsForEmail).isTrue() } //endregion }
0
Kotlin
0
0
e9c752d7e7248223ff2b4ba53f54388ce25fd7cc
1,360
kotblog
Apache License 2.0
modules/wasm-binary/src/commonMain/kotlin/visitors/ExceptionSectionVisitor.kt
wasmium
761,480,110
false
{"Kotlin": 352107, "JavaScript": 200}
package org.wasmium.wasm.binary.visitors import org.wasmium.wasm.binary.tree.WasmType public interface ExceptionSectionVisitor { public fun visitExceptionType(exceptionIndex: UInt, types: Array<WasmType>) public fun visitEnd() }
0
Kotlin
0
1
f7ddef76630278616d221e7c8251adf0f11b9587
240
wasmium-wasm-binary
Apache License 2.0
minecraft/src/test/kotlin/tests/minecraft/Location.kt
MineKing9534
871,916,804
false
{"Kotlin": 126964}
package tests.minecraft import de.mineking.database.* import de.mineking.database.vendors.PostgresConnection import de.mineking.database.vendors.PostgresMappers import org.bukkit.Location import org.bukkit.World import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import setup.ConsoleSqlLogger import setup.createServer import setup.createWorld import setup.recreate import java.util.* data class LocationDao( @AutoIncrement @Key @Column val id: Int = 0, @Column val location1: Location = Location(null, 0.0, 0.0, 0.0), @LocationWorldColumn(name = "worldTest") @Column val location2: Location = Location(null, 0.0, 0.0, 0.0), @Column(name = "world") val worldTest: World = createWorld() ) class LocationTest { val connection = PostgresConnection("localhost:5432/test", user = "test", password = "<PASSWORD>") val table: Table<LocationDao> val id1 = UUID.randomUUID() val id2 = UUID.randomUUID() val worlds = listOf( createWorld(id1), createWorld(id2) ) init { connection.registerMinecraftMappers(createServer(worlds = worlds), PostgresMappers.UUID_MAPPER, PostgresMappers.ARRAY, PostgresMappers.DOUBLE) table = connection.getTable(name = "location_test") { LocationDao() } table.recreate() table.insert(LocationDao(location1 = Location(worlds[0], 0.0, 5.0, 0.0), location2 = Location(null, 0.0, 0.0, 0.0), worldTest = worlds[1])) connection.driver.setSqlLogger(ConsoleSqlLogger) } @Test fun selectAll() { val result = table.select().list() assertEquals(result.size, 1) assertEquals(id1, result.first().location1.world.uid) assertEquals(id2, result.first().location2.world.uid) assertEquals(id2, result.first().worldTest.uid) } @Test fun coordinates() { assertEquals(1, table.selectRowCount(where = property("location1[0]") isEqualTo property("location1.x"))) assertEquals(0.0, table.select<Double>(property("location1.x")).first()) } @Test fun selectColumn() { assertEquals(Location(worlds[0], 0.0, 5.0, 0.0), table.select<Location>(property("location1")).first()) assertEquals(id1, table.select<World>(property("location1.world")).first().uid) assertEquals(id2, table.select<World>(property("worldTest")).first().uid) assertEquals(id2, table.select<World>(property("location2.world")).first().uid) } }
0
Kotlin
0
0
ebfd06cfb21c5d5697a28f2c6b09dc54ec1683c6
2,309
KORMite
MIT License
rtmp/src/main/java/com/pedro/rtmp/flv/video/H264Packet.kt
magiQAQ
374,279,754
true
{"Java": 842431, "Kotlin": 206016, "GLSL": 40954}
package com.pedro.rtmp.flv.video import android.media.MediaCodec import android.util.Log import com.pedro.rtmp.flv.FlvPacket import com.pedro.rtmp.flv.FlvType import java.nio.ByteBuffer import kotlin.experimental.and /** * Created by pedro on 8/04/21. * * ISO 14496-15 */ class H264Packet(private val videoPacketCallback: VideoPacketCallback) { private val TAG = "H264Packet" private val header = ByteArray(5) private val naluSize = 4 //first time we need send video config private var configSend = false private var sps: ByteArray? = null private var pps: ByteArray? = null var profileIop = ProfileIop.BASELINE enum class Type(val value: Byte) { SEQUENCE(0x00), NALU(0x01), EO_SEQ(0x02) } fun sendVideoInfo(sps: ByteBuffer, pps: ByteBuffer) { val mSps = removeHeader(sps) val mPps = removeHeader(pps) val spsBytes = ByteArray(mSps.remaining()) val ppsBytes = ByteArray(mPps.remaining()) mSps.get(spsBytes, 0, spsBytes.size) mPps.get(ppsBytes, 0, ppsBytes.size) this.sps = spsBytes this.pps = ppsBytes } // fun createFlvAudioPacket(byteBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { // byteBuffer.rewind() // val ts = info.presentationTimeUs / 1000 // //header is 5 bytes length: // //4 bits FrameType, 4 bits CodecID // //1 byte AVCPacketType // //3 bytes CompositionTime, the cts. // val cts = 0 // header[2] = (cts shr 16).toByte() // header[3] = (cts shr 8).toByte() // header[4] = cts.toByte() // // var buffer: ByteArray // if (!configSend) { // header[0] = ((VideoDataType.KEYFRAME.value shl 4) or VideoFormat.AVC.value).toByte() // header[1] = Type.SEQUENCE.value // // val sps = this.sps // val pps = this.pps // if (sps != null && pps != null) { // val config = VideoSpecificConfig(sps, pps, profileIop) // buffer = ByteArray(config.size + header.size) // config.write(buffer, header.size) // } else { // Log.e(TAG, "waiting for a valid sps and pps") // return // } // // System.arraycopy(header, 0, buffer, 0, header.size) // videoPacketCallback.onVideoFrameCreated(FlvPacket(buffer, ts, buffer.size, FlvType.VIDEO)) // configSend = true // } // if (configSend){ // val headerSize = getHeaderSize(byteBuffer) // if (headerSize == 0) return //invalid buffer or waiting for sps/pps // byteBuffer.rewind() // val validBuffer = removeHeader(byteBuffer, headerSize) // val size = validBuffer.remaining() // buffer = ByteArray(header.size + size + naluSize) // // val type: Int = (validBuffer.get(0) and 0x1F).toInt() // var nalType = VideoDataType.INTER_FRAME.value // if (type == VideoNalType.IDR.value || info.flags == MediaCodec.BUFFER_FLAG_KEY_FRAME) { // nalType = VideoDataType.KEYFRAME.value // } else if (type == VideoNalType.SPS.value || type == VideoNalType.PPS.value) { // // we don't need send it because we already do it in video config // return // } // header[0] = ((nalType shl 4) or VideoFormat.AVC.value).toByte() // header[1] = Type.NALU.value // writeNaluSize(buffer, header.size, size) // validBuffer.get(buffer, header.size + naluSize, size) // // System.arraycopy(header, 0, buffer, 0, header.size) // videoPacketCallback.onVideoFrameCreated(FlvPacket(buffer, ts, buffer.size, FlvType.VIDEO)) // } // } private fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() } private val seiContent = byteArrayOfInts( 0x06,0x05,0x21,0x6C,0x63,0x70,0x73,0x62,0x35,0x64,0x61,0x39, 0x66,0x34,0x36,0x35,0x64,0x33,0x66,0x01,0x0f,0x32,0x30,0x30,0x36,0x32,0x34,0x31, 0x34,0x31,0x35,0x33,0x30,0x31,0x32,0x33,0x80 ) fun createFlvVideoPacket(byteBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { byteBuffer.rewind() val ts = info.presentationTimeUs / 1000 //header is 5 bytes length: //4 bits FrameType, 4 bits CodecID //1 byte AVCPacketType //3 bytes CompositionTime, the cts. val cts = 0 header[2] = (cts shr 16).toByte() header[3] = (cts shr 8).toByte() header[4] = cts.toByte() var buffer: ByteArray if (!configSend) { header[0] = ((VideoDataType.KEYFRAME.value shl 4) or VideoFormat.AVC.value).toByte() header[1] = Type.SEQUENCE.value val sps = this.sps val pps = this.pps if (sps != null && pps != null) { val config = VideoSpecificConfig(sps, pps, profileIop) buffer = ByteArray(config.size + header.size) config.write(buffer, header.size) } else { Log.e(TAG, "waiting for a valid sps and pps") return } System.arraycopy(header, 0, buffer, 0, header.size) videoPacketCallback.onVideoFrameCreated(FlvPacket(buffer, ts, buffer.size, FlvType.VIDEO)) configSend = true } if (configSend){ val headerSize = getHeaderSize(byteBuffer) if (headerSize == 0) return //invalid buffer or waiting for sps/pps byteBuffer.rewind() val validBuffer = removeHeader(byteBuffer, headerSize) val size = validBuffer.remaining() buffer = ByteArray(header.size + seiContent.size + naluSize * 2 + size) val type: Int = (validBuffer.get(0) and 0x1F).toInt() var nalType = VideoDataType.INTER_FRAME.value if (type == VideoNalType.IDR.value || info.flags == MediaCodec.BUFFER_FLAG_KEY_FRAME) { nalType = VideoDataType.KEYFRAME.value } else if (type == VideoNalType.SPS.value || type == VideoNalType.PPS.value) { // we don't need send it because we already do it in video config return } header[0] = ((nalType shl 4) or VideoFormat.AVC.value).toByte() header[1] = Type.NALU.value // 写入sei的nalu尺寸 writeNaluSize(buffer, header.size, seiContent.size) // 写入sei信息 System.arraycopy(seiContent, 0, buffer, header.size + naluSize, seiContent.size) // 写入图像nalu的尺寸 writeNaluSize(buffer, header.size + naluSize + seiContent.size, size) // 复制nalu部分 validBuffer.get(buffer, header.size + naluSize + seiContent.size + naluSize, size) // 复制头部 System.arraycopy(header, 0, buffer, 0, header.size) // if (buffer.size > 60) { // val builder = StringBuilder() // builder.append(" \n") // for (i in 0..60) { // builder.append(Integer.toHexString(buffer[i].toInt() and 0xff)).append(" ") // if (i == 24) builder.append("\n") // } // Log.w(TAG, builder.toString()) // } videoPacketCallback.onVideoFrameCreated(FlvPacket(buffer, ts, buffer.size, FlvType.VIDEO)) } } //naluSize = UInt32 private fun writeNaluSize(buffer: ByteArray, offset: Int, size: Int) { buffer[offset] = (size ushr 24).toByte() buffer[offset + 1] = (size ushr 16).toByte() buffer[offset + 2] = (size ushr 8).toByte() buffer[offset + 3] = size.toByte() } private fun removeHeader(byteBuffer: ByteBuffer, size: Int = -1): ByteBuffer { val position = if (size == -1) getStartCodeSize(byteBuffer) else size byteBuffer.position(position) return byteBuffer.slice() } private fun getHeaderSize(byteBuffer: ByteBuffer): Int { if (byteBuffer.remaining() < 4) return 0 val sps = this.sps val pps = this.pps if (sps != null && pps != null) { val startCodeSize = getStartCodeSize(byteBuffer) if (startCodeSize == 0) return 0 val startCode = ByteArray(startCodeSize) { 0x00 } startCode[startCodeSize - 1] = 0x01 val avcHeader = startCode.plus(sps).plus(startCode).plus(pps).plus(startCode) if (byteBuffer.remaining() < avcHeader.size) return startCodeSize val possibleAvcHeader = ByteArray(avcHeader.size) byteBuffer.get(possibleAvcHeader, 0, possibleAvcHeader.size) return if (avcHeader.contentEquals(possibleAvcHeader)) { avcHeader.size } else { startCodeSize } } return 0 } private fun getStartCodeSize(byteBuffer: ByteBuffer): Int { var startCodeSize = 0 if (byteBuffer.get(0).toInt() == 0x00 && byteBuffer.get(1).toInt() == 0x00 && byteBuffer.get(2).toInt() == 0x00 && byteBuffer.get(3).toInt() == 0x01) { //match 00 00 00 01 startCodeSize = 4 } else if (byteBuffer.get(0).toInt() == 0x00 && byteBuffer.get(1).toInt() == 0x00 && byteBuffer.get(2).toInt() == 0x01) { //match 00 00 01 startCodeSize = 3 } return startCodeSize } fun reset(resetInfo: Boolean = true) { if (resetInfo) { sps = null pps = null } configSend = false } }
0
Java
0
0
3848d191a149484d2190d1c863e4b5d2f6265404
8,669
rtmp-rtsp-stream-client-java
Apache License 2.0
app/src/main/java/me/rerere/rainmusic/util/ConditionCheck.kt
re-ovo
414,157,893
false
{"Kotlin": 240173}
package me.rerere.rainmusic.util /** * 确保T是确定数值中的一员 * 某些函数的参数可能是确定的几个值,使用此函数确保参数在确定范围内 * * @receiver 要校验的值 * @param condition 该值的几种可能性 */ fun <T> T.requireOneOf(vararg condition: T) { require(condition.contains(this)) { "param must be one of: ${condition.joinToString(",")}" } }
0
Kotlin
4
71
d2d8c7508463123da5d7183116fab8926d72b079
301
RainMusic
MIT License
heroapp/src/main/java/com/preachooda/heroapp/section/patrolling/viewModel/PatrollingViewModel.kt
Ko4eBHuK
768,244,174
false
{"Kotlin": 869239}
package com.preachooda.heroapp.section.patrolling.viewModel import androidx.lifecycle.viewModelScope import com.preachooda.assets.util.BaseViewModel import com.preachooda.assets.util.NetworkCallState import com.preachooda.assets.util.Status import com.preachooda.domain.model.Patrol import com.preachooda.heroapp.BuildConfig import com.preachooda.heroapp.section.patrolling.domain.PatrollingScreenIntent import com.preachooda.heroapp.section.patrolling.domain.PatrollingScreenState import com.preachooda.heroapp.section.patrolling.repository.PatrollingRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Date import javax.inject.Inject @HiltViewModel class PatrollingViewModel @Inject constructor( private val repository: PatrollingRepository ) : BaseViewModel<PatrollingScreenIntent, PatrollingScreenState>() { private val _screenState: MutableStateFlow<PatrollingScreenState> = MutableStateFlow(PatrollingScreenState()) override val screenState: StateFlow<PatrollingScreenState> = _screenState override fun processIntent(intent: PatrollingScreenIntent) { when (intent) { PatrollingScreenIntent.CloseError -> closeError() is PatrollingScreenIntent.ShowError -> showError(intent.message) PatrollingScreenIntent.CloseMessage -> closeMessage() PatrollingScreenIntent.Refresh -> loadPatrol() PatrollingScreenIntent.StartPatrolling -> startPatrolling() PatrollingScreenIntent.FinishPatrolling -> finishPatrolling() } } private fun closeError() { _screenState.value = _screenState.value.copy( isError = false ) } private fun showError(message: String) { _screenState.value = _screenState.value.copy( isError = true, message = message ) } private fun closeMessage() { _screenState.value = _screenState.value.copy( isMessage = false ) } fun loadPatrol() { viewModelScope.launch(Dispatchers.IO) { makeNetworkCallPatrol(repository.getPatrol()) } } private fun startPatrolling() { viewModelScope.launch(Dispatchers.IO) { val startedPatrol = _screenState.value.patrol?.copy( status = Patrol.Status.STARTED, actualStart = SimpleDateFormat(BuildConfig.DATE_COMMON_FORMAT).format(Date()) ) if (startedPatrol!= null) { makeNetworkCallPatrol(repository.updatePatrol(startedPatrol)) } else { _screenState.value = _screenState.value.copy( isError = true, message = "Данные о патруле не определены" ) } } } private fun finishPatrolling() { viewModelScope.launch(Dispatchers.IO) { val startedPatrol = _screenState.value.patrol?.copy( status = Patrol.Status.COMPLETED, actualEnd = SimpleDateFormat(BuildConfig.DATE_COMMON_FORMAT).format(Date()) ) if (startedPatrol!= null) { makeNetworkCallPatrol(repository.updatePatrol(startedPatrol)) } else { _screenState.value = _screenState.value.copy( isError = true, message = "Данные о патруле не определены" ) } } } private fun <T : NetworkCallState<Patrol?>> makeNetworkCallPatrol( networkFlow: Flow<T> ) { viewModelScope.launch(Dispatchers.IO) { networkFlow.collect { when (it.status) { Status.SUCCESS -> { _screenState.value = _screenState.value.copy( isLoading = false, patrol = it.data ) } Status.ERROR -> { _screenState.value = _screenState.value.copy( isLoading = false, isError = true, message = it.message ) } Status.LOADING -> { _screenState.value = _screenState.value.copy( isLoading = true, message = it.message ) } } } } } }
0
Kotlin
0
0
8c7051c9000bd132e27be0ce786a6881661791ce
4,741
BokuNoHeroServiceApps
The Unlicense
config/src/test/kotlin/org/springframework/security/config/annotation/web/oauth2/login/UserInfoEndpointDslTests.kt
spring-projects
3,148,979
false
null
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.web.servlet.oauth2.login import io.mockk.every import io.mockk.mockkObject import io.mockk.verify import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.config.web.servlet.invoke import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository import org.springframework.security.oauth2.core.OAuth2AccessToken import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get /** * Tests for [TokenEndpointDsl] * * @author <NAME> */ @ExtendWith(SpringTestContextExtension::class) class TokenEndpointDslTests { @JvmField val spring = SpringTestContext(this) @Autowired lateinit var mockMvc: MockMvc @Test fun `oauth2Login when custom access token response client then client used`() { this.spring.register(TokenConfig::class.java, ClientConfig::class.java).autowire() mockkObject(TokenConfig.REPOSITORY) mockkObject(TokenConfig.CLIENT) val registrationId = "registrationId" val attributes = HashMap<String, Any>() attributes[OAuth2ParameterNames.REGISTRATION_ID] = registrationId val authorizationRequest = OAuth2AuthorizationRequest .authorizationCode() .state("test") .clientId("clientId") .authorizationUri("https://test") .redirectUri("http://localhost/login/oauth2/code/google") .attributes(attributes) .build() every { TokenConfig.REPOSITORY.removeAuthorizationRequest(any(), any()) } returns authorizationRequest every { TokenConfig.CLIENT.getTokenResponse(any()) } returns OAuth2AccessTokenResponse .withToken("token") .tokenType(OAuth2AccessToken.TokenType.BEARER) .build() this.mockMvc.get("/login/oauth2/code/google") { param("code", "auth-code") param("state", "test") } verify(exactly = 1) { TokenConfig.CLIENT.getTokenResponse(any()) } } @EnableWebSecurity open class TokenConfig : WebSecurityConfigurerAdapter() { companion object { val REPOSITORY: AuthorizationRequestRepository<OAuth2AuthorizationRequest> = HttpSessionOAuth2AuthorizationRequestRepository() val CLIENT: OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> = OAuth2AccessTokenResponseClient { OAuth2AccessTokenResponse.withToken("some tokenValue").build() } } override fun configure(http: HttpSecurity) { http { authorizeRequests { authorize(anyRequest, authenticated) } oauth2Login { tokenEndpoint { accessTokenResponseClient = CLIENT } authorizationEndpoint { authorizationRequestRepository = REPOSITORY } } } } } @Configuration open class ClientConfig { @Bean open fun clientRegistrationRepository(): ClientRegistrationRepository { return InMemoryClientRegistrationRepository( CommonOAuth2Provider.GOOGLE .getBuilder("google") .registrationId("registrationId") .clientId("clientId") .clientSecret("clientSecret") .build() ) } } }
961
null
5864
8,737
9ba2435cb21a828dd2bccaabcac63dabf12d5dc8
5,748
spring-security
Apache License 2.0
domain/usecase/src/main/kotlin/it/battagliandrea/formula1/domain/usecase/GetCurrentLastResultUseCase.kt
battagliandrea
708,330,176
false
{"Kotlin": 69787, "Shell": 1093}
package it.battagliandrea.formula1.domain.usecase import it.battagliandrea.formula1.data.results.api.repository.IResultsRepository import it.battagliandrea.formula1.domain.models.QueryResult import it.battagliandrea.formula1.domain.models.Race import it.battagliandrea.formula1.domain.usecase.GetCurrentLastResultUseCase.Params import it.battagliandrea.formula1.domain.usecase.internal.FlowUseCase import kotlinx.coroutines.flow.Flow import javax.inject.Inject class GetCurrentLastResultUseCase @Inject constructor( private val resultsRepository: IResultsRepository, ) : FlowUseCase<Params, Flow<QueryResult<List<Race>>>> { object Params override fun execute( params: Params, onStart: () -> Unit, onComplete: () -> Unit, onError: (String?) -> Unit, ): Flow<QueryResult<List<Race>>> = resultsRepository.getCurrentLastResult( onStart = onStart, onComplete = onComplete, onError = onError, ) }
5
Kotlin
0
0
acb9141d28ad9890eb0e4da76b22f26d5d76ae56
995
Fomula1
Apache License 2.0
hmf-id-generator/src/main/kotlin/com/hartwig/hmftools/idgenerator/anonymizedIds/HashId.kt
jiaan-yu
171,220,496
true
{"XML": 35, "Maven POM": 30, "Markdown": 13, "Git Attributes": 1, "Text": 22, "Ignore List": 1, "Java": 1078, "SQL": 34, "Shell": 1, "Kotlin": 233, "R": 3, "JSON": 1}
package com.hartwig.hmftools.idgenerator.anonymizedIds import com.hartwig.hmftools.idgenerator.Hash data class HashId(override val hash: Hash, override val id: Int) : AnonymizedId { companion object { operator fun invoke(hashString: String, id: Int) = HashId(Hash(hashString), id) } }
0
Java
0
0
f619e02cdb166594e7dd4d7d1dd7fe8592267f2d
303
hmftools
MIT License
unlockable/core-common/src/test/kotlin/com/rarible/protocol/unlockable/util/SignUtilTest.kt
NFTDroppr
418,665,809
true
{"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547}
package com.rarible.protocol.unlockable.util import com.rarible.ethereum.common.generateNewKeys import com.rarible.ethereum.common.toBinary import com.rarible.ethereum.domain.EthUInt256 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.web3j.crypto.Sign import scalether.domain.Address internal class SignUtilTest { @Test fun `should recover the signed message`() { val (privateKey, publicKey, ownerAddress) = generateNewKeys() val signature = Sign.signMessage( SignUtil.addStart( LockMessageUtil.getLockMessage( Address.ONE(), EthUInt256.TEN, "ipfs://content" ) ).bytes(), publicKey, privateKey ).toBinary() val signer = SignUtil.recover( LockMessageUtil.getLockMessage( Address.ONE(), EthUInt256.TEN, "ipfs://content" ), signature ) Assertions.assertEquals(ownerAddress, signer) } }
0
Kotlin
0
1
b1efdaceab8be95429befe80ce1092fab3004d18
1,085
ethereum-indexer
MIT License
application-model/src/test/kotlin/pl/beone/promena/transformer/barcodedetector/zxingopencv/applicationmodel/support/ZxingOpenCvBarcodeDetectorMediaTypeSupportTest.kt
BeOne-PL
235,078,126
false
null
package pl.beone.promena.transformer.barcodedetector.zxingopencv.applicationmodel.support import io.kotlintest.shouldNotThrow import io.kotlintest.shouldThrow import org.junit.jupiter.api.Test import pl.beone.promena.transformer.applicationmodel.exception.transformer.TransformationNotSupportedException import pl.beone.promena.transformer.applicationmodel.mediatype.MediaTypeConstants.APPLICATION_PDF import pl.beone.promena.transformer.applicationmodel.mediatype.MediaTypeConstants.TEXT_PLAIN import pl.beone.promena.transformer.barcodedetector.zxingopencv.applicationmodel.ZxingOpenCvBarcodeDetectorSupport.MediaTypeSupport.isSupported class ZxingOpenCvBarcodeDetectorMediaTypeSupportTest { @Test fun isSupported() { shouldNotThrow<TransformationNotSupportedException> { isSupported(APPLICATION_PDF, APPLICATION_PDF) } } @Test fun `isSupported _ media type is not supported _ should throw TransformationNotSupportedException`() { shouldThrow<TransformationNotSupportedException> { isSupported(APPLICATION_PDF, TEXT_PLAIN) } } @Test fun `isSupported _ target media type is not supported _ should throw TransformationNotSupportedException`() { shouldThrow<TransformationNotSupportedException> { isSupported(TEXT_PLAIN, APPLICATION_PDF) } } }
1
null
1
1
3aa2e278563b3b580639f3bcefc44d6696e56cd3
1,367
promena-transformer-barcode-detector-zxing-opencv
Apache License 2.0
features/search/src/test/java/com/lcabral/catsbyme/features/search/StubsSearch.kt
LucianaCabral
745,895,275
false
{"Kotlin": 66172}
package com.lcabral.catsbyme.features.search import com.lcabral.catsbyme.features.search.domain.model.Search internal object StubsSearch { fun searchBreeds(): List<Search> { return listOf( Search( id = "adsfs", name = "Siamese", referenceImageId = "jpg" ) ) } }
0
Kotlin
0
0
374b1a31b67b8eb14b3d92006b985c77bf058c94
359
Catsbyme
MIT License
core/src/main/kotlin/com/sbgapps/scoreit/core/utils/string/StringFactory.kt
StephaneBg
16,022,770
false
null
/* * Copyright 2019 <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 com.sbgapps.scoreit.core.utils.string sealed class StringFactory data class Pure(val s: String) : StringFactory() data class FromResources(val id: Int, val args: List<StringFactory>) : StringFactory() data class FromQuantityResources(val id: Int, val quantity: Int, val args: List<StringFactory>) : StringFactory() data class Concat(val parts: List<StringFactory>) : StringFactory()
1
null
11
37
7684d40c56c3293b1e9b06158efcbefa51693f7a
980
ScoreIt
Apache License 2.0
app/src/main/java/com/innovara/autoseers/onboarding/ui/PhoneAuthenticationScreen.kt
Autoseer-Org
821,653,056
false
{"Kotlin": 214370}
package com.innovara.autoseers.onboarding.ui import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.innovara.autoseers.AuthState import com.innovara.autoseers.R import com.innovara.autoseers.onboarding.logic.OnboardingEvents import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun PhoneAuthenticationScreen( modifier: Modifier = Modifier, onPhoneNumberEntered: (String) -> Unit, onBackPressed: () -> Unit, onPhoneAuthEvents: (OnboardingEvents) -> Unit, authState: AuthState, ) { var phoneNumber by remember { mutableStateOf("") } val interactionSource = remember { MutableInteractionSource() } val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() val focusManager = LocalFocusManager.current LaunchedEffect(key1 = authState) { when (authState) { is AuthState.PhoneVerificationInProgress -> { scope.launch { if (authState.error) { snackbarHostState.showSnackbar(authState.errorMessage ?: "") } } } else -> Unit } } Scaffold( modifier, topBar = { TopAppBar(title = { }, navigationIcon = { IconButton(onClick = onBackPressed) { Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "") } }) }, snackbarHost = { SnackbarHost(hostState = snackbarHostState) }) { Column( modifier = Modifier .padding(it) .padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { Text(text = "Sign up", style = MaterialTheme.typography.headlineLarge) Text(text = stringResource(id = R.string.sign_up_long_message)) TextField( modifier = Modifier .padding(vertical = 12.dp) .fillMaxWidth(), value = phoneNumber, onValueChange = { phoneNumber = it }, label = { Text(text = "Phone number") }, prefix = { Text(text = "+1") }, supportingText = { Text(text = stringResource(id = R.string.support_text_message)) }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Phone, imeAction = ImeAction.Done, autoCorrectEnabled = false, showKeyboardOnFocus = true, ), keyboardActions = KeyboardActions( onDone = { this.defaultKeyboardAction(imeAction = ImeAction.Done) } ), interactionSource = interactionSource, ) Button( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 26.dp), onClick = { onPhoneNumberEntered("+1$phoneNumber") focusManager.clearFocus(true) onPhoneAuthEvents.invoke(OnboardingEvents.PhoneNumberEntered) }) { Text(text = "Continue") } } } }
1
Kotlin
0
2
d5a8a6d3bfc8215716544d37792230f796728053
5,112
autoseers
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/BerOmInntektsmeldingTest.kt
navikt
193,907,367
false
null
package no.nav.helse.spleis.e2e import no.nav.helse.februar import no.nav.helse.hendelser.Periode import no.nav.helse.hendelser.Sykmeldingsperiode import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom import no.nav.helse.hendelser.til import no.nav.helse.januar import no.nav.helse.mars import no.nav.helse.person.PersonObserver import no.nav.helse.person.TilstandType.AVSLUTTET_UTEN_UTBETALING import no.nav.helse.person.TilstandType.AVVENTER_BLOKKERENDE_PERIODE import no.nav.helse.person.TilstandType.AVVENTER_GODKJENNING import no.nav.helse.person.TilstandType.AVVENTER_INFOTRYGDHISTORIKK import no.nav.helse.person.TilstandType.AVVENTER_INNTEKTSMELDING import no.nav.helse.person.TilstandType.AVVENTER_VILKÅRSPRØVING import no.nav.helse.person.TilstandType.START import no.nav.helse.økonomi.Prosentdel.Companion.prosent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test internal class BerOmInntektsmeldingTest : AbstractEndToEndTest() { @Test fun `Ber ikke om inntektsmelding på korte perioder`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 15.januar)) håndterSøknad(Sykdom(1.januar, 15.januar, 100.prosent)) assertIngenFunksjonelleFeil() assertTilstander(1.vedtaksperiode, START, AVVENTER_INFOTRYGDHISTORIKK, AVVENTER_INNTEKTSMELDING, AVSLUTTET_UTEN_UTBETALING) assertEquals(0, observatør.manglendeInntektsmeldingVedtaksperioder.size) } @Test fun `Ber ikke om inntektsmelding på korte perioder med uferdige periode hos annen ag`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar), orgnummer = a1) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(listOf(1.januar til 16.januar), orgnummer = a1,) håndterVilkårsgrunnlag(1.vedtaksperiode, orgnummer = a1) håndterYtelser(1.vedtaksperiode, orgnummer = a1) håndterSimulering(1.vedtaksperiode, orgnummer = a1) håndterSykmelding(Sykmeldingsperiode(1.mars, 15.mars), orgnummer = a2) val søknadId = håndterSøknad(Sykdom(1.mars, 15.mars, 100.prosent), orgnummer = a2) assertSisteTilstand(1.vedtaksperiode, AVVENTER_GODKJENNING, orgnummer = a1) assertTilstander(1.vedtaksperiode, START, AVVENTER_INNTEKTSMELDING, AVSLUTTET_UTEN_UTBETALING, orgnummer = a2) assertEquals(1, observatør.manglendeInntektsmeldingVedtaksperioder.size) assertTrue(observatør.manglendeInntektsmeldingVedtaksperioder.none { event -> søknadId in event.søknadIder }) } @Test fun `Ber om inntektsmelding når vi ankommer AvventerInntektsmelding`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar)) val søknadId = håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) assertIngenFunksjonelleFeil() assertTilstander( 1.vedtaksperiode, START, AVVENTER_INFOTRYGDHISTORIKK, AVVENTER_INNTEKTSMELDING, ) assertEquals(1, observatør.manglendeInntektsmeldingVedtaksperioder.size) assertEquals( PersonObserver.ManglendeInntektsmeldingEvent( fødselsnummer = UNG_PERSON_FNR_2018.toString(), aktørId = AKTØRID, organisasjonsnummer = ORGNUMMER, vedtaksperiodeId = 1.vedtaksperiode.id(ORGNUMMER), fom = 1.januar, tom = 31.januar, søknadIder = setOf(søknadId) ), observatør.manglendeInntektsmeldingVedtaksperioder.single() ) } @Test fun `Ber ikke om inntektsmelding ved forlengelser`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar)) val søknadId1 = håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar)) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent)) assertIngenFunksjonelleFeil() assertTilstander(1.vedtaksperiode, START, AVVENTER_INFOTRYGDHISTORIKK, AVVENTER_INNTEKTSMELDING) assertTilstander(2.vedtaksperiode, START, AVVENTER_INNTEKTSMELDING) assertEquals(1, observatør.manglendeInntektsmeldingVedtaksperioder.size) assertEquals( PersonObserver.ManglendeInntektsmeldingEvent( fødselsnummer = UNG_PERSON_FNR_2018.toString(), aktørId = AKTØRID, organisasjonsnummer = ORGNUMMER, vedtaksperiodeId = 1.vedtaksperiode.id(ORGNUMMER), fom = 1.januar, tom = 31.januar, søknadIder = setOf(søknadId1) ), observatør.manglendeInntektsmeldingVedtaksperioder.single() ) } @Test fun `Sender ut event om at vi ikke trenger inntektsmelding når vi forlater AvventerInntektsmelding`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(Periode(1.januar, 16.januar)),) assertTilstander( 1.vedtaksperiode, START, AVVENTER_INFOTRYGDHISTORIKK, AVVENTER_INNTEKTSMELDING, AVVENTER_BLOKKERENDE_PERIODE, AVVENTER_VILKÅRSPRØVING ) assertEquals(1, observatør.trengerIkkeInntektsmeldingVedtaksperioder.size) } @Test fun `Send event om at vi ikke trenger inntektsmelding når vi forlater AvventerInntektsmelding`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar)) håndterSykmelding(Sykmeldingsperiode(2.februar, 28.februar)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(2.februar, 28.februar, 100.prosent)) håndterInntektsmelding(listOf(Periode(1.januar, 16.januar)), 2.februar,) assertTilstander( 2.vedtaksperiode, START, AVVENTER_INNTEKTSMELDING, AVVENTER_BLOKKERENDE_PERIODE, ) assertEquals(1, observatør.trengerIkkeInntektsmeldingVedtaksperioder.size) } }
2
null
7
5
314d8a6e32b3dda391bcac31e0b4aeeee68f9f9b
6,186
helse-spleis
MIT License
app/src/main/java/com/project/farmingapp/viewmodel/UserDataViewModel.kt
hetsuthar028
325,234,399
false
null
package com.project.farmingapp.viewmodel import android.content.Context import android.util.Log import android.widget.Toast import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.project.farmingapp.R import com.project.farmingapp.view.user.UserFragment import kotlinx.android.synthetic.main.fragment_user.* import kotlinx.android.synthetic.main.nav_header.view.* import kotlinx.coroutines.channels.consumesAll class UserDataViewModel : ViewModel() { var userliveData = MutableLiveData<DocumentSnapshot>() fun getUserData(userId: String) { val firebaseFireStore = FirebaseFirestore.getInstance() firebaseFireStore.collection("users").document(userId) .get() .addOnCompleteListener { userliveData.value = it.result } } fun updateUserField(context: Context, userID: String, about: String?, city: String?) { if (about !=null) { val firebaseFireStore = FirebaseFirestore.getInstance() firebaseFireStore.collection("users").document("${userID}") .update( mapOf( "about" to about ) ) .addOnSuccessListener { Log.d("UserDataViewModel", "User About Data Updated") getUserData(userID) } .addOnFailureListener { Log.d("UserDataViewModel", "Failed to Update About User Data") Toast.makeText(context, "Failed to Update About. Try Again!", Toast.LENGTH_SHORT).show() } } if (city !=null) { val firebaseFireStore = FirebaseFirestore.getInstance() firebaseFireStore.collection("users").document("${userID}") .update( mapOf( "city" to city ) ) .addOnSuccessListener { Log.d("UserDataViewModel", "User City Data Updated") getUserData(userID) } .addOnFailureListener { Log.d("UserDataViewModel", "Failed to Update City User Data") Toast.makeText(context, "Failed to Update City Try Again!", Toast.LENGTH_SHORT).show() } } Toast.makeText(context, "Profile Updated", Toast.LENGTH_SHORT).show() } fun deleteUserPost(userId: String, postId: String){ val firebaseFirestore = FirebaseFirestore.getInstance() firebaseFirestore.collection("posts").document(postId) .delete() .addOnSuccessListener { Log.d("User Data View Model", "Post Deleted") UserProfilePostsViewModel().getAllPosts(userId) firebaseFirestore.collection("users").document(userId).update("posts", FieldValue.arrayRemove("${postId}")) .addOnSuccessListener { Log.d("UserDataViewModel", "Successfully Deleted User Doc Post") getUserData(userId) } .addOnFailureListener{ Log.e("UserDataViewModel", "Failed to delete post from User Doc") } } .addOnFailureListener { Log.d("User Data View Model", "Failed to delete post") } } }
9
Kotlin
25
58
53cf61fe4158db356d1c7741065820deea7104ce
3,619
Farming-App
MIT License
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/domain/validations/setup/SetupStakingValidationFailure.kt
novasamatech
415,834,480
false
null
package io.novafoundation.nova.feature_staking_impl.domain.validations.setup import java.math.BigDecimal sealed class SetupStakingValidationFailure { object CannotPayFee : SetupStakingValidationFailure() object NotEnoughStakeable : SetupStakingValidationFailure() class AmountLessThanAllowed(val threshold: BigDecimal) : SetupStakingValidationFailure() class AmountLessThanRecommended(val threshold: BigDecimal) : SetupStakingValidationFailure() object MaxNominatorsReached : SetupStakingValidationFailure() }
9
Kotlin
3
5
67bd23703276cdc1b804919d0baa679ada28db7f
537
nova-wallet-android
Apache License 2.0
compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/Effects.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime import androidx.compose.runtime.internal.PlatformOptimizedCancellationException import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.launch /** * Schedule [effect] to run when the current composition completes successfully and applies changes. * [SideEffect] can be used to apply side effects to objects managed by the composition that are not * backed by [snapshots][androidx.compose.runtime.snapshots.Snapshot] so as not to leave those * objects in an inconsistent state if the current composition operation fails. * * [effect] will always be run on the composition's apply dispatcher and appliers are never run * concurrent with themselves, one another, applying changes to the composition tree, or running * [RememberObserver] event callbacks. [SideEffect]s are always run after [RememberObserver] event * callbacks. * * A [SideEffect] runs after **every** recomposition. To launch an ongoing task spanning potentially * many recompositions, see [LaunchedEffect]. To manage an event subscription or other object * lifecycle, see [DisposableEffect]. */ @Composable @NonRestartableComposable @ExplicitGroupsComposable @OptIn(InternalComposeApi::class) fun SideEffect(effect: () -> Unit) { currentComposer.recordSideEffect(effect) } /** * Receiver scope for [DisposableEffect] that offers the [onDispose] clause that should be the last * statement in any call to [DisposableEffect]. */ class DisposableEffectScope { /** * Provide [onDisposeEffect] to the [DisposableEffect] to run when it leaves the composition or * its key changes. */ inline fun onDispose(crossinline onDisposeEffect: () -> Unit): DisposableEffectResult = object : DisposableEffectResult { override fun dispose() { onDisposeEffect() } } } interface DisposableEffectResult { fun dispose() } private val InternalDisposableEffectScope = DisposableEffectScope() private class DisposableEffectImpl( private val effect: DisposableEffectScope.() -> DisposableEffectResult ) : RememberObserver { private var onDispose: DisposableEffectResult? = null override fun onRemembered() { onDispose = InternalDisposableEffectScope.effect() } override fun onForgotten() { onDispose?.dispose() onDispose = null } override fun onAbandoned() { // Nothing to do as [onRemembered] was not called. } } private const val DisposableEffectNoParamError = "DisposableEffect must provide one or more 'key' parameters that define the identity of " + "the DisposableEffect and determine when its previous effect should be disposed and " + "a new effect started for the new key." private const val LaunchedEffectNoParamError = "LaunchedEffect must provide one or more 'key' parameters that define the identity of " + "the LaunchedEffect and determine when its previous effect coroutine should be cancelled " + "and a new effect launched for the new key." /** * A side effect of composition that must be reversed or cleaned up if the [DisposableEffect] leaves * the composition. * * It is an error to call [DisposableEffect] without at least one `key` parameter. */ // This deprecated-error function shadows the varargs overload so that the varargs version // is not used without key parameters. @Composable @NonRestartableComposable @Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER") @Deprecated(DisposableEffectNoParamError, level = DeprecationLevel.ERROR) fun DisposableEffect(effect: DisposableEffectScope.() -> DisposableEffectResult): Unit = error(DisposableEffectNoParamError) /** * A side effect of composition that must run for any new unique value of [key1] and must be * reversed or cleaned up if [key1] changes or if the [DisposableEffect] leaves the composition. * * A [DisposableEffect]'s _key_ is a value that defines the identity of the [DisposableEffect]. If a * key changes, the [DisposableEffect] must [dispose][DisposableEffectScope.onDispose] its current * [effect] and reset by calling [effect] again. Examples of keys include: * * Observable objects that the effect subscribes to * * Unique request parameters to an operation that must cancel and retry if those parameters change * * [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize when a * different key is provided, performing cleanup for the old operation before initializing the new. * For example: * * @sample androidx.compose.runtime.samples.disposableEffectSample * * A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause as * the final statement in its [effect] block. If your operation does not require disposal it might * be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should be * managed by the composition. * * There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call * to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run on * the composition's apply dispatcher and appliers are never run concurrent with themselves, one * another, applying changes to the composition tree, or running [RememberObserver] event callbacks. */ @Composable @NonRestartableComposable fun DisposableEffect(key1: Any?, effect: DisposableEffectScope.() -> DisposableEffectResult) { remember(key1) { DisposableEffectImpl(effect) } } /** * A side effect of composition that must run for any new unique value of [key1] or [key2] and must * be reversed or cleaned up if [key1] or [key2] changes, or if the [DisposableEffect] leaves the * composition. * * A [DisposableEffect]'s _key_ is a value that defines the identity of the [DisposableEffect]. If a * key changes, the [DisposableEffect] must [dispose][DisposableEffectScope.onDispose] its current * [effect] and reset by calling [effect] again. Examples of keys include: * * Observable objects that the effect subscribes to * * Unique request parameters to an operation that must cancel and retry if those parameters change * * [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize when a * different key is provided, performing cleanup for the old operation before initializing the new. * For example: * * @sample androidx.compose.runtime.samples.disposableEffectSample * * A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause as * the final statement in its [effect] block. If your operation does not require disposal it might * be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should be * managed by the composition. * * There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call * to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run on * the composition's apply dispatcher and appliers are never run concurrent with themselves, one * another, applying changes to the composition tree, or running [RememberObserver] event callbacks. */ @Composable @NonRestartableComposable fun DisposableEffect( key1: Any?, key2: Any?, effect: DisposableEffectScope.() -> DisposableEffectResult ) { remember(key1, key2) { DisposableEffectImpl(effect) } } /** * A side effect of composition that must run for any new unique value of [key1], [key2] or [key3] * and must be reversed or cleaned up if [key1], [key2] or [key3] changes, or if the * [DisposableEffect] leaves the composition. * * A [DisposableEffect]'s _key_ is a value that defines the identity of the [DisposableEffect]. If a * key changes, the [DisposableEffect] must [dispose][DisposableEffectScope.onDispose] its current * [effect] and reset by calling [effect] again. Examples of keys include: * * Observable objects that the effect subscribes to * * Unique request parameters to an operation that must cancel and retry if those parameters change * * [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize when a * different key is provided, performing cleanup for the old operation before initializing the new. * For example: * * @sample androidx.compose.runtime.samples.disposableEffectSample * * A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause as * the final statement in its [effect] block. If your operation does not require disposal it might * be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should be * managed by the composition. * * There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call * to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run on * the composition's apply dispatcher and appliers are never run concurrent with themselves, one * another, applying changes to the composition tree, or running [RememberObserver] event callbacks. */ @Composable @NonRestartableComposable fun DisposableEffect( key1: Any?, key2: Any?, key3: Any?, effect: DisposableEffectScope.() -> DisposableEffectResult ) { remember(key1, key2, key3) { DisposableEffectImpl(effect) } } /** * A side effect of composition that must run for any new unique value of [keys] and must be * reversed or cleaned up if any [keys] change or if the [DisposableEffect] leaves the composition. * * A [DisposableEffect]'s _key_ is a value that defines the identity of the [DisposableEffect]. If a * key changes, the [DisposableEffect] must [dispose][DisposableEffectScope.onDispose] its current * [effect] and reset by calling [effect] again. Examples of keys include: * * Observable objects that the effect subscribes to * * Unique request parameters to an operation that must cancel and retry if those parameters change * * [DisposableEffect] may be used to initialize or subscribe to a key and reinitialize when a * different key is provided, performing cleanup for the old operation before initializing the new. * For example: * * @sample androidx.compose.runtime.samples.disposableEffectSample * * A [DisposableEffect] **must** include an [onDispose][DisposableEffectScope.onDispose] clause as * the final statement in its [effect] block. If your operation does not require disposal it might * be a [SideEffect] instead, or a [LaunchedEffect] if it launches a coroutine that should be * managed by the composition. * * There is guaranteed to be one call to [dispose][DisposableEffectScope.onDispose] for every call * to [effect]. Both [effect] and [dispose][DisposableEffectScope.onDispose] will always be run on * the composition's apply dispatcher and appliers are never run concurrent with themselves, one * another, applying changes to the composition tree, or running [RememberObserver] event callbacks. */ @Composable @NonRestartableComposable @Suppress("ArrayReturn") fun DisposableEffect( vararg keys: Any?, effect: DisposableEffectScope.() -> DisposableEffectResult ) { remember(*keys) { DisposableEffectImpl(effect) } } internal class LaunchedEffectImpl( parentCoroutineContext: CoroutineContext, private val task: suspend CoroutineScope.() -> Unit ) : RememberObserver { private val scope = CoroutineScope(parentCoroutineContext) private var job: Job? = null override fun onRemembered() { // This should never happen but is left here for safety job?.cancel("Old job was still running!") job = scope.launch(block = task) } override fun onForgotten() { job?.cancel(LeftCompositionCancellationException()) job = null } override fun onAbandoned() { job?.cancel(LeftCompositionCancellationException()) job = null } } /** * When [LaunchedEffect] enters the composition it will launch [block] into the composition's * [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] when the [LaunchedEffect] * leaves the composition. * * It is an error to call [LaunchedEffect] without at least one `key` parameter. */ // This deprecated-error function shadows the varargs overload so that the varargs version // is not used without key parameters. @Deprecated(LaunchedEffectNoParamError, level = DeprecationLevel.ERROR) @Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER") @Composable fun LaunchedEffect(block: suspend CoroutineScope.() -> Unit): Unit = error(LaunchedEffectNoParamError) /** * When [LaunchedEffect] enters the composition it will launch [block] into the composition's * [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when * [LaunchedEffect] is recomposed with a different [key1]. The coroutine will be * [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition. * * This function should **not** be used to (re-)launch ongoing tasks in response to callback events * by way of storing callback data in [MutableState] passed to [key1]. Instead, see * [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs * scoped to the composition in response to event callbacks. */ @Composable @NonRestartableComposable @OptIn(InternalComposeApi::class) fun LaunchedEffect(key1: Any?, block: suspend CoroutineScope.() -> Unit) { val applyContext = currentComposer.applyCoroutineContext remember(key1) { LaunchedEffectImpl(applyContext, block) } } /** * When [LaunchedEffect] enters the composition it will launch [block] into the composition's * [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when * [LaunchedEffect] is recomposed with a different [key1] or [key2]. The coroutine will be * [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition. * * This function should **not** be used to (re-)launch ongoing tasks in response to callback events * by way of storing callback data in [MutableState] passed to [key]. Instead, see * [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs * scoped to the composition in response to event callbacks. */ @Composable @NonRestartableComposable @OptIn(InternalComposeApi::class) fun LaunchedEffect(key1: Any?, key2: Any?, block: suspend CoroutineScope.() -> Unit) { val applyContext = currentComposer.applyCoroutineContext remember(key1, key2) { LaunchedEffectImpl(applyContext, block) } } /** * When [LaunchedEffect] enters the composition it will launch [block] into the composition's * [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when * [LaunchedEffect] is recomposed with a different [key1], [key2] or [key3]. The coroutine will be * [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition. * * This function should **not** be used to (re-)launch ongoing tasks in response to callback events * by way of storing callback data in [MutableState] passed to [key]. Instead, see * [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs * scoped to the composition in response to event callbacks. */ @Composable @NonRestartableComposable @OptIn(InternalComposeApi::class) fun LaunchedEffect(key1: Any?, key2: Any?, key3: Any?, block: suspend CoroutineScope.() -> Unit) { val applyContext = currentComposer.applyCoroutineContext remember(key1, key2, key3) { LaunchedEffectImpl(applyContext, block) } } private class LeftCompositionCancellationException : PlatformOptimizedCancellationException("The coroutine scope left the composition") /** * When [LaunchedEffect] enters the composition it will launch [block] into the composition's * [CoroutineContext]. The coroutine will be [cancelled][Job.cancel] and **re-launched** when * [LaunchedEffect] is recomposed with any different [keys]. The coroutine will be * [cancelled][Job.cancel] when the [LaunchedEffect] leaves the composition. * * This function should **not** be used to (re-)launch ongoing tasks in response to callback events * by way of storing callback data in [MutableState] passed to [key]. Instead, see * [rememberCoroutineScope] to obtain a [CoroutineScope] that may be used to launch ongoing jobs * scoped to the composition in response to event callbacks. */ @Composable @NonRestartableComposable @Suppress("ArrayReturn") @OptIn(InternalComposeApi::class) fun LaunchedEffect(vararg keys: Any?, block: suspend CoroutineScope.() -> Unit) { val applyContext = currentComposer.applyCoroutineContext remember(*keys) { LaunchedEffectImpl(applyContext, block) } } // Maintenance note: this class once was used by the inlined implementation of // rememberCoroutineScope and must be maintained for binary compatibility. The new implementation // of RememberedCoroutineScope implements RememberObserver directly, since as of this writing the // compose runtime no longer implicitly treats objects incidentally stored in the slot table (e.g. // previous parameter values from a skippable invocation, remember keys, etc.) as eligible // RememberObservers. This dramatically reduces the risk of receiving unexpected RememberObserver // lifecycle callbacks when a reference to a RememberObserver is leaked into user code and we can // omit wrapper RememberObservers such as this one. @PublishedApi internal class CompositionScopedCoroutineScopeCanceller(val coroutineScope: CoroutineScope) : RememberObserver { override fun onRemembered() { // Nothing to do } override fun onForgotten() { val coroutineScope = coroutineScope if (coroutineScope is RememberedCoroutineScope) { coroutineScope.cancelIfCreated() } else { coroutineScope.cancel(LeftCompositionCancellationException()) } } override fun onAbandoned() { val coroutineScope = coroutineScope if (coroutineScope is RememberedCoroutineScope) { coroutineScope.cancelIfCreated() } else { coroutineScope.cancel(LeftCompositionCancellationException()) } } } internal expect class RememberedCoroutineScope( parentContext: CoroutineContext, overlayContext: CoroutineContext, ) : CoroutineScope, RememberObserver { fun cancelIfCreated() } @PublishedApi @OptIn(InternalComposeApi::class) internal fun createCompositionCoroutineScope( coroutineContext: CoroutineContext, composer: Composer ) = if (coroutineContext[Job] != null) { CoroutineScope( Job().apply { completeExceptionally( IllegalArgumentException( "CoroutineContext supplied to " + "rememberCoroutineScope may not include a parent job" ) ) } ) } else { val applyContext = composer.applyCoroutineContext RememberedCoroutineScope(applyContext, coroutineContext) } /** * Return a [CoroutineScope] bound to this point in the composition using the optional * [CoroutineContext] provided by [getContext]. [getContext] will only be called once and the same * [CoroutineScope] instance will be returned across recompositions. * * This scope will be [cancelled][CoroutineScope.cancel] when this call leaves the composition. The * [CoroutineContext] returned by [getContext] may not contain a [Job] as this scope is considered * to be a child of the composition. * * The default dispatcher of this scope if one is not provided by the context returned by * [getContext] will be the applying dispatcher of the composition's [Recomposer]. * * Use this scope to launch jobs in response to callback events such as clicks or other user * interaction where the response to that event needs to unfold over time and be cancelled if the * composable managing that process leaves the composition. Jobs should never be launched into * **any** coroutine scope as a side effect of composition itself. For scoped ongoing jobs initiated * by composition, see [LaunchedEffect]. * * This function will not throw if preconditions are not met, as composable functions do not yet * fully support exceptions. Instead the returned scope's [CoroutineScope.coroutineContext] will * contain a failed [Job] with the associated exception and will not be capable of launching child * jobs. */ @Composable inline fun rememberCoroutineScope( crossinline getContext: @DisallowComposableCalls () -> CoroutineContext = { EmptyCoroutineContext } ): CoroutineScope { val composer = currentComposer return remember { createCompositionCoroutineScope(getContext(), composer) } }
28
null
992
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
21,598
androidx
Apache License 2.0
app/src/main/java/com/adgvcxz/diycode/util/AppBlockCanaryContext.kt
adgvcxz
81,537,644
false
null
package com.car_inspection.app import android.content.Context import com.github.moduth.blockcanary.BlockCanaryContext import com.github.moduth.blockcanary.internal.BlockInfo import java.io.File import java.util.* class AppBlockCanaryContext : BlockCanaryContext() { /** * Implement in your project. * * @return Qualifier which can specify this installation, like version + flavor. */ override fun provideQualifier(): String { return "unknown" } /** * Implement in your project. * * @return user id */ override fun provideUid(): String { return "uid" } /** * Network type * * @return [String] like 2G, 3G, 4G, wifi, etc. */ override fun provideNetworkType(): String { return "unknown" } /** * Config monitor duration, after this time BlockCanary will stop, use * with `BlockCanary`'s isMonitorDurationEnd * * @return monitor last duration (in hour) */ override fun provideMonitorDuration(): Int { return -1 } /** * Config block threshold (in millis), dispatch over this duration is regarded as a BLOCK. You may set it * from performance of device. * * @return threshold in mills */ override fun provideBlockThreshold(): Int { return 1000 } /** * Thread stack dump interval, use when block happens, BlockCanary will dump on main thread * stack according to current sample cycle. * * * Because the implementation mechanism of Looper, real dump interval would be longer than * the period specified here (especially when cpu is busier). * * * @return dump interval (in millis) */ override fun provideDumpInterval(): Int { return provideBlockThreshold() } /** * Path to save log, like "/blockcanary/", will save to sdcard if can. * * @return path of log files */ override fun providePath(): String { return "/blockcanary/" } /** * If need notification to notice block. * * @return true if need, else if not need. */ override fun displayNotification(): Boolean { return true } /** * Implement in your project, bundle files into a zip file. * * @param src files before compress * @param dest files compressed * @return true if compression is successful */ override fun zip(src: Array<File>?, dest: File?): Boolean { return false } /** * Implement in your project, bundled log files. * * @param zippedFile zipped file */ override fun upload(zippedFile: File?) { throw UnsupportedOperationException() } /** * Packages that developer concern, by default it uses process name, * put high priority one in pre-order. * * @return null if simply concern only package with process name. */ override fun concernPackages(): List<String>? { return null } /** * Filter stack without any in concern package, used with @{code concernPackages}. * * @return true if filter, false it not. */ override fun filterNonConcernStack(): Boolean { return false } /** * Provide white list, entry in white list will not be shown in ui list. * * @return return null if you don't need white-list filter. */ override fun provideWhiteList(): List<String> { val whiteList = LinkedList<String>() whiteList.add("org.chromium") return whiteList } /** * Whether to delete files whose stack is in white list, used with white-list. * * @return true if delete, false it not. */ override fun deleteFilesInWhiteList(): Boolean { return true } /** * Block interceptor, developer may provide their own actions. */ override fun onBlock(context: Context?, blockInfo: BlockInfo?) { } }
1
null
1
4
9c10218be1291a2a3cd7676f3357320bf7c8961f
4,003
Diycode
Apache License 2.0
src/app/src/main/java/com/huawei/demo/health/HealthKitMainActivity.kt
HMS-Core
310,166,404
false
null
/* * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.demo.health import java.util.ArrayList; import android.content.Intent import android.os.Bundle import android.util.Log; import android.view.View import androidx.appcompat.app.AppCompatActivity import com.huawei.demo.health.auth.HealthKitAuthActivity import com.huawei.hms.common.ApiException import com.huawei.hms.support.account.AccountAuthManager import com.huawei.hms.support.account.request.AccountAuthParamsHelper class HealthKitMainActivity : AppCompatActivity() { private val TAG = "KitConnectActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_health_kit_main) } /** * Data Controller * * @param view UI object */ fun healthDataControllerOnclick(view: View) { val intent = Intent(this, HealthKitDataControllerActivity::class.java) startActivity(intent) } /** * Setting Controller * * @param view UI object */ fun healthSettingControllerOnclick(view: View) { val intent = Intent(this, HealthKitSettingControllerActivity::class.java) startActivity(intent) } /** * Auto Recorder * * @param view UI object */ fun healthAutoRecorderOnClick(view: View) { val intent = Intent(this, HealthKitAutoRecorderControllerActivity::class.java) startActivity(intent) } /** * Activity Records Controller * * @param view UI object */ fun healthActivityRecordOnClick(view: View) { val intent = Intent(this, HealthKitActivityRecordControllerActivity::class.java) startActivity(intent) } /** * signing In and applying for Scopes * * @param view UI object */ fun onLoginClick(view: View) { val intent = Intent(this, HealthKitAuthActivity::class.java) startActivity(intent) } /** * health Records Controller * * @param view UI object */ fun hihealthHealthControllerOnclick(view: View) { val intent = Intent(this, HealthKitHealthRecordControllerActivity::class.java) startActivity(intent) } /** * To improve privacy security, your app should allow users to cancel authorization. * After calling this function, you need to call login and authorize again. * * @param view (indicating a UI object) */ fun cancelScope(view: View) { val authParams = AccountAuthParamsHelper().setAccessToken().setScopeList(ArrayList()).createParams() val authService = AccountAuthManager.getService(applicationContext, authParams) authService.cancelAuthorization().addOnCompleteListener { task -> if (task.isSuccessful) { // Processing after successful cancellation of authorization Log.i(TAG, "cancelAuthorization success") } else { // Processing after failed cancellation of authorization val exception = task.exception Log.i(TAG, "cancelAuthorization fail") if (exception is ApiException) { val statusCode = exception.statusCode Log.e(TAG, "cancelAuthorization fail for errorCode: $statusCode") } } } } }
1
null
7
25
914f1007264a15e3f9ff387c1b8d774da3cc3d54
3,990
hms-health-demo-kotlin
Apache License 2.0
libraries/stdlib/unsigned/src/kotlin/UnsignedUtils.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package kotlin internal fun uintCompare(v1: Int, v2: Int): Int = (v1 xor Int.MIN_VALUE).compareTo(v2 xor Int.MIN_VALUE) internal fun ulongCompare(v1: Long, v2: Long): Int = (v1 xor Long.MIN_VALUE).compareTo(v2 xor Long.MIN_VALUE) internal fun uintDivide(v1: UInt, v2: UInt): UInt = (v1.toLong() / v2.toLong()).toUInt() internal fun uintRemainder(v1: UInt, v2: UInt): UInt = (v1.toLong() / v2.toLong()).toUInt() // TODO: Add reference to Guava implementation source internal fun ulongDivide(v1: ULong, v2: ULong): ULong { val dividend = v1.toLong() val divisor = v2.toLong() if (divisor < 0) { // i.e., divisor >= 2^63: return if (v1 < v2) ULong(0) else ULong(1) } // Optimization - use signed division if both dividend and divisor < 2^63 if (dividend >= 0) { return ULong(dividend / divisor) } // Otherwise, approximate the quotient, check, and correct if necessary. val quotient = ((dividend ushr 1) / divisor) shl 1 val rem = dividend - quotient * divisor return ULong(quotient + if (ULong(rem) >= ULong(divisor)) 1 else 0) } internal fun ulongRemainder(v1: ULong, v2: ULong): ULong { val dividend = v1.toLong() val divisor = v2.toLong() if (divisor < 0) { // i.e., divisor >= 2^63: return if (v1 < v2) { v1 // dividend < divisor } else { v1 - v2 // dividend >= divisor } } // Optimization - use signed modulus if both dividend and divisor < 2^63 if (dividend >= 0) { return ULong(dividend % divisor) } // Otherwise, approximate the quotient, check, and correct if necessary. val quotient = ((dividend ushr 1) / divisor) shl 1 val rem = dividend - quotient * divisor return ULong(rem - if (ULong(rem) >= ULong(divisor)) divisor else 0) } internal fun ulongToString(v: Long): String = ulongToString(v, 10) internal fun ulongToString(v: Long, base: Int): String { require(base == 10) // TODO: toString(base) support in common if (v >= 0) return v.toString(/* base */) var quotient = ((v ushr 1) / base) shl 1 var rem = v - quotient * base if (rem >= base) { rem -= base quotient += 1 } return quotient.toString(/* base */) + rem.toString(/* base */) }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
2,434
kotlin
Apache License 2.0
pluto-plugins/plugins/network/core/lib/src/main/java/com/pluto/plugins/network/internal/share/ShareOptionsAdapter.kt
androidPluto
390,471,457
false
{"Kotlin": 744352, "Shell": 646}
package com.pluto.plugins.network.internal.share import android.view.ViewGroup import com.pluto.plugins.network.internal.share.holders.ShareHeadingHolder import com.pluto.plugins.network.internal.share.holders.ShareOptionHolder import com.pluto.plugins.network.internal.share.holders.ShareResponseOptionHolder import com.pluto.utilities.list.BaseAdapter import com.pluto.utilities.list.DiffAwareHolder import com.pluto.utilities.list.ListItem internal class ShareOptionsAdapter(private val listener: OnActionListener) : BaseAdapter() { override fun getItemViewType(item: ListItem): Int? { return when (item) { is ShareOptionType.All -> ITEM_TYPE_OPTION is ShareOptionType.CURL -> ITEM_TYPE_OPTION is ShareOptionType.Request -> ITEM_TYPE_OPTION is ShareOptionType.Response -> ITEM_TYPE_OPTION_RESPONSE is ShareOptionType.Header -> ITEM_TYPE_HEADER else -> null } } override fun onViewHolderCreated(parent: ViewGroup, viewType: Int): DiffAwareHolder? { return when (viewType) { ITEM_TYPE_OPTION -> ShareOptionHolder(parent, listener) ITEM_TYPE_OPTION_RESPONSE -> ShareResponseOptionHolder(parent, listener) ITEM_TYPE_HEADER -> ShareHeadingHolder(parent, listener) else -> null } } companion object { const val ITEM_TYPE_OPTION = 1000 const val ITEM_TYPE_OPTION_RESPONSE = 1001 const val ITEM_TYPE_HEADER = 1002 } }
23
Kotlin
64
657
5562cb7065bcbcf18493820e287d87c7726f630b
1,517
pluto
Apache License 2.0
src/tools/important/tankslua/tkv/TKVDecoder.kt
dabigf5
752,112,579
false
{"Kotlin": 47791, "Lua": 5421}
package tools.important.tankslua.tkv class TKVDecodeException(message: String) : Exception(message) private fun decodeFail(message: String): Nothing = throw TKVDecodeException(message) private class ParseState(val text: String, var position: Int = 0) { fun peek(offset: Int = 0): Char? { val peekPos = position + offset if (peekPos < 0 || peekPos >= text.length) return null return text[peekPos] } fun consume(amt: Int = 1) { position += amt } val finished: Boolean get() = position >= text.length fun readWhile(predicate: (Char) -> Boolean): String { val builder = StringBuilder() while (!finished && predicate(peek()!!)) { builder.append(peek()) consume() } return builder.toString() } fun readIdentifier(): String { return readWhile { !it.isWhitespace() } } fun readValue(): String { return readWhile { it != '\n' && it != '\r' } } fun readType(): TKVType { val typeName = readIdentifier() return TKVType.entries.find { it.codeName == typeName } ?: decodeFail("Unknown TKV type \"$typeName\"") } fun skipWhitespace() { while (peek()?.isWhitespace() == true) { consume() } } } private fun String.decodeTKVValue(type: TKVType): TKVValue { when (type) { TKVType.INT -> { return TKVValue(TKVType.INT, toIntOrNull() ?: decodeFail("Malformed int")) } TKVType.FLOAT -> { return TKVValue(TKVType.FLOAT, toFloatOrNull() ?: decodeFail("Malformed float")) } TKVType.DOUBLE -> { return TKVValue(TKVType.DOUBLE, toDoubleOrNull() ?: decodeFail("Malformed double")) } TKVType.BOOLEAN -> { if (this != "true" && this != "false") decodeFail("Malformed bool") return TKVValue(TKVType.BOOLEAN, this == "true") } TKVType.STRING -> { if (!(startsWith('"') && endsWith('"'))) decodeFail("Malformed string") val noQuotes = try { substring(1..<length - 1) } catch (_: StringIndexOutOfBoundsException) { decodeFail("Malformed string") } val unescaped = noQuotes .replace("\\t", "\t") .replace("\\b", "\b") .replace("\\n", "\n") .replace("\\r", "\r") .replace("\\\"", "\"") .replace("\\\\", "\\") return TKVValue(TKVType.STRING, unescaped) } TKVType.VERSION -> { return try { TKVValue(TKVType.VERSION, SemanticVersion.fromVersionString(this)) } catch (e: IllegalArgumentException) { decodeFail(e.message!!) } } } } fun decodeTKV(text: String): Map<String, TKVValue> { val map = mutableMapOf<String, TKVValue>() val state = ParseState(text) while (!state.finished) { if (state.peek() == '\n' || state.peek() == '\r') { state.consume() continue } if (state.finished) break val type = state.readType() state.skipWhitespace() val name = state.readIdentifier() state.skipWhitespace() if (state.peek() != '=') decodeFail("Expected '='") state.consume() state.skipWhitespace() val value = state.readValue() if (!state.finished && state.peek() != '\n' && state.peek() != '\r') decodeFail("Expected newline or eof") if (map[name] != null) decodeFail("Two entries cannot have the same name") val decoded = value.decodeTKVValue(type) map[name] = decoded } return map.toMap() } fun main() { decodeTKV( """ string myString = "skibidi string" float myFloat = 2.0 int myInt = 2 double myDouble = 2.0 """ ) }
0
Kotlin
0
2
9a9cef853f320490e7d00588368f986f3f0dd5f8
3,929
TanksLua
MIT License
src/main/kotlin/de/akquinet/tim/proxy/logging/LogLevelService.kt
tim-ref
751,475,615
false
{"Kotlin": 312946, "Perl": 30621, "Shell": 11056, "Dockerfile": 3792, "Python": 976}
/* * Copyright © 2023 - 2024 akquinet GmbH (https://www.akquinet.de) * * 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 de.akquinet.tim.proxy.logging import ch.qos.logback.classic.Level import de.akquinet.tim.proxy.ProxyConfiguration import kotlinx.coroutines.delay import mu.KotlinLogging import org.slf4j.LoggerFactory import kotlin.time.DurationUnit import kotlin.time.toDuration class LogLevelService( private val logLevelResetConfiguration: ProxyConfiguration.LogLevelResetConfiguration ) { private val logger = KotlinLogging.logger {} private val loggerContext = LoggerFactory.getILoggerFactory() fun setLogLevel(newLogLevel: Level, loggerIdentifier: String = org.slf4j.Logger.ROOT_LOGGER_NAME) { val resetLogLevel = Level.toLevel(logLevelResetConfiguration.resetLogLevel) if (newLogLevel != resetLogLevel) { val targetLogger = loggerContext.getLogger(loggerIdentifier) as? ch.qos.logback.classic.Logger targetLogger?.let { logger.info { "Setting log level to $newLogLevel for target logger $loggerIdentifier" } it.level = newLogLevel } } } suspend fun scheduleLogLevelReset(loggerIdentifier: String = org.slf4j.Logger.ROOT_LOGGER_NAME) { delay(logLevelResetConfiguration.logLevelResetDelayInSeconds.toDuration(DurationUnit.SECONDS)) val targetLogger = loggerContext.getLogger(loggerIdentifier) as? ch.qos.logback.classic.Logger targetLogger?.let { it.level = Level.toLevel(logLevelResetConfiguration.resetLogLevel) logger.info { "Reset log level back to ${it.level.levelStr} for target logger ${it.name}" } } } }
0
Kotlin
0
1
70c6c72b6ce80b877628d7634754f30f00cf21b9
2,222
messenger-proxy
Apache License 2.0
availability/core/src/main/java/com/github/availability/ad/core/AdCache.kt
7449
652,961,505
false
{"Kotlin": 72805}
package com.github.availability.ad.core import com.github.availability.ad.debug.AdLog object AdCache { private val adCaches = linkedMapOf<String, Ad?>() @JvmStatic @Synchronized fun checkExpireTimeCache() { AdLog.i("checkExpireTimeCache") adCaches.checkExpireTimeCache() } @JvmStatic @Synchronized fun getCacheAndRemove(key: String): Ad? { AdLog.i("getCacheAndRemove") adCaches.checkExpireTimeCache() return adCaches.remove(key) } @Deprecated("@see getCacheAndRemove(key)") @JvmStatic @Synchronized fun getCache(key: String): Ad? { AdLog.i("getCache") adCaches.checkExpireTimeCache() return adCaches[key] } @JvmStatic @Synchronized fun getAllCache(): LinkedHashMap<String, Ad?> { AdLog.i("getAllCache") adCaches.checkExpireTimeCache() return adCaches } @JvmStatic @Synchronized fun containsKey(key: String): Boolean { AdLog.i("containsKey") adCaches.checkExpireTimeCache() return adCaches.containsKey(key) } @JvmStatic @Synchronized fun putAd(key: String, item: Ad) { AdLog.i("putAd") if (containsKey(key)) { getCacheAndRemove(key)?.destroy() } adCaches[key] = item } @JvmStatic @Synchronized private fun LinkedHashMap<String, Ad?>.checkExpireTimeCache() { val iterator = iterator() while (iterator.hasNext()) { val next = iterator.next().value ?: return let { iterator.remove() } if (next.expireMillis < System.currentTimeMillis()) { next.destroy() iterator.remove() } } } }
0
Kotlin
1
4
4f4a08e973abd1b6c00182ee66c0ae9c3b86ae24
1,754
AvailabilityAd
Apache License 2.0
app/src/main/java/com/qxy/tiktlin/data/netData/VideoList.kt
lukelmouse-github
517,612,289
false
null
package com.qxy.tiktlin.data.netData import java.io.Serializable data class VideoList( val data: Data, val extra: Extra ) : Serializable { data class Data( val cursor: Long, val has_more: Boolean, val list: List<Video> ) : Serializable data class Video( val video_status: Int, val title: String, val cover: String, val is_top: Boolean, val create_time: Long, val item_id: String, val is_reviewed: Boolean, val video_id: Long, val share_url: String, val media_type: Int, val statistics: Statistics ) : Serializable { data class Statistics( val share_count: Int, val forward_count: Int, val comment_count: Int, val digg_count: Int, val download_count: Int, val play_count: Int ) : Serializable } }
0
Kotlin
0
1
5ba2bdc7eb41371b578d52e8289b8d08f77ce10d
927
Tiktlin
Apache License 2.0
src/main/kotlin/de/debuglevel/streetdirectory/street/GetStreetResponse.kt
debuglevel
349,827,124
false
null
package de.debuglevel.streetdirectory.street import io.micronaut.data.annotation.DateCreated import io.micronaut.data.annotation.DateUpdated import java.time.LocalDateTime import java.util.* data class AddStreetResponse( val id: UUID, /** * The postal code */ var postalcode: String, /** * The name of the street */ var streetname: String, /** * Latitude of the center of the postal code area */ var centerLatitude: Double?, /** * Longitude of the center of the postal code area */ var centerLongitude: Double?, /** * When created in the database */ @DateCreated var createdOn: LocalDateTime, /** * When last modified in the database */ @DateUpdated var lastModifiedOn: LocalDateTime, ) { constructor(street: Street) : this( street.id!!, street.postalcode.code, street.streetname, street.centerLatitude, street.centerLongitude, street.createdOn, street.lastModifiedOn ) }
9
Kotlin
0
1
f979b8311174d7182ade8fb801f28f4d08d491be
1,057
street-lister
The Unlicense
Android/app/src/main/java/com/amrdeveloper/askme/ui/notification/NotificationViewModel.kt
AmrDeveloper
223,007,000
false
null
package com.amrdeveloper.askme.ui.notification import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.* import com.amrdeveloper.askme.data.Notification import com.amrdeveloper.askme.data.source.NotificationRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class NotificationViewModel @Inject constructor( private val notificationRepository: NotificationRepository ) : ViewModel() { private var notificationPagedList: MutableLiveData<PagingData<Notification>> = MutableLiveData() fun loadUserNotifications(userId : String, token : String){ viewModelScope.launch { notificationRepository.getUserNotifications(token, userId).collect { notificationPagedList.value = it } } } fun makeNotificationReaded(id : String, token : String){ viewModelScope.launch { val result = notificationRepository.makeNotificationOpened(token, id) if (result.isSuccess) { val response = result.getOrNull() when(response?.code()){ 200 -> Log.d("NotificationViewModel", "Notification Request is done Now") 403 -> Log.d("NotificationViewModel", "No Auth") else -> Log.d("NotificationViewModel", "Error") } } else { } } } fun getNotificationList() = notificationPagedList }
9
Kotlin
4
19
7b86588cd7cff18d7ba93758ceeff56e3b44d2be
1,645
Askme
MIT License
eva-icons/generate-source.main.kts
DevSrSouza
311,134,756
false
null
@file:Repository("https://jitpack.io") @file:Repository("https://maven.google.com") @file:Repository("https://jetbrains.bintray.com/trove4j") @file:Repository("file:///home/devsrsouza/.m2/repository") // svg-to-compose //@file:DependsOn("com.github.DevSrSouza:svg-to-compose:0.5.0") @file:DependsOn("br.com.devsrsouza:svg-to-compose:0.6.0-SNAPSHOT") @file:DependsOn("com.google.guava:guava:23.0") @file:DependsOn("com.android.tools:sdk-common:27.2.0-alpha16") @file:DependsOn("com.android.tools:common:27.2.0-alpha16") @file:DependsOn("com.squareup:kotlinpoet:1.7.2") @file:DependsOn("org.ogce:xpp3:1.1.6") @file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9") // Jgit @file:DependsOn("org.eclipse.jgit:org.eclipse.jgit:3.5.0.201409260305-r") import br.com.devsrsouza.svg2compose.ParsingResult import br.com.devsrsouza.svg2compose.Svg2Compose import br.com.devsrsouza.svg2compose.VectorType import org.eclipse.jgit.api.Git import java.io.File fun File.makeDirs() = apply { mkdirs() } val buildDir = File("build/").makeDirs() val githubId = "akveo/eva-icons" val repository = "https://github.com/$githubId" val version = "v1.1.3" val rawGithubRepository = "https://raw.githubusercontent.com/$githubId/$version" val blobGithubRepository = "$repository/blob/$version" val repoCloneDir = createTempDir(suffix = "eva-git-repo") println("Cloning repository") val git = Git.cloneRepository() .setURI(repository) .setDirectory(repoCloneDir) .call() git.checkout().setName("refs/tags/$version").call() val repoIcons = File(repoCloneDir, "package/icons") val iconsDir = File(repoCloneDir, "icons-to-build").makeDirs() File(repoIcons, "fill/svg").copyRecursively(File(iconsDir, "fill").makeDirs()) File(repoIcons, "outline/svg").copyRecursively(File(iconsDir, "outline").makeDirs()) fun replacePathName(path: String): String { val iconName = path.substringAfterLast('/') return path.replace("icons-to-build", "package/icons") .replace(iconName, "svg/$iconName") .replace("_", "-") } // renaming to match to svg-to-compose iconsDir.walkTopDown().filter { it.extension == "svg" } .forEach { val newFile = File(it.parentFile, it.name.replace("-", "_")) it.renameTo(newFile) } val srcDir = File("src/commonMain/kotlin").apply { mkdirs() } srcDir.deleteRecursively() srcDir.mkdirs() fun String.removeSuffix(suffix: String, ignoreCase: Boolean): String { if(ignoreCase) { val index = lastIndexOf(suffix, ignoreCase = true) return if(index > -1) substring(0, index) else this } else { return removeSuffix(suffix) } } println("Generating all svg to compose") val result = Svg2Compose.parse( applicationIconPackage = "compose.icons", accessorName = "EvaIcons", outputSourceDirectory = srcDir, vectorsDirectory = iconsDir, type = VectorType.SVG, allAssetsPropertyName = "AllIcons", iconNameTransformer = { name, group -> name.removeSuffix(group, ignoreCase = true) } ) println("Copying LICENSE from the Icon pack") val licensePath = "LICENSE.txt" val licenseFile = File(repoCloneDir, licensePath) val resDir = File("src/commonMain/resources").makeDirs() val licenseInResource = File(resDir, "eva-license.txt") licenseFile.copyTo(licenseInResource, overwrite = true) println("Generating documentation") data class DocumentationGroup( val groupName: String, val groupAccessingFormat: String, val icons: List<DocumentationIcon>, ) data class DocumentationIcon( val accessingFormat: String, val svgFilePathRelativeToRepository: String, ) fun ParsingResult.asDocumentationGroupList( previousAccessingGroupFormat: String? = null ): List<DocumentationGroup> { val accessingGroupFormat = if(previousAccessingGroupFormat != null) "$previousAccessingGroupFormat.${groupName.second}" else groupName.second return listOf(asDocumentationGroup(accessingGroupFormat)) + generatedGroups.flatMap { it.asDocumentationGroupList(accessingGroupFormat) } } fun ParsingResult.asDocumentationGroup( accessingGroupFormat: String ): DocumentationGroup { return DocumentationGroup( groupName = groupName.second, groupAccessingFormat = accessingGroupFormat, icons = generatedIconsMemberNames.map { DocumentationIcon( "$accessingGroupFormat.${it.value.simpleName}", it.key.relativeTo(repoCloneDir).path ) } ) } fun markdownSvg(doc: DocumentationIcon): String { return "![](${rawGithubRepository + "/" + replacePathName(doc.svgFilePathRelativeToRepository) })" } fun markdownIconDocumentation(doc: DocumentationIcon): String { return "${markdownSvg(doc)} | ${doc.accessingFormat}" } val chunks = 2 fun List<DocumentationIcon>.iconsTableDocumentation(): String = sortedBy { it.accessingFormat } .chunked(chunks).map { "| ${it.map { markdownIconDocumentation(it) }.joinToString(" | ")} |" }.joinToString("\n") val documentationGroups = result.asDocumentationGroupList() .filter { it.icons.isNotEmpty() } .map { """ ## ${it.groupName} |${" Icon | In Code |".repeat(chunks)} |${" --- | --- |".repeat(chunks)} """.trimIndent() + "\n" + it.icons.iconsTableDocumentation() }.joinToString("\n<br /><br />\n") val header = """ # [Eva Icons](https://akveo.github.io/eva-icons/) <br /> """.trimIndent() val license = """ ## [License]($blobGithubRepository/$licensePath) ``` """.trimIndent() + licenseFile.readText().trimEnd { it == '\n' } + "\n```\n\n<br /><br />\n\n" File("DOCUMENTATION.md").apply{ if(exists().not()) createNewFile() }.writeText( header + "\n" + license + "\n" + documentationGroups )
15
null
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
5,824
compose-icons
MIT License
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/npcs/definitions/undeads/count_draynor_level_37.plugin.kts
2011Scape
578,880,245
false
null
package gg.rsmod.plugins.content.npcs.definitions.undeads import gg.rsmod.game.model.attr.killedCountDraynor import gg.rsmod.plugins.content.drops.DropTableFactory val count = Npcs.COUNT_DRAYNOR val table = DropTableFactory val countTable = table.build { guaranteed { nothing(128) } } table.register(countTable) on_npc_pre_death(count) { val p = npc.damageMap.getMostDamage()!! as Player p.playSound(Sfx.VAMPIRE_DEATH) npc.animate(1568) npc.queue { wait(2) val distance = npc.tile.getDistance(p.tile) if (distance > 1) { p.walkTo(npc.tile.transform(p.faceDirection.getDeltaX(), p.faceDirection.getDeltaZ()), MovementQueue.StepType.FORCED_RUN, detectCollision = true) } npc.facePawn(p) npc.animate(id = 12604) p.facePawn(npc) p.animate(id = 12606, idleOnly = true) } } on_npc_death(count) { val p = npc.damageMap.getMostDamage()!! as Player p.attr.put(killedCountDraynor, true) p.lockingQueue(priority = TaskPriority.STRONG) { this.chatPlayer("I should tell Morgan that I've killed the vampyre!", facialExpression = FacialExpression.HAPPY) } } set_combat_def(count) { configs { attackSpeed = 4 respawnDelay = 0 } stats { hitpoints = 350 attack = 30 strength = 25 defence = 30 magic = 1 ranged = 1 } bonuses { defenceStab = 2 defenceSlash = 1 defenceCrush = 3 defenceMagic = 0 defenceRanged = 0 } anims { attack = 3331 block = 3332 death = 12604 } }
39
null
143
34
e5400cc71bfa087164153d468979c5a3abc24841
1,656
game
Apache License 2.0
ttl2-compatible/src/test/java/com/alibaba/perf/Utils.kt
alibaba
13,536,393
false
null
package com.alibaba.perf import java.util.* private val random = Random() internal fun bytes2Hex(bytes: ByteArray): String { val sb = StringBuilder(1024) for (b in bytes) { val s = Integer.toHexString(b.toInt() and 0xFF) sb.append(if (s.length == 1) "0$s" else s) } return sb.toString() } internal fun getRandomBytes(): ByteArray { val bytes = ByteArray(1024) random.nextBytes(bytes) return bytes } internal fun getRandomString(): String { return bytes2Hex(getRandomBytes()) }
33
null
1687
7,600
4e9957584f204ce45274f038342268c66e694d85
531
transmittable-thread-local
Apache License 2.0
modules/libgdx/kotlin/com/huskerdev/openglfx/libgdx/internal/OGLFXGraphics.kt
husker-dev
393,363,130
false
{"C++": 14907461, "C": 196825, "Kotlin": 146113, "Objective-C": 5907}
package com.huskerdev.openglfx.libgdx.internal import com.badlogic.gdx.AbstractGraphics import com.badlogic.gdx.Application import com.badlogic.gdx.Graphics import com.badlogic.gdx.Graphics.DisplayMode import com.badlogic.gdx.graphics.* import com.badlogic.gdx.graphics.Cursor.SystemCursor.* import com.badlogic.gdx.graphics.glutils.GLVersion import com.huskerdev.openglfx.canvas.GLCanvas import com.huskerdev.openglfx.canvas.GLCanvasAnimator import javafx.scene.ImageCursor import javafx.stage.Screen class OGLFXGraphics(val canvas: GLCanvas): AbstractGraphics() { private var gl20: GL20? = null private var gl30: GL30? = null private var gl31: GL31? = null private var gl32: GL32? = null override fun isGL30Available() = true override fun isGL31Available() = true override fun isGL32Available() = true override fun getGL20() = gl20 override fun getGL30() = gl30 override fun getGL31() = gl31 override fun getGL32() = gl32 override fun setGL20(gl20: GL20?) { this.gl20 = gl20 } override fun setGL30(gl30: GL30?) { this.gl30 = gl30 } override fun setGL31(gl31: GL31?) { this.gl31 = gl31 } override fun setGL32(gl32: GL32?) { this.gl32 = gl32 } override fun getWidth() = canvas.scaledWidth override fun getHeight() = canvas.scaledHeight override fun getBackBufferWidth() = canvas.scaledWidth override fun getBackBufferHeight() = canvas.scaledHeight override fun getSafeInsetLeft() = 0 override fun getSafeInsetTop() = 0 override fun getSafeInsetBottom() = 0 override fun getSafeInsetRight() = 0 override fun getFrameId() = canvas.fpsCounter.frameId override fun getDeltaTime() = canvas.fpsCounter.delta.toFloat() override fun getFramesPerSecond() = canvas.fpsCounter.currentFps override fun getType() = Graphics.GraphicsType.LWJGL3 override fun getGLVersion() = GLVersion(Application.ApplicationType.Desktop, "3.0 GL", "openglfx", "openglfx") override fun getPpiX() = 96f override fun getPpiY() = 96f override fun getPpcX() = 96f override fun getPpcY() = 96f override fun supportsDisplayModeChange() = false override fun getPrimaryMonitor() = FXMonitorWrapper(Screen.getPrimary()) override fun getMonitor(): Graphics.Monitor { val stage = canvas.scene.window return FXMonitorWrapper(Screen.getScreensForRectangle(stage.x, stage.y, stage.width, stage.height)[0]) } override fun getMonitors(): Array<Graphics.Monitor> { val stage = canvas.scene.window return Screen.getScreensForRectangle(stage.x, stage.y, stage.width, stage.height) .map { FXMonitorWrapper(it) }.toTypedArray() } override fun getDisplayModes() = arrayOf(getDisplayMode()) override fun getDisplayModes(monitor: Graphics.Monitor?) = arrayOf(getDisplayMode()) override fun getDisplayMode() = object: DisplayMode(canvas.scaledWidth, canvas.scaledHeight, 0, 32) {} override fun getDisplayMode(monitor: Graphics.Monitor?) = getDisplayMode() override fun setFullscreenMode(displayMode: DisplayMode?) = false override fun setWindowedMode(width: Int, height: Int) = false override fun setTitle(title: String?) {} override fun setUndecorated(undecorated: Boolean) {} override fun setResizable(resizable: Boolean) {} override fun setVSync(vsync: Boolean) {} override fun setForegroundFPS(fps: Int) {} override fun getBufferFormat() = Graphics.BufferFormat(32, 32, 32, 32, 32, 32, 16, false) override fun supportsExtension(extension: String?) = true override fun setContinuousRendering(isContinuous: Boolean) { canvas.animator = if(isContinuous) GLCanvasAnimator(60.0) else null } override fun isContinuousRendering() = canvas.animator != null override fun requestRendering() { canvas.repaint() } override fun isFullscreen() = false override fun newCursor(pixmap: Pixmap, xHotspot: Int, yHotspot: Int) = FXCursorWrapper(pixmap, xHotspot, yHotspot) override fun setCursor(cursor: Cursor?) { canvas.cursor = if(cursor != null) (cursor as FXCursorWrapper).imageCursor else null } override fun setSystemCursor(systemCursor: Cursor.SystemCursor) { canvas.cursor = when(systemCursor) { Arrow, Ibeam, NotAllowed, None -> javafx.scene.Cursor.DEFAULT Crosshair -> javafx.scene.Cursor.CROSSHAIR Hand -> javafx.scene.Cursor.HAND HorizontalResize -> javafx.scene.Cursor.H_RESIZE VerticalResize -> javafx.scene.Cursor.V_RESIZE NWSEResize -> javafx.scene.Cursor.NW_RESIZE NESWResize -> javafx.scene.Cursor.NE_RESIZE AllResize -> javafx.scene.Cursor.MOVE } } class FXCursorWrapper(pixmap: Pixmap, xHotspot: Int, yHotspot: Int) : Cursor { val imageCursor = ImageCursor(FXPixmapImage(pixmap), xHotspot.toDouble(), yHotspot.toDouble()) override fun dispose() {} } class FXMonitorWrapper internal constructor(screen: Screen) : Graphics.Monitor(screen.bounds.width.toInt(), screen.bounds.height.toInt(), "Unnamed screen") }
9
C++
8
84
ac22d5435915f16fa731b9e3564533c2507f2dc0
5,174
openglfx
Apache License 2.0
src/main/kotlin/silentorb/imp/intellij/actions/ToggleTilingAction.kt
silentorb
239,162,536
false
null
package silentorb.imp.intellij.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.application.ApplicationManager import silentorb.imp.intellij.messaging.toggleTilingTopic import silentorb.imp.intellij.ui.texturing.getTiling import silentorb.imp.intellij.ui.texturing.setTiling class ToggleTilingAction : ToggleAction() { override fun setSelected(event: AnActionEvent, state: Boolean) { val bus = ApplicationManager.getApplication().getMessageBus() val publisher = bus.syncPublisher(toggleTilingTopic) val tiling = !getTiling() setTiling(tiling) publisher.handle(tiling) } override fun isSelected(e: AnActionEvent): Boolean { return getTiling() } }
0
Kotlin
0
0
24c4f4b4e712256ee7686a947021072a6e9a2549
778
imp-intellij
MIT License
app/src/main/java/com/example/ead_mobile_application__native/screen/CartActivity.kt
LakinduVirajith
860,762,466
false
{"Kotlin": 110114}
package com.example.ead_mobile_application__native.screen import android.content.Intent import android.os.Build import android.os.Bundle import android.view.View import android.view.WindowInsetsController import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.ead_mobile_application__native.R import com.example.ead_mobile_application__native.adapter.CartAdapter import com.example.ead_mobile_application__native.model.Cart import com.example.ead_mobile_application__native.model.OrderItem import com.example.ead_mobile_application__native.service.CartApiService import com.example.ead_mobile_application__native.service.OrderApiService import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.gson.Gson import com.google.gson.reflect.TypeToken class CartActivity : AppCompatActivity() { // DECLARE VIEWS private lateinit var cartRecyclerView: RecyclerView private lateinit var layoutView : LinearLayout private lateinit var totalPriceText: TextView private lateinit var placeOrderButton: Button private lateinit var emptyCartText: TextView private lateinit var cartAdapter: CartAdapter // API SERVICE INSTANCE private val cartApiService = CartApiService() private val orderApiService = OrderApiService() // SAMPLE CART LIST private var cartList = listOf( Cart( productId = "1", name = "Casual Cotton T-Shirt", price = 19.99, discount = 4.00, imageResId = R.drawable.product_1, quantity = 1 ), Cart( productId = "4", name = "Classic Chino Pants", price = 34.99, discount = 7.00, imageResId = R.drawable.product_4, quantity = 2 ) ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_cart) // SET STATUS BAR ICONS TO LIGHT (BLACK) IN DARK THEME if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.decorView.windowInsetsController?.setSystemBarsAppearance( WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS ) } else { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } // HANDLE WINDOW INSETS FOR EDGE-TO-EDGE DISPLAY ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.cartActivity)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // FIND UI COMPONENTS BY ID cartRecyclerView = findViewById(R.id.cRecyclerView) layoutView = findViewById(R.id.cLayoutView) totalPriceText = findViewById(R.id.cTotalPriceText) placeOrderButton = findViewById(R.id.cBtnPlaceOrder) emptyCartText = findViewById(R.id.cEmptyCartText) // SETUP NAVIGATION BAR setupBottomNavigationView() // SETUP CART LIST AND ADAPTER setupCartList() // SET UP CLICK LISTENER FOR PLACE ORDER BUTTON placeOrderButton.setOnClickListener { handlePlaceOrder() } } // SETUP BOTTOM NAVIGATION VIEW AND ITS ITEM SELECTION private fun setupBottomNavigationView() { val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.selectedItemId = R.id.nvCart bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.nvHome -> { startActivity(Intent(applicationContext, HomeActivity::class.java)) @Suppress("DEPRECATION") overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true } R.id.nvOrder -> { startActivity(Intent(applicationContext, OrderActivity::class.java)) @Suppress("DEPRECATION") overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true } R.id.nvCart -> true R.id.nvAccount -> { startActivity(Intent(applicationContext, AccountActivity::class.java)) @Suppress("DEPRECATION") overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true } else -> false } } } // FUNCTION TO SETUP CART LIST AND ADAPTER private fun setupCartList() { // cartApiService.cartProducts() { response -> // runOnUiThread { // // UPDATE CART LIST BASED ON RESPONSE // if (response != null) { // val gson = Gson() // val productType = object : TypeToken<List<Product>>() {}.type // updateCartList(gson.fromJson(response, productType)) // } // } // } // INITIALIZE THE ADEPTER WITH AND CART LIST cartAdapter = CartAdapter(cartList) cartRecyclerView.adapter = cartAdapter cartRecyclerView.layoutManager = LinearLayoutManager(this) // CALCULATE TOTAL PRICE FROM CART LIST if (cartList.isNotEmpty()) { var calTotalPrice = 0.00 cartList.map { cartItem -> calTotalPrice += cartItem.price * cartItem.quantity } totalPriceText.text = getString(R.string.price_format, calTotalPrice) } // HANDLE CART VISIBILITY BASED ON ITEMS IN THE CART if (cartList.isEmpty()) { layoutView.visibility = View.GONE emptyCartText.visibility = View.VISIBLE }else{ layoutView.visibility = View.VISIBLE emptyCartText.visibility = View.GONE } } // FUNCTION TO UPDATE CART LIST private fun updateCartList(items: List<Cart>) { cartList = items cartAdapter.updateItems(items) } // FUNCTION TO HANDLE PLACE ORDER LOGIC private fun handlePlaceOrder(){ if(cartList.isNotEmpty()){ // CONVERT CART LIST TO ORDER ITEM LIST val orderItems = cartList.map { cartItem -> OrderItem( productId = cartItem.productId, quantity = cartItem.quantity ) } // PLACE THE ORDER USING THE ORDER ITEM LIST orderApiService.placeOrder(orderItems) { response -> if (response != null) { Toast.makeText(this, "Order Placed Successful", Toast.LENGTH_SHORT).show() val intent = Intent(this, OrderActivity::class.java) startActivity(intent) } else { Toast.makeText(this, "Order Placed Failed", Toast.LENGTH_SHORT).show() } } } } }
0
Kotlin
0
0
3a895c7398f9ec6989ce9374d604560d435359c6
7,610
EAD-Mobile-Application--Native
MIT License
app/src/main/java/pl/droidsonroids/toast/repositories/contact/ContactRepositoryImpl.kt
l-o-b-s-t-e-r
126,404,496
true
{"Kotlin": 377167, "Prolog": 102}
package pl.droidsonroids.toast.repositories.contact import io.reactivex.Single import pl.droidsonroids.toast.data.dto.contact.MessageDto import pl.droidsonroids.toast.data.mapper.toApi import pl.droidsonroids.toast.services.ContactService import pl.droidsonroids.toast.services.ContactStorage import javax.inject.Inject class ContactRepositoryImpl @Inject constructor(private val contactService: ContactService, private val contactStorage: ContactStorage) : ContactRepository { override fun sendMessage(message: MessageDto) = contactService.sendMessage(message.toApi()) override fun saveMessage(message: MessageDto) = contactStorage.saveMessage(message) override fun readMessage(): Single<MessageDto> = contactStorage.readMessage() }
0
Kotlin
0
0
b33bb2419802e936cec67f771b067adda92f2117
749
Toast-App
Apache License 2.0
src/main/kotlin/io/github/seggan/sf4k/extensions/VectorUtils.kt
Seggan
745,690,345
false
{"Kotlin": 67244, "Java": 3127}
package io.github.seggan.sf4k.extensions import org.bukkit.util.Vector operator fun Vector.component1() = x operator fun Vector.component2() = y operator fun Vector.component3() = z operator fun Vector.plus(other: Vector) = clone().add(other) operator fun Vector.plusAssign(other: Vector) { add(other) } operator fun Vector.minus(other: Vector) = clone().subtract(other) operator fun Vector.minusAssign(other: Vector) { subtract(other) } operator fun Vector.times(other: Vector) = clone().multiply(other) operator fun Vector.timesAssign(other: Vector) { multiply(other) } operator fun Vector.times(other: Double) = clone().multiply(other) operator fun Vector.timesAssign(other: Double) { multiply(other) } operator fun Vector.times(other: Int) = clone().multiply(other) operator fun Vector.timesAssign(other: Int) { multiply(other) } operator fun Vector.div(other: Vector) = clone().divide(other) operator fun Vector.divAssign(other: Vector) { divide(other) } operator fun Vector.div(other: Double) = clone().multiply(1 / other) // WHY VECTOR NO HAVE DIVIDE AAAAA operator fun Vector.divAssign(other: Double) { multiply(1 / other) } operator fun Vector.div(other: Int) = clone().multiply(1.0 / other) operator fun Vector.divAssign(other: Int) { multiply(1.0 / other) }
0
Kotlin
1
4
18c0074c9e8502c6431294da0c101b182269a034
1,278
sf4k
Apache License 2.0
app/src/main/java/com/example/gibmejob/model/Constants.kt
ken1000minus7
558,568,195
false
{"Kotlin": 112607}
package com.example.gibmejob.model object Constants { const val Users = "Users" const val JobApplications = "JobApplications" const val Jobs = "Jobs" }
0
Kotlin
2
0
895f90c938c3ebeff5edcb2287575af80e9f0ea9
164
GibMeJob
MIT License
app/src/main/java/com/android254/droidconke19/firebase/InstanceIdService.kt
carolinemusyoka
222,480,419
true
{"Kotlin": 179280, "HTML": 54621, "Java": 828}
package com.android254.droidconke19.firebase import android.content.SharedPreferences import com.android254.droidconke19.utils.SharedPref.FIREBASE_TOKEN import com.google.firebase.messaging.FirebaseMessagingService import org.koin.android.ext.android.inject import org.koin.core.parameter.parametersOf class InstanceIdService : FirebaseMessagingService() { private val sharedPreferences: SharedPreferences by inject { parametersOf(this) } override fun onNewToken(token: String) { super.onNewToken(token) saveToken(token) } private fun saveToken(token: String?) { sharedPreferences.edit().putString(FIREBASE_TOKEN, token).apply() } }
0
null
0
2
8e5410b786760a573a5498007a53cec94729c9ed
684
droidconKE2019App
MIT License
src/main/kotlin/io/github/deficuet/alpa/gui/PaintingPanel.kt
Deficuet
482,093,606
false
null
package io.github.deficuet.alpa.gui import io.github.deficuet.alpa.function.PaintingFunctions import io.github.deficuet.alpa.utils.* import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.geometry.Pos import javafx.scene.control.* import javafx.scene.paint.Color import javafx.util.Callback import tornadofx.* class PaintingPanel: PanelTemplate("立绘合并") { override val functions = PaintingFunctions(this) val dependenciesList = observableListOf<String>() var dependenciesColumn: TableColumn<String, String> by singleAssign() val requiredPaintingName = SimpleStringProperty("目标名称:N/A") init { with(importFileZone) { tableview(dependenciesList) { vboxConstraints { marginTop = 16.0; marginLeft = 8.0 marginRight = 8.0; marginBottom = 8.0 minWidth = 356.0; maxHeight = 150.0 } selectionModel = null dependenciesColumn = column("依赖项", String::class) { minWidth = 357.0; maxWidth = 357.0; isSortable = false cellValueFactory = Callback { SimpleObjectProperty(it.value) } } } } importImageTitledPane.text = "导入立绘" with(importImageButtonZone) { alignment = Pos.CENTER_LEFT button("添加立绘") { minWidth = 80.0; minHeight = 30.0 action { isDisable = true functions.importPainting() isDisable = false } } label(requiredPaintingName) { hboxConstraints { marginLeft = 12.0 } } } with(requiredImageListView) { cellFormat { text = it textFill = if (functions.continuation.mergeInfoList[index].isImported) { Color.BLUE } else Color.BLACK } onUserSelectModified { requiredPaintingName.value = "目标名称:$it" } } } }
1
Kotlin
0
22
8dd8106a9d3c827c9f23e730cc15c895f8e9cc2e
2,153
AzurLanePaintingAnalysis-Kt
MIT License
openpss/src/main/kotlin/com/hanggrian/openpss/control/DoubleField.kt
hanggrian
104,778,225
false
{"Kotlin": 324374, "HTML": 18736, "SCSS": 7162, "CSS": 5335, "Ruby": 147}
package com.hanggrian.openpss.control import com.jfoenix.controls.JFXTextField import javafx.beans.property.BooleanProperty import javafx.beans.property.DoubleProperty import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleDoubleProperty import ktfx.bindings.booleanBindingOf import ktfx.coroutines.listener import ktfx.getValue import ktfx.setValue import ktfx.text.buildStringConverter class DoubleField : JFXTextField() { val valueProperty: DoubleProperty = SimpleDoubleProperty() var value: Double by valueProperty val validProperty: BooleanProperty = SimpleBooleanProperty() val isValid: Boolean by validProperty init { textProperty().bindBidirectional( valueProperty, buildStringConverter { fromString { it.toDoubleOrNull() ?: 0.0 } }, ) validProperty.bind( booleanBindingOf(textProperty()) { try { java.lang.Double.parseDouble(text) true } catch (e: NumberFormatException) { false } }, ) focusedProperty().listener { _, _, focused -> if (focused && text.isNotEmpty()) { selectAll() } } } }
1
Kotlin
0
7
02013488fc115de903e7775d7c6d18d83537dcac
1,328
openpss
Apache License 2.0
src/main/kotlin/codespitz10/SortType.kt
skaengus2012
195,506,540
false
{"Gradle": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 109, "Java": 22}
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package codespitz10 enum class SortType : Comparator<Task> { TITLE_DESC { override fun compare(o1: Task, o2: Task): Int = o1.title.compareTo(o2.title) }, TITLE_ASC { override fun compare(o1: Task, o2: Task): Int = o2.title.compareTo(o1.title) }, DATE_ASC { override fun compare(o1: Task, o2: Task): Int = o1.date.compareTo(o2.date) }, DATE_DESC { override fun compare(o1: Task, o2: Task): Int = o2.date.compareTo(o1.date) }; }
1
null
1
1
645130abf71e0374dfea6077a1b7babcd10921b2
1,119
OBJECT_STUDY
Apache License 2.0
src/commonMain/kotlin/csense/kotlin/extensions/collections/generic/ForEach.kt
csense-oss
136,911,995
false
null
@file:Suppress("unused", "NOTHING_TO_INLINE") package csense.kotlin.extensions.collections.generic import csense.kotlin.* import csense.kotlin.annotations.numbers.* import csense.kotlin.extensions.collections.* import csense.kotlin.extensions.primitives.* public typealias Function2Unit<T, U> = (first: T, second: U) -> Unit public typealias Function2IndexedUnit<T, U> = (indexOfFirst: @IntLimit(from = 0) Int, first: T, second: U) -> Unit //region backwards /** * * @receiver GenericCollectionExtensions * @param length [Int] * @param getter [GenericGetterIndexMethod]<T> * @param action [FunctionUnit]<T> */ public inline fun <T> GenericCollectionExtensions.forEachBackwards( @IntLimit(from = 0) length: Int, getter: GenericGetterIndexMethod<T>, action: FunctionUnit<T> ) { for (i in (length - 1) downTo 0) { action(getter(i)) } } /** * * @receiver GenericCollectionExtensions * @param length [Int] * @param getter [GenericGetterIndexMethod]<T> * @param action [FunctionUnit]<T> */ public inline fun <T> GenericCollectionExtensions.forEachBackwardsIndexed( @IntLimit(from = 0) length: Int, getter: GenericGetterIndexMethod<T>, action: (index: @IntLimit(from = 0) Int, element: T) -> Unit ) { for (i in (length - 1) downTo 0) { action(i, getter(i)) } } //endregion //region foreach 2 /** * This is the "internal" generic function ,from which all the instances will be using. * @receiver GenericCollectionExtensions * @param length [Int] * @param getter [GenericGetterIndexMethod]<T> * @param action [Function2Unit]<T, T> */ public inline fun <T> GenericCollectionExtensions.forEach2( @IntLimit(from = 0) length: Int, getter: GenericGetterIndexMethod<T>, action: Function2Unit<T, T> ) { if (canNotForeach2(length)) { return } for (i in (0 until length step 2)) { val first = getter(i) val second = getter(i + 1) action(first, second) } } /** * * @receiver GenericCollectionExtensions * @param length [Int] * @param getter [GenericGetterIndexMethod]<T> * @param action [Function2IndexedUnit]<T, T> */ public inline fun <T> GenericCollectionExtensions.forEach2Indexed( @IntLimit(from = 0) length: Int, getter: GenericGetterIndexMethod<T>, action: Function2IndexedUnit<T, T> ) { if (canNotForeach2(length)) { return } for (i in (0 until length step 2)) { val first = getter(i) val second = getter(i + 1) action(i, first, second) } } //endregion //region map 2 /** * * @receiver GenericCollectionExtensions * @param length [Int] * @param getter [GenericGetterIndexMethod]<T> * @param mapper [Function2]<T, T, U> * @return [List]<U> */ public inline fun <T, U> GenericCollectionExtensions.mapEach2( @IntLimit(from = 0) length: Int, getter: GenericGetterIndexMethod<T>, mapper: Function2<T, T, U> ): List<U> { if (canNotForeach2(2)) { return emptyList() } return List(length / 2) { counter: Int -> val doubleIndex = counter * 2 val first = getter(doubleIndex) val second = getter(doubleIndex + 1) mapper(first, second) } } /** * * @receiver GenericCollectionExtensions * @param length [Int] * @param getter [GenericGetterIndexMethod]<T> * @param mapper [Function3]<Int, T, T, U> * @return [List]<U> */ public inline fun <T, U> GenericCollectionExtensions.mapEach2Indexed( @IntLimit(from = 0) length: Int, getter: GenericGetterIndexMethod<T>, mapper: Function3<Int, T, T, U> ): List<U> { if (canNotForeach2(2)) { return emptyList() } return List(length / 2) { counter: Int -> val doubleIndex = counter * 2 val first = getter(doubleIndex) val second = getter(doubleIndex + 1) mapper(doubleIndex, first, second) } } //endregion //region foreach / map 2 helper /** * Tells if we are able to perform any actions (foreach2) on the given length of a "collection" * @receiver [GenericCollectionExtensions] * @param length [Int] * @return [Boolean] */ public inline fun GenericCollectionExtensions.canNotForeach2(length: Int): Boolean { return (length <= 0 || length.isOdd) } //endregion
1
Kotlin
0
2
49113dd6b2cb1e18992d07faa1e0305d18f766f4
4,244
csense-kotlin
MIT License
app/src/main/java/com/yablunin/shopnstock/di/DomainModule.kt
yabluninn
702,962,028
false
null
package com.yablunin.shopnstock.di import com.yablunin.shopnstock.domain.repositories.ListHandlerRepository import com.yablunin.shopnstock.domain.repositories.ListRepository import com.yablunin.shopnstock.domain.repositories.ShoppingListHandlerRepository import com.yablunin.shopnstock.domain.repositories.ShoppingListRepository import com.yablunin.shopnstock.domain.repositories.UserRepository import com.yablunin.shopnstock.domain.usecases.list.AddItemUseCase import com.yablunin.shopnstock.domain.usecases.list.GetCompletedItemsCountUseCase import com.yablunin.shopnstock.domain.usecases.list.GetItemByIdUseCase import com.yablunin.shopnstock.domain.usecases.list.GetItemByIndexUseCase import com.yablunin.shopnstock.domain.usecases.list.GetSizeUseCase import com.yablunin.shopnstock.domain.usecases.list.RemoveItemAtUseCase import com.yablunin.shopnstock.domain.usecases.list.RemoveItemUseCase import com.yablunin.shopnstock.domain.usecases.list.handler.AddListUseCase import com.yablunin.shopnstock.domain.usecases.list.handler.CopyListUseCase import com.yablunin.shopnstock.domain.usecases.list.handler.GenerateListIdUseCase import com.yablunin.shopnstock.domain.usecases.list.handler.GetListByIdUseCase import com.yablunin.shopnstock.domain.usecases.list.handler.RemoveListUseCase import com.yablunin.shopnstock.domain.usecases.list.handler.RenameListUseCase import com.yablunin.shopnstock.domain.usecases.user.LoadUserUseCase import com.yablunin.shopnstock.domain.usecases.user.SaveUserUseCase import dagger.Module import dagger.Provides @Module class DomainModule { @Provides fun provideListRepository(): ListRepository{ return ShoppingListRepository() } @Provides fun provideListHandlerRepository(): ListHandlerRepository{ return ShoppingListHandlerRepository() } @Provides fun provideAddListUseCase(listHandlerRepository: ListHandlerRepository): AddListUseCase{ return AddListUseCase(listHandlerRepository = listHandlerRepository) } @Provides fun provideGenerateListIdUseCase(listHandlerRepository: ListHandlerRepository): GenerateListIdUseCase{ return GenerateListIdUseCase(listHandlerRepository = listHandlerRepository) } @Provides fun provideGetListIdUseCase(listHandlerRepository: ListHandlerRepository): GetListByIdUseCase{ return GetListByIdUseCase(listHandlerRepository = listHandlerRepository) } @Provides fun provideRemoveListUseCase(listHandlerRepository: ListHandlerRepository): RemoveListUseCase{ return RemoveListUseCase(listHandlerRepository = listHandlerRepository) } @Provides fun provideRenameListUseCase(listHandlerRepository: ListHandlerRepository): RenameListUseCase{ return RenameListUseCase(listHandlerRepository = listHandlerRepository) } @Provides fun provideCopyListUseCase(listHandlerRepository: ListHandlerRepository): CopyListUseCase{ return CopyListUseCase(listHandlerRepository = listHandlerRepository) } @Provides fun provideAddItemUseCase(listRepository: ListRepository): AddItemUseCase{ return AddItemUseCase(listRepository = listRepository) } @Provides fun provideGetCompletedItemsUseCase(listRepository: ListRepository): GetCompletedItemsCountUseCase{ return GetCompletedItemsCountUseCase(listRepository = listRepository) } @Provides fun provideGetItemByIdUseCase(listRepository: ListRepository): GetItemByIdUseCase{ return GetItemByIdUseCase(listRepository = listRepository) } @Provides fun provideGetItemByIndexUseCase(listRepository: ListRepository): GetItemByIndexUseCase{ return GetItemByIndexUseCase(listRepository = listRepository) } @Provides fun provideGetSizeUseCase(listRepository: ListRepository): GetSizeUseCase{ return GetSizeUseCase(listRepository = listRepository) } @Provides fun provideRemoveItemAtUseCase(listRepository: ListRepository): RemoveItemAtUseCase{ return RemoveItemAtUseCase(listRepository = listRepository) } @Provides fun provideRemoveItemUseCase(listRepository: ListRepository): RemoveItemUseCase{ return RemoveItemUseCase(listRepository = listRepository) } @Provides fun provideSaveUserUseCase(userRepository: UserRepository): SaveUserUseCase{ return SaveUserUseCase(userRepository = userRepository) } @Provides fun provideLoadUserUseCase(userRepository: UserRepository): LoadUserUseCase{ return LoadUserUseCase(userRepository = userRepository) } }
0
null
0
3
eb1b9e2f0ceda62b0cc57173034b3186aef7e3e2
4,573
shopnstock
MIT License
framework666/src/main/java/studio/attect/framework666/extensions/Context.kt
Attect
192,833,321
false
null
package studio.attect.framework666.extensions import android.app.ActivityManager import android.content.Context import android.os.Build import android.os.Environment import android.os.Handler import android.os.Looper import android.os.storage.StorageManager import org.msgpack.core.MessagePack import studio.attect.framework666.DataXOffice import studio.attect.framework666.Logcat import studio.attect.framework666.RuntimeBuildConfig import studio.attect.framework666.cache.CacheDataX import studio.attect.framework666.cache.CacheManager import studio.attect.framework666.simple.FileSafeWriteCallback import java.io.File import java.io.FileOutputStream import java.io.IOException /** * 获得进程名 * 不一定成功 * 不使用反射 */ val Context.progressName: String? get() { val pid = android.os.Process.myPid() val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? ?: return null val progress = activityManager.runningAppProcesses ?: return null progress.forEach { if (it.pid == pid) return it.processName } return null } /** * 获得App在内部储存(/data)的可用空间 * Android O以上系统可以自动释放空间,但需要调用StorageManager#allo */ fun Context.internalStorageAllocatableSpace(): Long = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val storageManager = getSystemService(Context.STORAGE_SERVICE) if (storageManager is StorageManager) { storageManager.getAllocatableBytes(StorageManager.UUID_DEFAULT) } else { 0 } } else { Environment.getDataDirectory().usableSpace } /** * 一个相对安全的文件写入文件 * 子线程中写入 * 满足各种条件后才会写入 * 不适合连续写入(如录像录音数据) * * @param file 要创建/写入的目标文件 * @param expectedSize 预计的文件大小 * @param callback 错误与成功回调 * @param writeLogic 在子线程中文件写入的逻辑,如outputStream的操作,切记不要操作UI */ fun Context.makeSureFileWriteEnvironment(file: File, expectedSize: Long, callback: FileSafeWriteCallback? = null, writeLogic: () -> Unit) { if (internalStorageAllocatableSpace() > expectedSize * 1.5) { try { val parentFile = file.parentFile if (!parentFile.exists()) { if (!parentFile.mkdirs()) { callback?.pathDirCreateFailed(parentFile.absolutePath) return } } if (!parentFile.isDirectory) { callback?.pathIsNotDirectory(parentFile.absolutePath) return } if (file.exists() && !file.canWrite()) { callback?.fileCannotWrite() return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val storageManager = getSystemService(Context.STORAGE_SERVICE) if (storageManager is StorageManager) { storageManager.allocateBytes(StorageManager.UUID_DEFAULT, expectedSize) } } } catch (e: Exception) { callback?.unexpectedError() e.printStackTrace() } val handler = Handler(Looper.getMainLooper(), Handler.Callback { callback?.success() return@Callback true }) Thread() { try { writeLogic.invoke() handler.sendEmptyMessage(0) } catch (e: Exception) { callback?.unexpectedError() try { file.delete() } catch (deleteException: Exception) { e.printStackTrace() } } }.start() } else { callback?.spaceNotEnough(((expectedSize * 1.5) - internalStorageAllocatableSpace()).toLong()) } } /** * 缓存一个DataX */ fun <T> Context.writeCacheDataX(tag: String, @CacheDataX.Companion.StoreType storeType: Int, data: T, effectiveDuration: Long = -1): Boolean { if (!CacheManager.ensureCacheDir(this)) return false val cacheDataX = CacheDataX(data).apply { this.tag = tag this.storeType = storeType this.effectiveDuration = effectiveDuration } val file = File(CacheManager.getCacheFileName(this, tag)) Logcat.d("写入缓存文件[$tag]:${file.absolutePath}") val outputStream = FileOutputStream(file) try { val packer = MessagePack.newDefaultBufferPacker() val time = System.currentTimeMillis() DataXOffice(packer).putDataX(cacheDataX) Logcat.i("序列化时间:${System.currentTimeMillis() - time}ms") if (packer.totalWrittenBytes * 2 >= internalStorageAllocatableSpace()) { Logcat.w("缓存${tag}写入失败(空间不足)") return false } outputStream.write(packer.toByteArray()) } catch (e: IllegalStateException) { Logcat.w("缓存${tag}写入失败(数据内容)") e.printStackTrace() return false } catch (e: IOException) { Logcat.w("缓存${tag}写入失败(文件系统)") e.printStackTrace() return false } finally { try { outputStream.close() } catch (e: Exception) { e.printStackTrace() return false } } return true } /** * 根据[tags]快速检测有效缓存 * 过程中失效的缓存将会被删除 * 有效的将会作为DataX返回(无数据部分) * * 应该根据返回的文件头来决定是否读取完整缓存,避免无用的性能消耗 * 比如提示用户存在草稿是否恢复…… * * MessagePack并不需要数据完整也能读出头部数据 * @return 有效的缓存文件头,不包含数据部分 */ fun Context.fastCheckCache(tags: List<String>): ArrayList<CacheDataX> { val resultArray = arrayListOf<CacheDataX>() tags.forEach { tag -> val file = File(CacheManager.getCacheFileName(this, tag)) if (file.exists() && file.isFile && file.canRead() && file.length() > CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { file.inputStream().use { input -> //先尝试读出文件头的长度数据 val preLoadByteArray = ByteArray(CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) //读取固定FILE_HEAD_LENGTH_MIN_LENGTH长度内容(如果连这点数据都没办法一次性读入……储存介质没救了) val preLoadDataSize = input.read(preLoadByteArray, 0, CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) if (preLoadDataSize < CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { if (file.delete()) { Logcat.i("缓存:${tag}文件读取失败,已删除") } else { Logcat.w("缓存:${tag}文件读取失败,且删除失败") } return@use null } //读不够直接弃了 //由DataXOffice解析出头部长度数据,如果发生任何错误都直接弃了 var headerSize = DataXOffice().unpack(preLoadByteArray).getLong()?.toInt() if (headerSize == null) { file.delete() return@use null } headerSize++ //需要多预读一位,否则MessagePack解码会出错 //除去已经预读的内容,剩下的header的长度 headerSize -= preLoadDataSize //真正的head内容数组 val remainingByteArray = ByteArray(headerSize) //不能跳过之前的长度数据!!因为MessagePack用了半字节!! var offset = 0 while (headerSize > 0) { val read = input.read(remainingByteArray, offset, headerSize) if (read < 0) break headerSize -= read offset += read } if (headerSize == 0) (preLoadByteArray + remainingByteArray) else (preLoadByteArray + remainingByteArray.copyOf(offset)) } } else { if (file.exists()) file.delete() //文件太小,删了 null //啥子玩意儿不会自动null,必须写这个else }?.let { headByteArray -> val dataXOffice = DataXOffice().apply { unpack(headByteArray) } val cacheDataX = CacheDataX(null) cacheDataX.applyFromOffice(dataXOffice) if (cacheDataX.versionCode == RuntimeBuildConfig.VERSION_CODE && //检查版本 cacheDataX.time > 0 && (cacheDataX.effectiveDuration <= 0 || (System.currentTimeMillis() - cacheDataX.time) <= cacheDataX.effectiveDuration) ) { //计算保质期 resultArray.add(cacheDataX) } else { //过期的就删了 file.delete() } } } return resultArray } /** * 读取缓存 * 同样会进行检查(但因为更费时不要用这个方法检查),期间如果发现数据无效同样会被删除 * 最好在子线程执行此方法 * * @param tag 缓存的tag * @param dataClass 数据DataX的类 * @return null为不存在有效缓存,否则tag与缓存数据成对返回 */ fun Context.readCacheDataX(tag: String, dataClass: Class<*>): Pair<String, Any>? { val file = File(CacheManager.getCacheFileName(this, tag)) if (file.exists() && file.isFile && file.canRead() && file.length() > CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { file.inputStream().use { input -> //先尝试读出文件头的长度数据 val preLoadByteArray = ByteArray(CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) //读取固定FILE_HEAD_LENGTH_MIN_LENGTH长度内容(如果连这点数据都没办法一次性读入……储存介质没救了) val preLoadDataSize = input.read(preLoadByteArray, 0, CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) if (preLoadDataSize < CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { if (file.delete()) { Logcat.i("缓存:${tag}文件读取失败,已删除") } else { Logcat.w("缓存:${tag}文件读取失败,且删除失败") } return@use null } //读不够直接弃了 //由DataXOffice解析出头部长度数据,如果发生任何错误都直接弃了 val headerSize = DataXOffice().unpack(preLoadByteArray).getLong()?.toInt() if (headerSize == null) { file.delete() return@use null } Any() } } else { if (file.exists()) file.delete() //文件太小,删了 null //啥子玩意儿不会自动null,必须写这个else }?.let { _ -> val dataXOffice = DataXOffice().apply { unpack(file.inputStream()) } // val dataX = dataClass.newInstance() val cacheDataX = CacheDataX() cacheDataX.dataClass = dataClass cacheDataX.applyFromOffice(dataXOffice) if (cacheDataX.versionCode == RuntimeBuildConfig.VERSION_CODE && //检查版本 cacheDataX.time > 0 && (cacheDataX.effectiveDuration <= 0 || (System.currentTimeMillis() - cacheDataX.time) <= cacheDataX.effectiveDuration) ) { //计算保质期 cacheDataX.data?.let { data -> return Pair(tag, data) } } else { //过期的就删了 file.delete() } } return null } /** * 检查框架的所有缓存数据,通常用于自动维护 * 失效的将会被删除,有效的保留 * 推荐子线程中处理 * 与 Context#fastCheckCache规则一致 */ fun Context.autoCleanCacheDataX() { val cacheDir = File(CacheManager.getCacheFileName(this, "")).parentFile if (!cacheDir.canWrite() || !cacheDir.canWrite()) return //文件系统损坏或权限错乱就不操作了 if (!cacheDir.isDirectory) cacheDir.delete() val files = cacheDir.listFiles() files.forEach { file -> if (file.exists() && file.isFile && file.canRead() && file.length() > CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { file.inputStream().use { input -> //先尝试读出文件头的长度数据 val preLoadByteArray = ByteArray(CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) //读取固定FILE_HEAD_LENGTH_MIN_LENGTH长度内容(如果连这点数据都没办法一次性读入……储存介质没救了) val preLoadDataSize = input.read(preLoadByteArray, 0, CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) if (preLoadDataSize < CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { if (file.delete()) { Logcat.i("缓存:${file.name}文件读取失败,已删除") } else { Logcat.w("缓存:${file.name}文件读取失败,且删除失败") } return@use null } //读不够直接弃了 //由DataXOffice解析出头部长度数据,如果发生任何错误都直接弃了 var headerSize = DataXOffice().unpack(preLoadByteArray).getLong()?.toInt() if (headerSize == null) { file.delete() return@use null } headerSize++ //需要多预读一位,否则MessagePack解码会出错 //除去已经预读的内容,剩下的header的长度 headerSize -= preLoadDataSize //真正的head内容数组 val remainingByteArray = ByteArray(headerSize) //不能跳过之前的长度数据!!因为MessagePack用了半字节!! var offset = 0 while (headerSize > 0) { val read = input.read(remainingByteArray, offset, headerSize) if (read < 0) break headerSize -= read offset += read } if (headerSize == 0) (preLoadByteArray + remainingByteArray) else (preLoadByteArray + remainingByteArray.copyOf(offset)) } } else { if (file.exists()) file.delete() //文件太小,删了 null //啥子玩意儿不会自动null,必须写这个else }?.let { headByteArray -> val dataXOffice = DataXOffice().apply { unpack(headByteArray) } val cacheDataX = CacheDataX(null) cacheDataX.applyFromOffice(dataXOffice) if (cacheDataX.versionCode == RuntimeBuildConfig.VERSION_CODE && //检查版本 cacheDataX.time > 0 && (cacheDataX.effectiveDuration <= 0 || (System.currentTimeMillis() - cacheDataX.time) <= cacheDataX.effectiveDuration) ) { } else { //过期的就删了 file.delete() } } } } /** * 请求删除缓存数据 * 不一定成功 * * 可以主线程操作 * @return 是否成功删除 */ fun Context.deleteCacheDataX(tag: String): Boolean { val file = File(CacheManager.getCacheFileName(this, tag)) if (file.exists() && file.canWrite()) { return file.delete() } return false }
0
null
1
6
22285ee7026abf6fd00150af6a96d12287154336
13,524
Android-Framework666
Apache License 2.0
framework666/src/main/java/studio/attect/framework666/extensions/Context.kt
Attect
192,833,321
false
null
package studio.attect.framework666.extensions import android.app.ActivityManager import android.content.Context import android.os.Build import android.os.Environment import android.os.Handler import android.os.Looper import android.os.storage.StorageManager import org.msgpack.core.MessagePack import studio.attect.framework666.DataXOffice import studio.attect.framework666.Logcat import studio.attect.framework666.RuntimeBuildConfig import studio.attect.framework666.cache.CacheDataX import studio.attect.framework666.cache.CacheManager import studio.attect.framework666.simple.FileSafeWriteCallback import java.io.File import java.io.FileOutputStream import java.io.IOException /** * 获得进程名 * 不一定成功 * 不使用反射 */ val Context.progressName: String? get() { val pid = android.os.Process.myPid() val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? ?: return null val progress = activityManager.runningAppProcesses ?: return null progress.forEach { if (it.pid == pid) return it.processName } return null } /** * 获得App在内部储存(/data)的可用空间 * Android O以上系统可以自动释放空间,但需要调用StorageManager#allo */ fun Context.internalStorageAllocatableSpace(): Long = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val storageManager = getSystemService(Context.STORAGE_SERVICE) if (storageManager is StorageManager) { storageManager.getAllocatableBytes(StorageManager.UUID_DEFAULT) } else { 0 } } else { Environment.getDataDirectory().usableSpace } /** * 一个相对安全的文件写入文件 * 子线程中写入 * 满足各种条件后才会写入 * 不适合连续写入(如录像录音数据) * * @param file 要创建/写入的目标文件 * @param expectedSize 预计的文件大小 * @param callback 错误与成功回调 * @param writeLogic 在子线程中文件写入的逻辑,如outputStream的操作,切记不要操作UI */ fun Context.makeSureFileWriteEnvironment(file: File, expectedSize: Long, callback: FileSafeWriteCallback? = null, writeLogic: () -> Unit) { if (internalStorageAllocatableSpace() > expectedSize * 1.5) { try { val parentFile = file.parentFile if (!parentFile.exists()) { if (!parentFile.mkdirs()) { callback?.pathDirCreateFailed(parentFile.absolutePath) return } } if (!parentFile.isDirectory) { callback?.pathIsNotDirectory(parentFile.absolutePath) return } if (file.exists() && !file.canWrite()) { callback?.fileCannotWrite() return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val storageManager = getSystemService(Context.STORAGE_SERVICE) if (storageManager is StorageManager) { storageManager.allocateBytes(StorageManager.UUID_DEFAULT, expectedSize) } } } catch (e: Exception) { callback?.unexpectedError() e.printStackTrace() } val handler = Handler(Looper.getMainLooper(), Handler.Callback { callback?.success() return@Callback true }) Thread() { try { writeLogic.invoke() handler.sendEmptyMessage(0) } catch (e: Exception) { callback?.unexpectedError() try { file.delete() } catch (deleteException: Exception) { e.printStackTrace() } } }.start() } else { callback?.spaceNotEnough(((expectedSize * 1.5) - internalStorageAllocatableSpace()).toLong()) } } /** * 缓存一个DataX */ fun <T> Context.writeCacheDataX(tag: String, @CacheDataX.Companion.StoreType storeType: Int, data: T, effectiveDuration: Long = -1): Boolean { if (!CacheManager.ensureCacheDir(this)) return false val cacheDataX = CacheDataX(data).apply { this.tag = tag this.storeType = storeType this.effectiveDuration = effectiveDuration } val file = File(CacheManager.getCacheFileName(this, tag)) Logcat.d("写入缓存文件[$tag]:${file.absolutePath}") val outputStream = FileOutputStream(file) try { val packer = MessagePack.newDefaultBufferPacker() val time = System.currentTimeMillis() DataXOffice(packer).putDataX(cacheDataX) Logcat.i("序列化时间:${System.currentTimeMillis() - time}ms") if (packer.totalWrittenBytes * 2 >= internalStorageAllocatableSpace()) { Logcat.w("缓存${tag}写入失败(空间不足)") return false } outputStream.write(packer.toByteArray()) } catch (e: IllegalStateException) { Logcat.w("缓存${tag}写入失败(数据内容)") e.printStackTrace() return false } catch (e: IOException) { Logcat.w("缓存${tag}写入失败(文件系统)") e.printStackTrace() return false } finally { try { outputStream.close() } catch (e: Exception) { e.printStackTrace() return false } } return true } /** * 根据[tags]快速检测有效缓存 * 过程中失效的缓存将会被删除 * 有效的将会作为DataX返回(无数据部分) * * 应该根据返回的文件头来决定是否读取完整缓存,避免无用的性能消耗 * 比如提示用户存在草稿是否恢复…… * * MessagePack并不需要数据完整也能读出头部数据 * @return 有效的缓存文件头,不包含数据部分 */ fun Context.fastCheckCache(tags: List<String>): ArrayList<CacheDataX> { val resultArray = arrayListOf<CacheDataX>() tags.forEach { tag -> val file = File(CacheManager.getCacheFileName(this, tag)) if (file.exists() && file.isFile && file.canRead() && file.length() > CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { file.inputStream().use { input -> //先尝试读出文件头的长度数据 val preLoadByteArray = ByteArray(CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) //读取固定FILE_HEAD_LENGTH_MIN_LENGTH长度内容(如果连这点数据都没办法一次性读入……储存介质没救了) val preLoadDataSize = input.read(preLoadByteArray, 0, CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) if (preLoadDataSize < CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { if (file.delete()) { Logcat.i("缓存:${tag}文件读取失败,已删除") } else { Logcat.w("缓存:${tag}文件读取失败,且删除失败") } return@use null } //读不够直接弃了 //由DataXOffice解析出头部长度数据,如果发生任何错误都直接弃了 var headerSize = DataXOffice().unpack(preLoadByteArray).getLong()?.toInt() if (headerSize == null) { file.delete() return@use null } headerSize++ //需要多预读一位,否则MessagePack解码会出错 //除去已经预读的内容,剩下的header的长度 headerSize -= preLoadDataSize //真正的head内容数组 val remainingByteArray = ByteArray(headerSize) //不能跳过之前的长度数据!!因为MessagePack用了半字节!! var offset = 0 while (headerSize > 0) { val read = input.read(remainingByteArray, offset, headerSize) if (read < 0) break headerSize -= read offset += read } if (headerSize == 0) (preLoadByteArray + remainingByteArray) else (preLoadByteArray + remainingByteArray.copyOf(offset)) } } else { if (file.exists()) file.delete() //文件太小,删了 null //啥子玩意儿不会自动null,必须写这个else }?.let { headByteArray -> val dataXOffice = DataXOffice().apply { unpack(headByteArray) } val cacheDataX = CacheDataX(null) cacheDataX.applyFromOffice(dataXOffice) if (cacheDataX.versionCode == RuntimeBuildConfig.VERSION_CODE && //检查版本 cacheDataX.time > 0 && (cacheDataX.effectiveDuration <= 0 || (System.currentTimeMillis() - cacheDataX.time) <= cacheDataX.effectiveDuration) ) { //计算保质期 resultArray.add(cacheDataX) } else { //过期的就删了 file.delete() } } } return resultArray } /** * 读取缓存 * 同样会进行检查(但因为更费时不要用这个方法检查),期间如果发现数据无效同样会被删除 * 最好在子线程执行此方法 * * @param tag 缓存的tag * @param dataClass 数据DataX的类 * @return null为不存在有效缓存,否则tag与缓存数据成对返回 */ fun Context.readCacheDataX(tag: String, dataClass: Class<*>): Pair<String, Any>? { val file = File(CacheManager.getCacheFileName(this, tag)) if (file.exists() && file.isFile && file.canRead() && file.length() > CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { file.inputStream().use { input -> //先尝试读出文件头的长度数据 val preLoadByteArray = ByteArray(CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) //读取固定FILE_HEAD_LENGTH_MIN_LENGTH长度内容(如果连这点数据都没办法一次性读入……储存介质没救了) val preLoadDataSize = input.read(preLoadByteArray, 0, CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) if (preLoadDataSize < CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { if (file.delete()) { Logcat.i("缓存:${tag}文件读取失败,已删除") } else { Logcat.w("缓存:${tag}文件读取失败,且删除失败") } return@use null } //读不够直接弃了 //由DataXOffice解析出头部长度数据,如果发生任何错误都直接弃了 val headerSize = DataXOffice().unpack(preLoadByteArray).getLong()?.toInt() if (headerSize == null) { file.delete() return@use null } Any() } } else { if (file.exists()) file.delete() //文件太小,删了 null //啥子玩意儿不会自动null,必须写这个else }?.let { _ -> val dataXOffice = DataXOffice().apply { unpack(file.inputStream()) } // val dataX = dataClass.newInstance() val cacheDataX = CacheDataX() cacheDataX.dataClass = dataClass cacheDataX.applyFromOffice(dataXOffice) if (cacheDataX.versionCode == RuntimeBuildConfig.VERSION_CODE && //检查版本 cacheDataX.time > 0 && (cacheDataX.effectiveDuration <= 0 || (System.currentTimeMillis() - cacheDataX.time) <= cacheDataX.effectiveDuration) ) { //计算保质期 cacheDataX.data?.let { data -> return Pair(tag, data) } } else { //过期的就删了 file.delete() } } return null } /** * 检查框架的所有缓存数据,通常用于自动维护 * 失效的将会被删除,有效的保留 * 推荐子线程中处理 * 与 Context#fastCheckCache规则一致 */ fun Context.autoCleanCacheDataX() { val cacheDir = File(CacheManager.getCacheFileName(this, "")).parentFile if (!cacheDir.canWrite() || !cacheDir.canWrite()) return //文件系统损坏或权限错乱就不操作了 if (!cacheDir.isDirectory) cacheDir.delete() val files = cacheDir.listFiles() files.forEach { file -> if (file.exists() && file.isFile && file.canRead() && file.length() > CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { file.inputStream().use { input -> //先尝试读出文件头的长度数据 val preLoadByteArray = ByteArray(CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) //读取固定FILE_HEAD_LENGTH_MIN_LENGTH长度内容(如果连这点数据都没办法一次性读入……储存介质没救了) val preLoadDataSize = input.read(preLoadByteArray, 0, CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) if (preLoadDataSize < CacheDataX.FILE_HEAD_LENGTH_MIN_LENGTH) { if (file.delete()) { Logcat.i("缓存:${file.name}文件读取失败,已删除") } else { Logcat.w("缓存:${file.name}文件读取失败,且删除失败") } return@use null } //读不够直接弃了 //由DataXOffice解析出头部长度数据,如果发生任何错误都直接弃了 var headerSize = DataXOffice().unpack(preLoadByteArray).getLong()?.toInt() if (headerSize == null) { file.delete() return@use null } headerSize++ //需要多预读一位,否则MessagePack解码会出错 //除去已经预读的内容,剩下的header的长度 headerSize -= preLoadDataSize //真正的head内容数组 val remainingByteArray = ByteArray(headerSize) //不能跳过之前的长度数据!!因为MessagePack用了半字节!! var offset = 0 while (headerSize > 0) { val read = input.read(remainingByteArray, offset, headerSize) if (read < 0) break headerSize -= read offset += read } if (headerSize == 0) (preLoadByteArray + remainingByteArray) else (preLoadByteArray + remainingByteArray.copyOf(offset)) } } else { if (file.exists()) file.delete() //文件太小,删了 null //啥子玩意儿不会自动null,必须写这个else }?.let { headByteArray -> val dataXOffice = DataXOffice().apply { unpack(headByteArray) } val cacheDataX = CacheDataX(null) cacheDataX.applyFromOffice(dataXOffice) if (cacheDataX.versionCode == RuntimeBuildConfig.VERSION_CODE && //检查版本 cacheDataX.time > 0 && (cacheDataX.effectiveDuration <= 0 || (System.currentTimeMillis() - cacheDataX.time) <= cacheDataX.effectiveDuration) ) { } else { //过期的就删了 file.delete() } } } } /** * 请求删除缓存数据 * 不一定成功 * * 可以主线程操作 * @return 是否成功删除 */ fun Context.deleteCacheDataX(tag: String): Boolean { val file = File(CacheManager.getCacheFileName(this, tag)) if (file.exists() && file.canWrite()) { return file.delete() } return false }
0
null
1
6
22285ee7026abf6fd00150af6a96d12287154336
13,524
Android-Framework666
Apache License 2.0
base-domain/src/main/kotlin/org/ossiaustria/lib/domain/database/NfcInfoDao.kt
ossi-austria
430,606,582
false
{"Kotlin": 456155, "HTML": 2066, "Dockerfile": 441}
package org.ossiaustria.lib.domain.database import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import kotlinx.coroutines.flow.Flow import org.ossiaustria.lib.domain.database.entities.NfcInfoEntity import java.util.* @Dao abstract class NfcInfoDao : AbstractEntityDao<NfcInfoEntity, NfcInfoEntity>() { @Query("DELETE FROM nfcs") abstract override suspend fun deleteAll() @Query("DELETE FROM nfcs where nfcTagId = :id") abstract override suspend fun deleteById(id: UUID) @Transaction @Query("SELECT * FROM nfcs ORDER BY createdAt ASC") abstract override fun findAll(): Flow<List<NfcInfoEntity>> @Transaction @Query("SELECT * FROM nfcs where nfcTagId = :id") abstract override fun findById(id: UUID): Flow<NfcInfoEntity> }
0
Kotlin
0
1
8d8b167555d62e6ceb58a20efe9d6ee0c609b199
800
amigo-box
MIT License
sphinx/application/network/concepts/concept-link-preview/src/main/java/chat/sphinx/concept_link_preview/LinkPreviewHandler.kt
stakwork
340,103,148
false
{"Kotlin": 4008358, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.concept_link_preview import chat.sphinx.wrapper_common.tribe.TribeJoinLink import chat.sphinx.concept_link_preview.model.HtmlPreviewData import chat.sphinx.concept_link_preview.model.TribePreviewData abstract class LinkPreviewHandler { abstract suspend fun retrieveHtmlPreview(url: String): HtmlPreviewData? abstract suspend fun retrieveTribeLinkPreview(tribeJoinLink: TribeJoinLink): TribePreviewData? }
96
Kotlin
11
18
64eb5948ee1878cea6f375adc94ac173f25919fa
435
sphinx-kotlin
MIT License
src/main/kotlin/model/Course.kt
KevinD-UP
278,425,508
false
null
package model data class Course(val id: Int, val title: String, val level: Int, val isActive: Boolean)
0
Kotlin
0
0
87e60d33325946e09e787637397d5a220fc03882
157
OCWebServer
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsalertsapi/service/event/AlertEventServiceTest.kt
ministryofjustice
750,461,021
false
{"Kotlin": 693597, "Shell": 1834, "Mermaid": 1398, "Dockerfile": 1372}
package uk.gov.justice.digital.hmpps.hmppsalertsapi.service.event import com.microsoft.applicationinsights.TelemetryClient import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import uk.gov.justice.digital.hmpps.hmppsalertsapi.common.toZoneDateTime import uk.gov.justice.digital.hmpps.hmppsalertsapi.config.EventProperties import uk.gov.justice.digital.hmpps.hmppsalertsapi.entity.event.AlertAdditionalInformation import uk.gov.justice.digital.hmpps.hmppsalertsapi.entity.event.AlertCreatedEvent import uk.gov.justice.digital.hmpps.hmppsalertsapi.entity.event.AlertDomainEvent import uk.gov.justice.digital.hmpps.hmppsalertsapi.entity.event.PersonReference import uk.gov.justice.digital.hmpps.hmppsalertsapi.enumeration.DomainEventType.ALERT_CREATED import uk.gov.justice.digital.hmpps.hmppsalertsapi.enumeration.Source.NOMIS import uk.gov.justice.digital.hmpps.hmppsalertsapi.integration.wiremock.PRISON_NUMBER import uk.gov.justice.digital.hmpps.hmppsalertsapi.integration.wiremock.TEST_USER import uk.gov.justice.digital.hmpps.hmppsalertsapi.utils.ALERT_CODE_VICTIM import java.time.LocalDateTime import java.util.UUID class AlertEventServiceTest { private val telemetryClient = mock<TelemetryClient>() private val domainEventPublisher = mock<DomainEventPublisher>() private val baseUrl = "http://localhost:8080" @Test fun `handle alert event - publish enabled`() { val eventProperties = EventProperties(true, baseUrl) val alertEventService = AlertEventService(eventProperties, telemetryClient, domainEventPublisher) val alertEvent = AlertCreatedEvent( UUID.randomUUID(), PRISON_NUMBER, ALERT_CODE_VICTIM, LocalDateTime.now(), NOMIS, TEST_USER, ) alertEventService.handleAlertEvent(alertEvent) val domainEventCaptor = argumentCaptor<AlertDomainEvent<AlertAdditionalInformation>>() verify(domainEventPublisher).publish(domainEventCaptor.capture()) assertThat(domainEventCaptor.firstValue).isEqualTo( AlertDomainEvent( eventType = ALERT_CREATED.eventType, additionalInformation = AlertAdditionalInformation( alertUuid = alertEvent.alertUuid, alertCode = alertEvent.alertCode, source = alertEvent.source, ), description = ALERT_CREATED.description, occurredAt = alertEvent.occurredAt.toZoneDateTime(), detailUrl = "$baseUrl/alerts/${alertEvent.alertUuid}", personReference = PersonReference.withPrisonNumber(alertEvent.prisonNumber), ), ) } @Test fun `handle alert event - publish disabled`() { val eventProperties = EventProperties(false, baseUrl) val alertEventService = AlertEventService(eventProperties, telemetryClient, domainEventPublisher) val alertEvent = AlertCreatedEvent( UUID.randomUUID(), PRISON_NUMBER, ALERT_CODE_VICTIM, LocalDateTime.now(), NOMIS, TEST_USER, ) alertEventService.handleAlertEvent(alertEvent) verify(domainEventPublisher, never()).publish(any<AlertDomainEvent<AlertAdditionalInformation>>()) } }
1
Kotlin
1
0
ff2c9aee38daa3cc0654b7957a9da0ffca7ceee8
3,282
hmpps-alerts-api
MIT License
app/src/main/java/com/kyant/pixelmusic/ui/sharedelements/MathUtils.kt
Kyant0
334,608,108
false
null
package sharedelementtransaction import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.layout.ScaleFactor import androidx.compose.ui.layout.lerp internal val Rect.area: Float get() = width * height internal operator fun Size.div(operand: Size): ScaleFactor = ScaleFactor(width / operand.width, height / operand.height) internal fun calculateDirection(start: Rect, end: Rect): TransitionDirection = if (end.area > start.area) TransitionDirection.Enter else TransitionDirection.Return internal fun calculateAlpha( direction: TransitionDirection?, fadeMode: FadeMode?, fraction: Float, // Absolute isStart: Boolean ) = when (fadeMode) { FadeMode.In, null -> if (isStart) 1f else fraction FadeMode.Out -> if (isStart) 1 - fraction else 1f FadeMode.Cross -> if (isStart) 1 - fraction else fraction FadeMode.Through -> { val threshold = if (direction == TransitionDirection.Enter) FadeThroughProgressThreshold else 1 - FadeThroughProgressThreshold if (fraction < threshold) { if (isStart) 1 - fraction / threshold else 0f } else { if (isStart) 0f else (fraction - threshold) / (1 - threshold) } } } internal fun calculateOffset( start: Rect, end: Rect?, fraction: Float, // Relative pathMotion: PathMotion?, width: Float ): Offset = if (end == null) start.topLeft else { val topCenter = pathMotion!!.invoke( start.topCenter, end.topCenter, fraction ) Offset(topCenter.x - width / 2, topCenter.y) } internal val Identity = ScaleFactor(1f, 1f) internal fun calculateScale( start: Rect, end: Rect?, fraction: Float // Relative ): ScaleFactor = if (end == null) Identity else lerp(Identity, end.size / start.size, fraction)
2
Kotlin
9
95
e94362a4bc9c6da13b1a1848dce528975bf52b13
1,911
PixelMusic
Apache License 2.0
core/src/main/kotlin/com/justai/jaicf/plugin/PathValue.kt
just-ai
246,869,336
false
null
package com.justai.jaicf.plugin /** * This annotation indicates to the plugin that a StatePath will be passed to the annotated parameter or receiver. * This allows you to use the plugin's features, such as state navigation and inspections. To use it, * you need to annotate a parameter of a function or a primary constructor that takes a state name. * Also, you can annotate a receiver type of extensions function or a String expression inside a function. * * Examples: * ``` * fun @PathValue String.and(@PathValue that: String) {} * * fun example() { * val a = @PathValue "../a" * } * * ``` */ @Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE, AnnotationTarget.EXPRESSION) @Retention(AnnotationRetention.SOURCE) annotation class PathValue()
21
null
39
241
cc076db73e03bf89db2ab94e7f48c8736735706b
777
jaicf-kotlin
Apache License 2.0
app/src/main/java/com/newgamesoftware/moviesappdemo/subviews/imageViews/ImageViewTop.kt
nejatboy
426,532,203
false
null
package com.newgamesoftware.moviesappdemo.subviews.imageViews import android.content.Context import androidx.constraintlayout.widget.ConstraintLayout import com.newgamesoftware.moviesappdemo.base.view.imageView.BaseImageView class ImageViewTop(context: Context) : BaseImageView(context) { init { layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT).apply { dimensionRatio = "1.78" } } }
0
Kotlin
0
2
f1f4a0f21834b1f32d914cd4a0e089d0a587a46e
513
MoviesDemo-Android
MIT License
app/src/main/java/com/boolder/boolder/view/detail/composable/CircuitControls.kt
boolder-org
566,723,758
false
null
package com.boolder.boolder.view.detail.composable import androidx.annotation.DrawableRes import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.compose.ui.unit.dp import com.boolder.boolder.R import com.boolder.boolder.domain.model.CircuitColor import com.boolder.boolder.domain.model.CircuitInfo import com.boolder.boolder.view.compose.BoolderTheme @Composable fun CircuitControls( circuitInfo: CircuitInfo, onPreviousProblemClicked: () -> Unit, onNextProblemClicked: () -> Unit, modifier: Modifier = Modifier ) { if (circuitInfo.previousProblemId == null && circuitInfo.nextProblemId == null) return Row( modifier = modifier.padding(16.dp) ) { circuitInfo.previousProblemId?.let { CircuitControlButton( iconRes = R.drawable.ic_arrow_back, contentDescription = stringResource(id = R.string.cd_circuit_previous_boulder_problem), circuitColor = circuitInfo.color, onClick = { onPreviousProblemClicked() } ) } Spacer(modifier = Modifier.weight(1f)) circuitInfo.nextProblemId?.let { CircuitControlButton( iconRes = R.drawable.ic_arrow_forward, contentDescription = stringResource(id = R.string.cd_circuit_next_boulder_problem), circuitColor = circuitInfo.color, onClick = { onNextProblemClicked() } ) } } } @Composable private fun CircuitControlButton( @DrawableRes iconRes: Int, contentDescription: String, circuitColor: CircuitColor, onClick: () -> Unit ) { Icon( modifier = Modifier .clip(shape = CircleShape) .background(color = Color.White, shape = CircleShape) .clickable(onClick = onClick) .padding(8.dp), painter = painterResource(id = iconRes), contentDescription = contentDescription, tint = when (circuitColor) { CircuitColor.WHITE, CircuitColor.WHITEFORKIDS -> Color.Black else -> colorResource(id = circuitColor.colorRes) } ) } @Preview @Composable private fun CircuitControlsPreview( @PreviewParameter(CircuitControlsPreviewParameterProvider::class) circuitColor: CircuitColor ) { BoolderTheme { CircuitControls( circuitInfo = CircuitInfo( color = circuitColor, previousProblemId = 9, nextProblemId = 11 ), onPreviousProblemClicked = {}, onNextProblemClicked = {} ) } } private class CircuitControlsPreviewParameterProvider : PreviewParameterProvider<CircuitColor> { override val values = CircuitColor.entries.asSequence() }
7
null
9
26
dd93a7b9c29ee0eec80b63a62de4b5eea7203f6e
3,546
boolder-android
MIT License
core/src/main/kotlin/no/nav/poao_tilgang/core/provider/GeografiskTilknyttetEnhetProvider.kt
navikt
491,417,288
false
null
package no.nav.poao_tilgang.core.provider import no.nav.poao_tilgang.core.domain.NavEnhetId import no.nav.poao_tilgang.core.domain.NorskIdent interface GeografiskTilknyttetEnhetProvider { fun hentGeografiskTilknytetEnhet(norskIdent: NorskIdent): NavEnhetId? }
3
Kotlin
0
0
720f11182c5e648ff74a21cf030a02a2449318bf
264
poao-tilgang
MIT License
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddModifierFixFE10.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.psi.PsiFile import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.idea.util.collectAllExpectAndActualDeclaration import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.TypeUtils /** Similar to [AddModifierFix] but with multi-platform support. */ open class AddModifierFixFE10( element: KtModifierListOwner, modifier: KtModifierKeywordToken ) : AddModifierFix(element, modifier) { override fun startInWriteAction(): Boolean = !modifier.isMultiplatformPersistent() || (element?.hasActualModifier() != true && element?.hasExpectModifier() != true) override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) { val originalElement = element if (originalElement is KtDeclaration && modifier.isMultiplatformPersistent()) { val elementsToMutate = originalElement.collectAllExpectAndActualDeclaration(withSelf = true) if (elementsToMutate.size > 1 && modifier in modifiersWithWarning) { val dialog = MessageDialogBuilder.okCancel( KotlinBundle.message("fix.potentially.broken.inheritance.title"), KotlinBundle.message("fix.potentially.broken.inheritance.message"), ).asWarning() if (!dialog.ask(project)) return } runWriteActionIfPhysical(originalElement) { for (declaration in elementsToMutate) { invokeOnElement(declaration) } } } else { invokeOnElement(originalElement) } } override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean { val element = element ?: return false return element.canRefactor() } companion object : Factory<AddModifierFixFE10> { private fun KtModifierKeywordToken.isMultiplatformPersistent(): Boolean = this in MODALITY_MODIFIERS || this == INLINE_KEYWORD override fun createModifierFix(element: KtModifierListOwner, modifier: KtModifierKeywordToken): AddModifierFixFE10 = AddModifierFixFE10(element, modifier) } object MakeClassOpenFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val typeReference = diagnostic.psiElement as KtTypeReference val declaration = typeReference.classForRefactor() ?: return null if (declaration.isEnum() || declaration.isData()) return null return AddModifierFixFE10(declaration, OPEN_KEYWORD) } } object AddLateinitFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val property = Errors.MUST_BE_INITIALIZED_OR_BE_ABSTRACT.cast(diagnostic).psiElement if (!property.isVar) return null val descriptor = property.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return null val type = (descriptor as? PropertyDescriptor)?.type ?: return null if (TypeUtils.isNullableType(type)) return null if (KotlinBuiltIns.isPrimitiveType(type)) return null return AddModifierFixFE10(property, LATEINIT_KEYWORD) } } } fun KtTypeReference.classForRefactor(): KtClass? { val bindingContext = analyze(BodyResolveMode.PARTIAL) val type = bindingContext[BindingContext.TYPE, this] ?: return null val classDescriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return null val declaration = DescriptorToSourceUtils.descriptorToDeclaration(classDescriptor) as? KtClass ?: return null if (!declaration.canRefactor()) return null return declaration }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
5,121
intellij-community
Apache License 2.0
app/src/main/java/com/example/moviedatabase/favourites/data/entity/FavouriteMapper.kt
ali-gevari
838,166,478
false
{"Kotlin": 192241}
package com.example.moviedatabase.favourites.data.entity import com.example.moviedatabase.allMovies.data.entity.MovieDto import com.example.moviedatabase.allShows.data.entity.ShowDto import com.example.moviedatabase.favourites.domain.entity.FavouriteProgram import com.example.moviedatabase.util.Constant.IMAGE_BASE_URL import com.example.moviedatabase.util.ProgramType import javax.inject.Inject class FavouriteMapper @Inject constructor() { fun mapMoviesToFavouriteProgram(movies: List<MovieDto>): List<FavouriteProgram> { val favouritePrograms = mutableListOf<FavouriteProgram>() movies.forEach { movie -> favouritePrograms.add( FavouriteProgram( id = movie.id, title = movie.title, image = IMAGE_BASE_URL + movie.posterPath, programType = ProgramType.Movie ) ) } return favouritePrograms } fun mapShowsToFavouritePrograms(shows: List<ShowDto>): List<FavouriteProgram> { val favouritePrograms = mutableListOf<FavouriteProgram>() shows.forEach { show -> favouritePrograms.add( FavouriteProgram( id = show.id, title = show.title, image = IMAGE_BASE_URL + show.posterPath, programType = ProgramType.TV ) ) } return favouritePrograms } }
1
Kotlin
0
0
764509e150c28857d2992f2d2e1b427faaa0c5f7
1,491
MovieDatabase
Apache License 2.0
samples/src/main/kotlin/com/simplemobiletools/fileproperties/samples/MainActivity.kt
srkns
83,441,285
true
{"Kotlin": 9412}
package com.simplemobiletools.fileproperties.samples import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import com.simplemobiletools.filepicker.dialogs.FilePickerDialog import com.simplemobiletools.filepicker.extensions.hasStoragePermission import com.simplemobiletools.fileproperties.dialogs.PropertiesDialog import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { val STORAGE_PERMISSION = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) select_file_button.setOnClickListener { if (hasStoragePermission()) showFilePicker() else requestStoragePermission() } } private fun showFilePicker() { FilePickerDialog(this, listener = object : FilePickerDialog.OnFilePickerListener { override fun onFail(error: FilePickerDialog.FilePickerResult) { } override fun onSuccess(pickedPath: String) { PropertiesDialog(this@MainActivity, pickedPath) } }) } private fun requestStoragePermission() = ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == STORAGE_PERMISSION && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showFilePicker() } } }
0
Kotlin
0
0
a8b4d2a164427bb9525c10442f9ac0942276d6ed
1,831
Simple-File-Properties
Apache License 2.0
presentation/src/main/kotlin/com/yossisegev/movienight/popularmovies/PopularMoviesViewModel.kt
mrsegev
122,669,273
false
null
package com.yossisegev.movienight.popularmovies import android.arch.lifecycle.MutableLiveData import com.yossisegev.domain.Mapper import com.yossisegev.domain.entities.MovieEntity import com.yossisegev.domain.usecases.GetPopularMovies import com.yossisegev.movienight.common.BaseViewModel import com.yossisegev.movienight.common.SingleLiveEvent import com.yossisegev.movienight.entities.Movie /** * Created by <NAME> on 11/11/2017. */ class PopularMoviesViewModel(private val getPopularMovies: GetPopularMovies, private val movieEntityMovieMapper: Mapper<MovieEntity, Movie>) : BaseViewModel() { var viewState: MutableLiveData<PopularMoviesViewState> = MutableLiveData() var errorState: SingleLiveEvent<Throwable?> = SingleLiveEvent() init { viewState.value = PopularMoviesViewState() } fun getPopularMovies() { addDisposable(getPopularMovies.observable() .flatMap { movieEntityMovieMapper.observable(it) } .subscribe({ movies -> viewState.value?.let { val newState = this.viewState.value?.copy(showLoading = false, movies = movies) this.viewState.value = newState this.errorState.value = null } }, { viewState.value = viewState.value?.copy(showLoading = false) errorState.value = it })) } }
7
null
147
772
7df52e6c93d6932b4b58de9f4f906f86df93dce1
1,493
MovieNight
Apache License 2.0
time/src/commonMain/kotlin/com/merseyside/merseyLib/time/ext/CollectionExt.kt
Merseyside
396,607,192
false
null
package com.merseyside.merseyLib.time.ext import com.merseyside.merseyLib.time.TimeUnit import com.merseyside.merseyLib.time.plus fun List<TimeUnit>.sum(): TimeUnit { var sum = TimeUnit.getEmpty() forEach { sum += it } return sum } inline fun <T> Iterable<T>.sumOf(selector: (T) -> TimeUnit): TimeUnit { var sum: TimeUnit = TimeUnit.getEmpty() for (element in this) { sum += selector(element) } return sum }
0
Kotlin
0
0
6c3fc6caade990ad92562f89bc33beb77072f879
447
mersey-kmp-time
Apache License 2.0
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/ProgressionHandlers.kt
walltz556
212,946,144
false
null
/* * Copyright 2010-2019 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.lower.loops import org.jetbrains.kotlin.backend.common.CommonBackendContext import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.lower.matchers.Quantifier import org.jetbrains.kotlin.backend.common.lower.matchers.SimpleCalleeMatcher import org.jetbrains.kotlin.backend.common.lower.matchers.createIrCallMatcher import org.jetbrains.kotlin.backend.common.lower.matchers.singleArgumentExtension import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.isPrimitiveArray import org.jetbrains.kotlin.ir.util.properties import org.jetbrains.kotlin.ir.visitors.IrElementVisitor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name /** Builds a [HeaderInfo] for progressions built using the `rangeTo` function. */ internal class RangeToHandler(private val context: CommonBackendContext, private val progressionElementTypes: Collection<IrType>) : ProgressionHandler { override val matcher = SimpleCalleeMatcher { dispatchReceiver { it != null && it.type in progressionElementTypes } fqName { it.pathSegments().last() == Name.identifier("rangeTo") } parameterCount { it == 1 } parameter(0) { it.type in progressionElementTypes } } override fun build(expression: IrCall, data: ProgressionType, scopeOwner: IrSymbol) = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { ProgressionHeaderInfo( data, first = expression.dispatchReceiver!!, last = expression.getValueArgument(0)!!, step = irInt(1), direction = ProgressionDirection.INCREASING ) } } /** Builds a [HeaderInfo] for progressions built using the `downTo` extension function. */ internal class DownToHandler(private val context: CommonBackendContext, private val progressionElementTypes: Collection<IrType>) : ProgressionHandler { override val matcher = SimpleCalleeMatcher { singleArgumentExtension(FqName("kotlin.ranges.downTo"), progressionElementTypes) parameterCount { it == 1 } parameter(0) { it.type in progressionElementTypes } } override fun build(expression: IrCall, data: ProgressionType, scopeOwner: IrSymbol): HeaderInfo? = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { ProgressionHeaderInfo( data, first = expression.extensionReceiver!!, last = expression.getValueArgument(0)!!, step = irInt(-1), direction = ProgressionDirection.DECREASING ) } } /** Builds a [HeaderInfo] for progressions built using the `until` extension function. */ internal class UntilHandler(private val context: CommonBackendContext, private val progressionElementTypes: Collection<IrType>) : ProgressionHandler { override val matcher = SimpleCalleeMatcher { singleArgumentExtension(FqName("kotlin.ranges.until"), progressionElementTypes) parameterCount { it == 1 } parameter(0) { it.type in progressionElementTypes } } override fun build(expression: IrCall, data: ProgressionType, scopeOwner: IrSymbol): HeaderInfo? = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { // `A until B` is essentially the same as `A .. (B-1)`. However, B could be MIN_VALUE and hence `(B-1)` could underflow. // If B is MIN_VALUE, then `A until B` is an empty range. We handle this special case be adding an additional "not empty" // condition in the lowered for-loop. Therefore the following for-loop: // // for (i in A until B) { // Loop body } // // is lowered into: // // var inductionVar = A // val last = B - 1 // if (inductionVar <= last && B != MIN_VALUE) { // // Loop is not empty // do { // val loopVar = inductionVar // inductionVar++ // // Loop body // } while (inductionVar <= last) // } // // However, `B` may be an expression with side-effects that should only be evaluated once, and `A` may also have side-effects. // They are evaluated once and in the correct order (`A` then `B`), the final lowered form is: // // // Additional variables // val untilReceiverValue = A // val untilArg = B // // Standard form of loop over progression // var inductionVar = untilReceiverValue // val last = untilArg - 1 // if (inductionVar <= last && untilFunArg != MIN_VALUE) { // // Loop is not empty // do { // val loopVar = inductionVar // inductionVar++ // // Loop body // } while (inductionVar <= last) // } val receiverValue = expression.extensionReceiver!! val untilArg = expression.getValueArgument(0)!! // Ensure that the argument conforms to the progression type before we decrement. val untilArgCasted = untilArg.castIfNecessary( data.elementType(context.irBuiltIns), data.elementCastFunctionName ) // To reduce local variable usage, we create and use temporary variables only if necessary. var receiverValueVar: IrVariable? = null var untilArgVar: IrVariable? = null var additionalVariables = emptyList<IrVariable>() if (untilArg.canHaveSideEffects) { if (receiverValue.canHaveSideEffects) { receiverValueVar = scope.createTemporaryVariable(receiverValue, nameHint = "untilReceiverValue") } untilArgVar = scope.createTemporaryVariable(untilArgCasted, nameHint = "untilArg") additionalVariables = listOfNotNull(receiverValueVar, untilArgVar) } val first = if (receiverValueVar == null) receiverValue else irGet(receiverValueVar) val untilArgExpression = if (untilArgVar == null) untilArgCasted else irGet(untilArgVar) val last = untilArgExpression.decrement() val (minValueAsLong, minValueIrConst) = when (data) { ProgressionType.INT_PROGRESSION -> Pair(Int.MIN_VALUE.toLong(), irInt(Int.MIN_VALUE)) ProgressionType.CHAR_PROGRESSION -> Pair(Char.MIN_VALUE.toLong(), irChar(Char.MIN_VALUE)) ProgressionType.LONG_PROGRESSION -> Pair(Long.MIN_VALUE, irLong(Long.MIN_VALUE)) } val additionalNotEmptyCondition = untilArg.constLongValue.let { when { it == null && isAdditionalNotEmptyConditionNeeded(receiverValue.type, untilArg.type) -> // Condition is needed and untilArg is non-const. // Build the additional "not empty" condition: `untilArg != MIN_VALUE`. irNotEquals(untilArgExpression, minValueIrConst) it == minValueAsLong -> // Hardcode "false" as additional condition so that the progression is considered empty. // The entire lowered loop becomes a candidate for dead code elimination, depending on backend. irFalse() else -> // We know that untilArg != MIN_VALUE, so the additional condition is not necessary. null } } ProgressionHeaderInfo( data, first = first, last = last, step = irInt(1), canOverflow = false, additionalVariables = additionalVariables, additionalNotEmptyCondition = additionalNotEmptyCondition, direction = ProgressionDirection.INCREASING ) } private fun isAdditionalNotEmptyConditionNeeded(receiverType: IrType, argType: IrType): Boolean { // Here are the available `until` extension functions: // // infix fun Char.until(to: Char): CharRange // infix fun Byte.until(to: Byte): IntRange // infix fun Byte.until(to: Short): IntRange // infix fun Byte.until(to: Int): IntRange // infix fun Byte.until(to: Long): LongRange // infix fun Short.until(to: Byte): IntRange // infix fun Short.until(to: Short): IntRange // infix fun Short.until(to: Int): IntRange // infix fun Short.until(to: Long): LongRange // infix fun Int.until(to: Byte): IntRange // infix fun Int.until(to: Short): IntRange // infix fun Int.until(to: Int): IntRange // infix fun Int.until(to: Long): LongRange // infix fun Long.until(to: Byte): LongRange // infix fun Long.until(to: Short): LongRange // infix fun Long.until(to: Int): LongRange // infix fun Long.until(to: Long): LongRange // // The combinations where the range element type is strictly larger than the argument type do NOT need the additional condition. // In such combinations, there is no possibility of underflow when the argument (casted to the range element type) is decremented. // For unexpected combinations that currently don't exist (e.g., Int until Char), we assume the check is needed to be safe. // TODO: Include unsigned types return with(context.irBuiltIns) { when (receiverType) { charType -> true byteType, shortType, intType -> when (argType) { byteType, shortType -> false else -> true } longType -> when (argType) { byteType, shortType, intType -> false else -> true } else -> true } } } } /** Builds a [HeaderInfo] for progressions built using the `indices` extension property. */ internal class IndicesHandler(private val context: CommonBackendContext) : ProgressionHandler { override val matcher = SimpleCalleeMatcher { // TODO: Handle Collection<*>.indices // TODO: Handle CharSequence.indices extensionReceiver { it != null && it.type.run { isArray() || isPrimitiveArray() } } fqName { it == FqName("kotlin.collections.<get-indices>") } parameterCount { it == 0 } } override fun build(expression: IrCall, data: ProgressionType, scopeOwner: IrSymbol): HeaderInfo? = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { // `last = array.size - 1` (last is inclusive) for the loop `for (i in array.indices)`. val arraySizeProperty = expression.extensionReceiver!!.type.getClass()!!.properties.first { it.name.asString() == "size" } val last = irCall(arraySizeProperty.getter!!).apply { dispatchReceiver = expression.extensionReceiver }.decrement() ProgressionHeaderInfo( data, first = irInt(0), last = last, step = irInt(1), canOverflow = false, direction = ProgressionDirection.INCREASING ) } } /** Builds a [HeaderInfo] for calls to reverse an iterable. */ internal class ReversedHandler(context: CommonBackendContext, private val visitor: IrElementVisitor<HeaderInfo?, Nothing?>) : HeaderInfoFromCallHandler<Nothing?> { private val symbols = context.ir.symbols // Use Quantifier.ANY so we can handle all reversed iterables in the same manner. override val matcher = createIrCallMatcher(Quantifier.ANY) { // Matcher for reversed progression. callee { fqName { it == FqName("kotlin.ranges.reversed") } extensionReceiver { it != null && it.type.toKotlinType() in symbols.progressionClassesTypes } parameterCount { it == 0 } } // TODO: Handle reversed String, Progression.withIndex(), etc. } // Reverse the HeaderInfo from the underlying progression or array (if any). override fun build(expression: IrCall, data: Nothing?, scopeOwner: IrSymbol) = expression.extensionReceiver!!.accept(visitor, null)?.asReversed() } /** Builds a [HeaderInfo] for progressions not handled by more specialized handlers. */ internal class DefaultProgressionHandler(private val context: CommonBackendContext) : ExpressionHandler { private val symbols = context.ir.symbols override fun match(expression: IrExpression) = ProgressionType.fromIrType(expression.type, symbols) != null override fun build(expression: IrExpression, scopeOwner: IrSymbol): HeaderInfo? = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { // Directly use the `first/last/step` properties of the progression. val progression = scope.createTemporaryVariable(expression, nameHint = "progression") val progressionClass = progression.type.getClass()!! val firstProperty = progressionClass.properties.first { it.name.asString() == "first" } val first = irCall(firstProperty.getter!!).apply { dispatchReceiver = irGet(progression) } val lastProperty = progressionClass.properties.first { it.name.asString() == "last" } val last = irCall(lastProperty.getter!!).apply { dispatchReceiver = irGet(progression) } val stepProperty = progressionClass.properties.first { it.name.asString() == "step" } val step = irCall(stepProperty.getter!!).apply { dispatchReceiver = irGet(progression) } ProgressionHeaderInfo( ProgressionType.fromIrType(progression.type, symbols)!!, first, last, step, additionalVariables = listOf(progression), direction = ProgressionDirection.UNKNOWN ) } } internal abstract class IndexedGetIterationHandler(protected val context: CommonBackendContext) : ExpressionHandler { override fun build(expression: IrExpression, scopeOwner: IrSymbol): HeaderInfo? = with(context.createIrBuilder(scopeOwner, expression.startOffset, expression.endOffset)) { // Consider the case like: // // for (elem in A) { f(elem) }` // // If we lower it to: // // for (i in A.indices) { f(A[i]) } // // ...then we will break program behaviour if `A` is an expression with side-effect. Instead, we lower it to: // // val a = A // for (i in a.indices) { f(a[i]) } // // This also ensures that the semantics of re-assignment of array variables used in the loop is consistent with the semantics // proposed in https://youtrack.jetbrains.com/issue/KT-21354. val arrayReference = scope.createTemporaryVariable( expression, nameHint = "indexedObject", origin = IrDeclarationOrigin.FOR_LOOP_IMPLICIT_VARIABLE ) // `last = array.size` (last is exclusive) for the loop `for (i in array.indices)`. val arraySizeProperty = arrayReference.type.getClass()!!.properties.first { it.name.asString() == sizePropertyName() } val last = irCall(arraySizeProperty.getter!!).apply { dispatchReceiver = irGet(arrayReference) } IndexedGetHeaderInfo( first = irInt(0), last = last, step = irInt(1), objectVariable = arrayReference ) } abstract fun sizePropertyName() : String } /** Builds a [HeaderInfo] for arrays. */ internal class ArrayIterationHandler(context: CommonBackendContext) : IndexedGetIterationHandler(context) { override fun match(expression: IrExpression) = expression.type.run { isArray() || isPrimitiveArray() } override fun sizePropertyName(): String = "size" } /** Builds a [HeaderInfo] for iteration over characters in a `CharacterSequence`. */ internal class CharSequenceIterationHandler(context: CommonBackendContext) : IndexedGetIterationHandler(context) { override fun match(expression: IrExpression) = expression.type.isSubtypeOfClass(context.ir.symbols.charSequence) override fun sizePropertyName(): String = "length" }
7
null
1
1
f17e9ba9febdabcf7a5e0f17e4be02e0f9e87f13
17,620
kotlin
Apache License 2.0
firebase-messaging/src/nativeMain/kotlin/suntrix/kmp/firebase/messaging/Firebase.kt
kotlin-multiplatform
542,823,504
false
{"Kotlin": 126662, "Makefile": 152}
package suntrix.kmp.firebase.messaging import native.FirebaseMessaging.FIRMessaging import suntrix.kmp.firebase.Firebase /** * Created by <NAME> on 14/04/2023 */ actual val Firebase.messaging: FirebaseMessaging get() = FirebaseMessaging(FIRMessaging.messaging())
0
Kotlin
0
1
684e9142ce9fced949c1a9c539e8651aeb0a87da
270
firebase-kmp-sdks
MIT License
compiler/testData/diagnostics/tests/smartCasts/kt27221_2.fir.kt
JetBrains
3,432,266
false
null
// !DIAGNOSTICS: -UNUSED_VARIABLE // SKIP_TXT sealed class A sealed class B : A() sealed class C : B() sealed class D : C() object BB : B() object CC : C() object DD : D() fun foo1(a: A) { if (a is B) { if (a is D) { if (<!USELESS_IS_CHECK!>a is C<!>) { val t = when (a) { is DD -> "DD" } } } } } fun foo2(a: A) { if (a is B) { if (a is D) { if (<!USELESS_IS_CHECK!>a is C<!>) { val t = when (a) { is DD -> "DD" } } } } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
681
kotlin
Apache License 2.0
commonCompose/src/commonMain/kotlin/tk/zwander/commonCompose/view/pages/DecryptView.kt
zacharee
342,079,605
false
null
package tk.zwander.commonCompose.view.pages import androidx.compose.foundation.ScrollState import androidx.compose.foundation.layout.* import androidx.compose.foundation.verticalScroll import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import io.ktor.utils.io.core.internal.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import tk.zwander.common.data.DecryptFileInfo import tk.zwander.commonCompose.model.DecryptModel import tk.zwander.common.tools.CryptUtils import tk.zwander.commonCompose.locals.LocalDecryptModel import tk.zwander.commonCompose.util.vectorResource import tk.zwander.commonCompose.view.components.HybridButton import tk.zwander.commonCompose.view.components.MRFLayout import tk.zwander.commonCompose.view.components.ProgressInfo import tk.zwander.samloaderkotlin.resources.MR import tk.zwander.samloaderkotlin.strings import kotlin.time.ExperimentalTime /** * Delegate getting the decryption input and output to the platform. */ expect object PlatformDecryptView { suspend fun getInput(callback: suspend CoroutineScope.(DecryptFileInfo?) -> Unit) fun onStart() fun onFinish() fun onProgress(status: String, current: Long, max: Long) } @OptIn(DangerousInternalIoApi::class, ExperimentalTime::class, ExperimentalMaterial3Api::class) private suspend fun onDecrypt(model: DecryptModel) { PlatformDecryptView.onStart() val info = model.fileToDecrypt!! val inputFile = info.encFile val outputFile = info.decFile val key = if (inputFile.getName().endsWith(".enc2")) CryptUtils.getV2Key( model.fw, model.model, model.region ) else { try { CryptUtils.getV4Key(client, model.fw, model.model, model.region) } catch (e: Throwable) { model.endJob(strings.decryptError(e.message.toString())) return } } CryptUtils.decryptProgress(inputFile.openInputStream(), outputFile.openOutputStream(), key, inputFile.getLength()) { current, max, bps -> model.progress = current to max model.speed = bps PlatformDecryptView.onProgress(strings.decrypting(), current, max) } PlatformDecryptView.onFinish() model.endJob(strings.done()) } private suspend fun onOpenFile(model: DecryptModel) { PlatformDecryptView.getInput { info -> if (info != null) { if (!info.encFile.getName().endsWith(".enc2") && !info.encFile.getName().endsWith( ".enc4" ) ) { model.endJob(strings.selectEncrypted()) } else { model.endJob("") model.fileToDecrypt = info } } else { model.endJob("") } } } /** * The Decrypter View. * @param scrollState a shared scroll state among all pages. */ @DangerousInternalIoApi @ExperimentalTime @Composable @OptIn(ExperimentalMaterial3Api::class) internal fun DecryptView(scrollState: ScrollState) { val model = LocalDecryptModel.current val canDecrypt = model.fileToDecrypt != null && model.job == null && model.fw.isNotBlank() && model.model.isNotBlank() && model.region.isNotBlank() val canChangeOption = model.job == null Column( modifier = Modifier.fillMaxSize() .verticalScroll(scrollState) ) { BoxWithConstraints( modifier = Modifier.fillMaxWidth() ) { val constraints = constraints Row( modifier = Modifier.fillMaxWidth() ) { HybridButton( onClick = { model.job = model.scope.launch { onDecrypt(model) } }, enabled = canDecrypt, text = strings.decrypt(), description = strings.decryptFirmware(), vectorIcon = vectorResource(MR.assets.lock_open_outline), parentSize = constraints.maxWidth ) Spacer(Modifier.width(8.dp)) HybridButton( onClick = { model.scope.launch { onOpenFile(model) } }, enabled = canChangeOption, text = strings.openFile(), description = strings.openFileDesc(), vectorIcon = vectorResource(MR.assets.open_in_new), parentSize = constraints.maxWidth ) Spacer(Modifier.weight(1f)) HybridButton( onClick = { PlatformDecryptView.onFinish() model.endJob("") }, enabled = model.job != null, text = strings.cancel(), description = strings.cancel(), vectorIcon = vectorResource(MR.assets.cancel), parentSize = constraints.maxWidth ) } } Spacer(Modifier.height(8.dp)) MRFLayout(model, canChangeOption, canChangeOption) Spacer(Modifier.height(8.dp)) Row( modifier = Modifier.fillMaxWidth() ) { OutlinedTextField( value = model.fileToDecrypt?.encFile?.getAbsolutePath() ?: "", onValueChange = {}, label = { Text(strings.file()) }, modifier = Modifier.weight(1f), readOnly = true, singleLine = true, ) } Spacer(Modifier.height(16.dp)) ProgressInfo(model) } }
12
Kotlin
57
484
d96d942d745e8fb96c88202ba39c2ad116335351
5,868
SamloaderKotlin
MIT License
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/KtTestCompiler.kt
warnergodfrey
79,441,818
true
{"Kotlin": 161349, "Java": 153}
package io.gitlab.arturbosch.detekt.api import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiFileFactory import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.KtFile import java.nio.file.Files import java.nio.file.Path /** * This is basically an enhanced version of the KtCompiler from the core project which allows plain text to be * compiled to a KtFile. * * @author <NAME> */ @Unstable(removedIn = "M4") internal object KtTestCompiler { private val psiFileFactory: PsiFileFactory init { val project = KotlinCoreEnvironment.createForProduction(Disposer.newDisposable(), CompilerConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES).project psiFileFactory = PsiFileFactory.getInstance(project) } internal fun compileFromText(content: String): KtFile { return psiFileFactory.createFileFromText(KotlinLanguage.INSTANCE, content) as KtFile } internal fun compile(path: Path): KtFile { require(Files.isRegularFile(path)) { "Given path should be a regular file!" } val file = path.normalize().toAbsolutePath() val content = String(Files.readAllBytes(file)) return psiFileFactory.createFileFromText(file.fileName.toString(), KotlinLanguage.INSTANCE, content) as KtFile } } /** * Use this method if you define a kt file/class as a plain string in your test. */ @Unstable(removedIn = "M4") fun compileContentForTest(content: String) = KtTestCompiler.compileFromText(content) /** * Use this method if you test a kt file/class in the test resources. */ @Unstable(removedIn = "M4") fun compileForTest(path: Path) = KtTestCompiler.compile(path)
0
Kotlin
0
0
645ff4b571dff29e728171ffbd2906132d0c2c11
1,814
detekt
Apache License 2.0
site/src/jvmMain/kotlin/dev/yekta/searchit/api/SearchEngine.kt
YektaDev
806,609,098
false
{"Kotlin": 59797}
package dev.yekta.searchit.api import com.moriatsushi.cacheable.Cacheable import com.varabyte.kobweb.api.log.Logger import dev.yekta.searchit.api.model.Page import dev.yekta.searchit.api.repo.DBManager import dev.yekta.searchit.api.repo.StringNormalizer import dev.yekta.searchit.api.repo.WebpageIndexes import dev.yekta.searchit.api.repo.Webpages import dev.yekta.searchit.api.util.HtmlParser import dev.yekta.searchit.common.Item import dev.yekta.searchit.common.ResultStats import dev.yekta.searchit.common.SearchResult import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import org.jetbrains.exposed.sql.selectAll import kotlin.math.min import kotlin.system.measureTimeMillis class SearchEngine(private val logger: Logger) { private val db = DBManager(logger) private val parser = HtmlParser(logger) private val pages = runBlocking { logger.info("Reading Page Data...") db.transaction { Webpages.selectAll().mapNotNull { val parsedHtml = parser.parse(it[Webpages.html]) ?: return@mapNotNull null Page(url = it[Webpages.url], parsedHtml = parsedHtml) } } } private val pageItems = runBlocking { logger.info("Extracting Items...") pages.map { Item( url = it.url, title = it.title, description = it.body.substring(0, min(500, it.body.length)), ) } } private val indexes = runBlocking { logger.info("Building Indexes...") WebpageIndexes(pages) } private val finder = Finder(indexes, logger) private inline fun Map<String, ArrayList<Int>>.getUniqueMatchingPageIndexes( crossinline uniquePredicate: (String) -> Boolean ) = this .asSequence() .filter { (token: String, _) -> uniquePredicate(token) } .flatMap { (_, pageIndexes: ArrayList<Int>) -> pageIndexes } .groupBy { pageIndex -> pageIndex } suspend fun search(query: String): SearchResult = coroutineScope { var result: List<Item> val duration = measureTimeMillis { result = when (query.length) { in 4..100 -> performCachableSearch(query) else -> performNonCachableSearch(query) } } SearchResult( items = result, stats = ResultStats( results = result.size.toLong(), durationMs = duration, ), ) } @Cacheable(maxCount = 100_000, lock = true) private fun performCachableSearch(query: String): List<Item> = searchForQuery(query) private fun performNonCachableSearch(query: String): List<Item> = searchForQuery(query) private fun searchForQuery(query: String): List<Item> { val result = mutableListOf<Item>() // Normalizers must be the same for both query and indexes, this can be encapsulated. val tokens = StringNormalizer.normalizeAndTokenize(query) // Defaults to AND search val foundPages = finder.havingAllTokens(tokens, indexes.titleInvertedIndex, indexes.bodyInvertedIndex) foundPages.forEach { result.add(pageItems[it]) } return result // val titleMatches = indexes.titleInvertedIndex // .getUniqueMatchingPageIndexes { token -> tokens.contains(token) } // .map { (token, pageIndex) -> token to pageIndex.size } // .sortedByDescending { it.second } // .map { it.first } // .toList() // .forEach { result.add(0, pageItems[it]) } // // val bodyMatches = indexes.bodyInvertedIndex // .getUniqueMatchingPageIndexes { token -> tokens.contains(token) } // .filter { (token: String, _) -> tokens.contains(token) } // .flatMap { (_, pageIndexes: ArrayList<Int>) -> pageIndexes } // // (titleMatches + bodyMatches) // .groupBy { pageIndex -> pageIndex } // .map { (token, pageIndex) -> token to pageIndex.size } // .sortedByDescending { it.second } // .map { it.first } // .toList() // .forEach { result.add(0, pageItems[it]) } // // for ((index, page) in pages.withIndex()) { // when { // page.title.contains(query, ignoreCase = true) -> result.add(0, pageItems[index]) // page.body.contains(query, ignoreCase = true) -> result.add(pageItems[index]) // } // } } }
0
Kotlin
0
0
2252d39c1274b3d71899ef9d11848afa6de0b711
4,624
searchit
Apache License 2.0
src/frontendMain/kotlin/io/joaofig/vedmap/viewmodels/VehicleListViewModel.kt
joaofig
437,581,924
false
null
package io.joaofig.vedmap.viewmodels class VehicleListViewModel : ViewModel() { }
0
Kotlin
0
1
6b11d1183cc48526612a33967c516a5bfcbc6e07
82
ved-map
MIT License
app/common/src/commonMain/kotlin/sh/christian/ozone/user/UserDatabase.kt
christiandeange
611,550,055
false
{"Kotlin": 484890, "Shell": 1254, "Swift": 690, "HTML": 306, "JavaScript": 202, "CSS": 129}
package sh.christian.ozone.user import app.bsky.actor.GetProfileQueryParams import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.mapNotNull import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.serialization.Serializable import me.tatarka.inject.annotations.Inject import sh.christian.ozone.api.ApiProvider import sh.christian.ozone.api.AtIdentifier import sh.christian.ozone.di.SingleInApp import sh.christian.ozone.model.FullProfile import sh.christian.ozone.model.toProfile import sh.christian.ozone.store.PersistentStorage import sh.christian.ozone.store.preference import kotlin.time.Duration.Companion.minutes @Inject @SingleInApp class UserDatabase( private val clock: Clock, private val storage: PersistentStorage, private val apiProvider: ApiProvider, ) { fun profile(userReference: UserReference): Flow<FullProfile> { return profileOrNull(userReference).filterNotNull() } fun profileOrNull(userReference: UserReference): Flow<FullProfile?> = flow { val key = when (userReference) { is UserDid -> "did:${userReference.did}" is UserHandle -> "handle:${userReference.handle}" } val preference = storage.preference<CacheObject>(key, null) val cached = preference.get() if (cached != null && cached.isFresh()) { emit(cached.profile) } val identifier = when (userReference) { is UserDid -> AtIdentifier(userReference.did.did) is UserHandle -> AtIdentifier(userReference.handle.handle) } val profileOrNull = apiProvider.api.getProfile(GetProfileQueryParams(identifier)) .maybeResponse() ?.let { response -> val profile = response.toProfile() val newCacheObject = CacheObject(clock.now(), profile) storage.preference<CacheObject>("did:${profile.did}", null).set(newCacheObject) storage.preference<CacheObject>("handle:${profile.handle}", null).set(newCacheObject) profile } emit(profileOrNull) emitAll(preference.updates.mapNotNull { it?.profile }) }.distinctUntilChanged() private fun CacheObject.isFresh() = (clock.now() - instant) < 5.minutes @Serializable private data class CacheObject( val instant: Instant, val profile: FullProfile, ) }
1
Kotlin
6
34
df457f4fcedca8e621c99689a79b46812023bffd
2,452
ozone
MIT License
Client/app/src/main/java/uk/ac/aber/dcs/mmp/faa/ui/adoption/AdoptionStatusCard.kt
Pasarus
236,987,746
false
null
/* Copyright 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 uk.ac.aber.dcs.mmp.faa.ui.adoption import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.google.firebase.firestore.DocumentReference import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.adoption_status_card.view.* import uk.ac.aber.dcs.mmp.faa.R import uk.ac.aber.dcs.mmp.faa.datasources.DataService import uk.ac.aber.dcs.mmp.faa.datasources.dataclasses.AdoptionProcess import uk.ac.aber.dcs.mmp.faa.datasources.dataclasses.Cat /** * A RecyclerView.ViewHolder implementation that produces the information required for the adoption * status view to be easy to read and when bind is called, it requires an AdoptionProcess object * that is provided as a snapshot of the data, but is guaranteed at time of bind being called. */ class AdoptionStatusCard(itemView: View) : RecyclerView.ViewHolder(itemView) { private val view: View = itemView private val catName: TextView = view.findViewById(R.id.adoptionStatusCardTitle) private val catImage: ImageView = view.findViewById(R.id.adoptionStatusCardCatImage) private val adoptionInfo: TextView = view.findViewById(R.id.adoptionStatusAdoptionInfo) private val adoptionStatusIcon: ImageView = view.findViewById(R.id.adoptionStatusStatusIcon) lateinit var adoptionProcess: AdoptionProcess lateinit var cat: Cat fun bind(model: AdoptionProcess) { adoptionProcess = model requestCatInfoAndBind(model.cat!!) val status = model.status!! val drawable = when { status["accepted"] as Boolean -> { adoptionInfo.setText(R.string.adoption_success) view.resources.getDrawable(R.drawable.ic_done_all_green_24dp, null) } status["pending"] as Boolean -> { adoptionInfo.text = status["pendingReason"].toString() view.resources.getDrawable(R.drawable.ic_access_alarm_yellow_24dp, null) } else -> { // Must have been rejected adoptionInfo.text = status["rejectedReason"].toString() view.resources.getDrawable(R.drawable.ic_highlight_off_red_24dp, null) } } adoptionStatusIcon.setImageDrawable(drawable) view.setOnClickListener { val bundle = Bundle() bundle.putParcelable("adoptionProcess", model) view.findNavController().navigate(R.id.adoptionStatusInfoViewFragment, bundle) } val white = ContextCompat.getColor(view.context!!, R.color.white) if (DataService.INSTANCE.darkMode) { view.adoptionProcessCard.setBackgroundColor( ContextCompat.getColor( view.context!!, R.color.darkCardBackground ) ) catName.setTextColor(white) adoptionInfo.setTextColor(white) } } private fun requestCatInfoAndBind(catReference: DocumentReference) { catReference.get().addOnSuccessListener { document -> cat = document.toObject(Cat::class.java)!! catName.text = cat.catName Picasso.get().load(cat.pictureUrl).into(catImage) } } }
0
Kotlin
1
2
1080db746af565288fa6a7bdca419f01932a7a28
3,991
FelineAdoptionAgencyMajorProject
Apache License 2.0
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/ToolInstanceFactory.kt
JetBrains
49,584,664
false
null
package jetbrains.buildServer.agent.runner import jetbrains.buildServer.agent.Version import jetbrains.buildServer.dotnet.Platform import java.io.File interface ToolInstanceFactory { fun tryCreate(path: File, baseVersion: Version, platform: Platform): ToolInstance? }
3
null
25
94
5f444c22b3354955d1060e08478d543d2b0b99b0
275
teamcity-dotnet-plugin
Apache License 2.0
app/src/test/java/com/zeynelerdi/deezer/repository/MainRepositoryTest.kt
ZeynelErdiKarabulut
318,848,182
false
null
package com.fevziomurtekin.deezer.repository import androidx.arch.core.executor.testing.InstantTaskExecutorRule import app.cash.turbine.test import com.fevziomurtekin.deezer.core.MockUtil import com.fevziomurtekin.deezer.core.Result import com.fevziomurtekin.deezer.data.albumdetails.AlbumData import com.fevziomurtekin.deezer.data.albumdetails.AlbumDetailsResponse import com.fevziomurtekin.deezer.data.artist.ArtistData import com.fevziomurtekin.deezer.data.artist.ArtistsResponse import com.fevziomurtekin.deezer.data.artistdetails.* import com.fevziomurtekin.deezer.data.genre.Data import com.fevziomurtekin.deezer.data.genre.GenreResponse import com.fevziomurtekin.deezer.data.search.SearchData import com.fevziomurtekin.deezer.data.search.SearchResponse import com.fevziomurtekin.deezer.di.MainCoroutinesRule import com.fevziomurtekin.deezer.domain.local.DeezerDao import com.fevziomurtekin.deezer.domain.network.DeezerClient import com.fevziomurtekin.deezer.domain.network.DeezerService import com.nhaarman.mockitokotlin2.* import kotlinx.coroutines.CompletableDeferred import org.junit.Assert.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import kotlin.time.ExperimentalTime @ExperimentalCoroutinesApi class MainRepositoryTest { private lateinit var repository: DeezerRepository private lateinit var client: DeezerClient private val service: DeezerService = mock() private val deezerDao: DeezerDao = mock() @ExperimentalCoroutinesApi @get:Rule var coroutinesRule = MainCoroutinesRule() @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @ExperimentalCoroutinesApi @Before fun setup() { client = DeezerClient(service) repository = DeezerRepository(client, deezerDao) } @ExperimentalTime @Test fun fetchGenreListFromNetworkTest() = runBlocking { val mockData = GenreResponse(MockUtil.genres) val deferredData = CompletableDeferred(mockData) whenever(deezerDao.getGenreList()).thenReturn(emptyList()) whenever(service.fetchGenreList()).thenReturn(deferredData) /** core testing */ /* val result = repository.fetchGenreList().asLiveData().value Assert.assertEquals(result, Result.Succes(MockUtil.genres))*/ /** add to turbine library.*/ repository.fetchGenreList().test { val result = expectItem() assertEquals(result, Result.Succes(MockUtil.genres)) assertEquals((result as Result.Succes<List<Data>>).data[0].name , "All") assertEquals(result.data[0].id , "0") assertEquals(result.data[1].name , "Pop") assertEquals(result.data[1].id , "132") expectComplete() } verify(deezerDao, atLeastOnce()).getGenreList() verify(service, atLeastOnce()).fetchGenreList().await() verify(deezerDao, atLeastOnce()).insertGenreList(MockUtil.genres) } @ExperimentalTime @Test fun fetchArtistListFromNetworkTest() = runBlocking { val mockData = ArtistsResponse(listOf(MockUtil.artist)) val deferredData = CompletableDeferred(mockData) whenever(service.fetchArtistList(MockUtil.genreID)).thenReturn(deferredData) repository.fetchArtistList(MockUtil.genreID).test { val result = expectItem() assertEquals(result, Result.Succes(listOf(MockUtil.artist))) assertEquals((result as Result.Succes<List<ArtistData>>).data[0].name , "Ezhel") assertEquals(result.data[0].id , "8354140") assertEquals(result.data[1].name , "<NAME>") assertEquals(result.data[1].id , "12934") expectComplete() } verify(service, atLeastOnce()).fetchArtistList(MockUtil.genreID).await() verifyNoMoreInteractions(service) } @ExperimentalTime @Test fun fetchArtistDetailsFromNetworkTest() = runBlocking { val mockData = MockUtil.artistDetails val deferredData = CompletableDeferred(mockData) whenever(service.fetchArtistDetails(MockUtil.artistID)).thenReturn(deferredData) repository.fetchArtistDetails(MockUtil.artistID).test { val result = expectItem() assertEquals(result, Result.Succes(mockData)) assertEquals((result as Result.Succes<ArtistDetailResponse>).data.name , "Ezhel") assertEquals(result.data.id , "8354140") expectComplete() } verify(service, atLeastOnce()).fetchArtistList(MockUtil.artistID).await() verifyNoMoreInteractions(service) } @ExperimentalTime @Test fun fetchArtistAlbumsFromNetworkTest() = runBlocking { val mockData = ArtistAlbumResponse(data= listOf(MockUtil.artistAlbum),next= "",total=20) val deferredData = CompletableDeferred(mockData) whenever(service.fetchArtistAlbums(MockUtil.artistID)).thenReturn(deferredData) repository.fetchArtistAlbums(MockUtil.artistID).test { val result = expectItem() assertEquals(result, Result.Succes(listOf(MockUtil.artistAlbum))) assertEquals((result as Result.Succes<List<ArtistAlbumData>>).data[0].title , "Müptezhel") assertEquals(result.data[0].id , "51174732") assertEquals(result.data[1].title , "Made In Turkey") assertEquals(result.data[1].id , "155597932") expectComplete() } verify(service, atLeastOnce()).fetchArtistAlbums(MockUtil.artistID).await() verifyNoMoreInteractions(service) } @ExperimentalTime @Test fun fetchArtistRelatedFromNetworkTest() = runBlocking { val mockData = ArtistRelatedResponse(data= listOf(MockUtil.artistRelatedData),total=20) val deferredData = CompletableDeferred(mockData) whenever(service.fetchArtistRelated(MockUtil.artistID)).thenReturn(deferredData) repository.fetchArtistRelated(MockUtil.artistID).test { val result = expectItem() assertEquals(result, Result.Succes(listOf(MockUtil.artistRelatedData))) assertEquals((result as Result.Succes<List<ArtistRelatedData>>).data[0].name , "Murda") assertEquals(result.data[0].id , "389038") assertEquals(result.data[1].name , "Reynmen") assertEquals(result.data[1].id , "13136341") expectComplete() } verify(service, atLeastOnce()).fetchArtistRelated(MockUtil.artistID).await() verifyNoMoreInteractions(service) } @ExperimentalTime @Test fun fetchAlbumTracksFromNetworkTest() = runBlocking { val mockData = AlbumDetailsResponse(data= listOf(MockUtil.album),total=12) val deferredData = CompletableDeferred(mockData) whenever(service.fetchAlbumDetails(MockUtil.albumID)).thenReturn(deferredData) repository.fetchAlbumTracks(MockUtil.albumID).test { val result = expectItem() assertEquals(result, Result.Succes(listOf(MockUtil.album))) assertEquals((result as Result.Succes<List<AlbumData>>).data[0].title , "Alo") assertEquals(result.data[0].id , "425605922") assertEquals(result.data[1].title , "Geceler") assertEquals(result.data[1].id , "425605932") expectComplete() } verify(service, atLeastOnce()).fetchAlbumDetails(MockUtil.albumID).await() verifyNoMoreInteractions(service) } @ExperimentalTime @Test fun fetchRecentSearchFromDaoTest() = runBlocking { val mockData = listOf(MockUtil.recentData) whenever(deezerDao.getQueryList()).thenReturn(mockData) repository.fetchRecentSearch().test { val result = expectItem() assertEquals(result, mockData) assertEquals(result[0].q , "Ezhel") assertEquals(result[0].id , "1") expectComplete() } verify(deezerDao, atLeastOnce()).getQueryList() verifyNoMoreInteractions(deezerDao) } @ExperimentalTime @Test fun insertSearchFromDaoTest() = runBlocking { val mockData = MockUtil.recentData whenever(deezerDao.getQueryList()).thenReturn(emptyList()) /*"1","ezhel",12345.toLong()*/ repository.insertSearch(mockData) repository.fetchRecentSearch().test { val result = expectItem() assertEquals(result, mockData) assertEquals(result[0].q , "Ezhel") assertEquals(result[0].id , "1") assertEquals(result[0].time,12345.toLong()) expectComplete() } verify(deezerDao, atLeastOnce()).insertQuery(MockUtil.recentData) } @ExperimentalTime @Test fun fetchSearchFromNetworkTest() = runBlocking { val mockData = SearchResponse(data= listOf(MockUtil.searchData),next="",total=12) val deferredData = CompletableDeferred(mockData) whenever(service.fetchSearchAlbum(MockUtil.query)).thenReturn(deferredData) repository.fetchSearch(MockUtil.query).test { val result = expectItem() assertEquals(result, Result.Succes(listOf(MockUtil.searchData))) assertEquals((result as Result.Succes<List<SearchData>>).data[0].title , "İmkansızım") assertEquals(result.data[0].id , "51434782") assertEquals(result.data[0].record_type , "single") assertEquals(result.data[0].genre_id , "116") expectComplete() } verify(service, atLeastOnce()).fetchSearchAlbum(MockUtil.query).await() verifyNoMoreInteractions(service) } @ExperimentalTime @Test fun fetchFavoriteFromDaoTest() = runBlocking{ val mockData = listOf(MockUtil.album) whenever(deezerDao.getFavorites()).thenReturn(mockData) repository.fetchFavorites().test { val result = expectItem() assertEquals(result,mockData) assertEquals(result[0].title , "Alo") assertEquals(result[0].id , "425605922") assertEquals(result[1].title , "Geceler") assertEquals(result[1].id , "425605932") } verify(deezerDao, atLeastOnce()).getFavorites() verifyNoMoreInteractions(deezerDao) } @ExperimentalTime @Test fun insertFavoriteTrackFromDaoTest()= runBlocking { val mockData = MockUtil.album whenever(deezerDao.getFavorites()).thenReturn(emptyList()) repository.insertFavoritesData(mockData) repository.fetchFavorites().test { val result = expectItem() assertEquals(result,mockData) assertEquals(result[0].title , "Alo") assertEquals(result[0].id , "425605922") assertEquals(result[1].title , "Geceler") assertEquals(result[1].id , "425605932") } verify(deezerDao, atLeastOnce()).insertTrack(MockUtil.album) } }
0
null
0
1
f6ef2843d34dbb853181658cb9e001206df4694a
11,067
DeezerClone
Apache License 2.0
sdk/src/main/java/com/seamlesspay/ui/common/filled/CvcInputFilled.kt
seamlesspay
235,817,887
false
{"Kotlin": 190728, "Java": 131412}
package com.seamlesspay.ui.common.filled import android.content.Context import android.os.Build import android.text.Editable import android.text.InputFilter import android.text.InputType import android.text.method.DigitsKeyListener import android.util.AttributeSet import android.view.View import androidx.core.content.ContextCompat import com.google.android.material.textfield.TextInputLayout import com.seamlesspay.R import com.seamlesspay.ui.common.CvcEditText import com.seamlesspay.ui.common.SeamlesspayTextWatcher import com.seamlesspay.ui.common.TextInputView import com.seamlesspay.ui.models.CardBrand import com.seamlesspay.ui.models.style.InputIcons class CvcInputFilled @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : TextInputView(context, attrs, defStyleAttr) { /** * @return the inputted CVC value if valid; otherwise, null */ val cvcValue: String? get() { return rawCvcValue.takeIf { isValidCvv } } internal val rawCvcValue: String @JvmSynthetic get() { return fieldText.trim() } private var cardBrand: CardBrand = CardBrand.Unknown val isValidCvv: Boolean get() { return cardBrand.isValidCvc(rawCvcValue) } // invoked when a valid CVC has been entered @JvmSynthetic internal var completionCallback: () -> Unit = {} init { editText.maxLines = 1 editText.filters = createFilters(CardBrand.Unknown) editText.inputType = InputType.TYPE_NUMBER_VARIATION_PASSWORD editText.keyListener = DigitsKeyListener.getInstance(false, true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { setAutofillHints(View.AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE) } setUpListeners() } private fun setUpListeners() { editText.addTextChangedListener(object : SeamlesspayTextWatcher() { override fun afterTextChanged(s: Editable?) { if (cardBrand.isMaxCvc(rawCvcValue)) { completionCallback() } validateState() } }) } /** * @param cardBrand the [CardBrand] used to update the view * @param customHintText optional user-specified hint text * @param textInputLayout if specified, hint text will be set on this [TextInputLayout] * instead of directly on the [CvcEditText] */ @JvmSynthetic internal fun updateBrand( cardBrand: CardBrand ) { this.cardBrand = cardBrand editText.filters = createFilters(cardBrand) val hint = if (cardBrand == CardBrand.AmericanExpress) { R.string.cvc_amex_hint } else { R.string.cvc_number_hint } setHint(hint) validateState() } private fun createFilters(cardBrand: CardBrand): Array<InputFilter> { return arrayOf(InputFilter.LengthFilter(cardBrand.maxCvcLength)) } override fun isUIValid() = isValidCvv override fun getErrorText() = resources.getString(R.string.invalid_cvc) override fun getEndIcons() = if (cardBrand == CardBrand.AmericanExpress) { InputIcons(ContextCompat.getDrawable(context, R.drawable.ic_cvc_active), ContextCompat.getDrawable(context, R.drawable.ic_cvc_inactive)) } else { InputIcons(ContextCompat.getDrawable(context, R.drawable.ic_cvv_active), ContextCompat.getDrawable(context, R.drawable.ic_cvv_inactive)) } }
11
Kotlin
1
2
ceefb734015ad35bb8a556ba6b2933687b59ef7f
3,300
seamlesspay-android
MIT License
MSDKUIDemo/MSDKUIApp/src/main/java/com/here/msdkuiapp/guidance/GuidanceRouteSelectionCoordinator.kt
heremaps
141,680,627
false
null
/* * Copyright (C) 2017-2019 HERE Europe B.V. * * 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.here.msdkuiapp.guidance import android.support.v4.app.FragmentManager import android.content.Context import com.here.android.mpa.common.GeoCoordinate import com.here.android.mpa.common.MapEngine import com.here.android.mpa.mapping.Map import com.here.android.mpa.routing.Route import com.here.msdkui.routing.WaypointEntry import com.here.msdkuiapp.R import com.here.msdkuiapp.base.BaseFragmentCoordinator import com.here.msdkuiapp.common.routepreview.RoutePreviewFragment import com.here.msdkuiapp.guidance.SingletonHelper.appPositioningManager import com.here.msdkuiapp.isLocationOk import com.here.msdkuiapp.map.MapFragmentWrapper /** * Coordinator for managing (add, remove, show, hide etc) different views/panel for guidance route selection. */ class GuidanceRouteSelectionCoordinator(private val context: Context, fragmentManager: FragmentManager) : BaseFragmentCoordinator(fragmentManager), MapFragmentWrapper.Listener, GuidanceWaypointSelectionFragment.Listener, RoutePreviewFragment.Listener { internal var mapFragment: MapFragmentWrapper? = null get() = field ?: fragmentManager.findFragmentById(R.id.mapfragment_wrapper) as? MapFragmentWrapper internal val routePreviewFragment: RoutePreviewFragment? = null get() = field ?: getFragment(R.id.guidance_selection_bottom_container) as? RoutePreviewFragment private val guidanceWaypointSelectionFragment: GuidanceWaypointSelectionFragment? = null get() = field ?: getFragment(R.id.guidance_selection_top_container) as? GuidanceWaypointSelectionFragment /** * Init the map engine. */ fun start() { mapFragment?.start(this::onEngineInit) // if bottom fragment is not there, add waypoint selection fragments getFragment(R.id.guidance_selection_bottom_container) ?: run { addFragment(R.id.guidance_selection_top_container, GuidanceWaypointSelectionFragment::class.java) } } private fun onEngineInit() { mapFragment?.run { traffic = true view?.isFocusable = true } if (context.isLocationOk) { onLocationReady() } } /** * Indicates location services and permission are ready to use. */ fun onLocationReady() { if (MapEngine.isInitialized()) { guidanceWaypointSelectionFragment?.presenter?.onLocationReady() } } override fun onPositionAvailable() { appPositioningManager?.run { mapFragment?.showPositionIndicator() mapFragment?.map?.setCenter(customLocation, Map.Animation.LINEAR) } mapFragment?.onTouch(true, this) } override fun onPointSelectedOnMap(cord: GeoCoordinate) { guidanceWaypointSelectionFragment?.updateCord(cord) } override fun onWaypointSelected(entry: WaypointEntry) { mapFragment?.onTouch(false) removeFragment(R.id.guidance_selection_top_container) val fragment = addFragment(R.id.guidance_selection_bottom_container, RoutePreviewFragment::class.java, true) fragment.setWaypoint(entry) } override fun renderRoute(route: Route) { with(mapFragment!!) { renderAndZoomTo(route, false) } } /** * Manages views on back button pressed. */ override fun onBackPressed(): Boolean { getFragment(R.id.guidance_selection_bottom_container)?.run { addFragment(R.id.guidance_selection_top_container, GuidanceWaypointSelectionFragment::class.java) with(mapFragment!!) { clearMap() onPositionAvailable() } } return super.onBackPressed() } }
1
null
19
49
3b54e002f92cb92edb5a71e55fb064e6112158d6
4,333
msdkui-android
Apache License 2.0
src/main/kotlin/net/andreinc/serverneat/server/RouteDSL.kt
nomemory
255,720,445
false
null
package net.andreinc.serverneat.server import io.vertx.core.http.HttpHeaders import io.vertx.core.http.HttpMethod import io.vertx.ext.web.Router import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import mu.KotlinLogging import net.andreinc.mockneat.abstraction.MockUnit import net.andreinc.serverneat.logging.ansi import java.util.concurrent.atomic.AtomicLong private val logger = KotlinLogging.logger { } @ServerNeatDslMarker class Routes(private val router: Router, private val globalHeaders: MutableMap<String, String>) { private val count: AtomicLong = AtomicLong(0) companion object { // A list of HTTP Methods without a response body private val noBodyHttpMethods : Set<HttpMethod> = setOf( HttpMethod.HEAD, HttpMethod.CONNECT, HttpMethod.OPTIONS, HttpMethod.TRACE ) private fun hasNoBody(httpMethod: HttpMethod) : Boolean { return httpMethod in noBodyHttpMethods } } private val routes : MutableList<Route> = mutableListOf() fun get(init: Route.() -> Unit) { createRoute(init, HttpMethod.GET) } fun head(init: Route.()-> Unit) { createRoute(init, HttpMethod.HEAD) } fun post(init: Route.() -> Unit) { createRoute(init, HttpMethod.POST) } fun put(init: Route.() -> Unit) { createRoute(init, HttpMethod.PUT) } fun delete(init: Route.() -> Unit) { createRoute(init, HttpMethod.DELETE) } fun connect(init: Route.() -> Unit) { createRoute(init, HttpMethod.CONNECT) } fun options(init: Route.() -> Unit) { createRoute(init, HttpMethod.OPTIONS) } fun trace(init: Route.() -> Unit) { createRoute(init, HttpMethod.TRACE) } fun patch(init: Route.() -> Unit) { createRoute(init, HttpMethod.PATCH) } private fun createRoute(init: Route.() -> Unit, httpMethod: HttpMethod) { val r = Route(httpMethod); r.apply(init) logger.info { ansi("Adding new ({httpMethod ${r.method}}) route path='{path ${r.path}}'") } routes.add(r) if (hasNoBody(r.method) && r.response.contentObject !is RouteResponseEmptyContent) { logger.warn { ansi("{red Found response for {httpMethod ${r.method}} route. Response will be ignored.}") } } router .route(r.path) .method(r.method) .handler{ ctx -> GlobalScope.launch { val response = ctx.response() // No need to set a delay if value is 0 if (r.response.delay > 0) { delay(r.response.delay) } response.headers().addAll(globalHeaders) response.headers().addAll(r.response.customHeaders) response.statusCode = r.response.statusCode logger.info { ansi("({httpMethod ${r.method}}) request for path='{path ${r.path}}' (requestId={b ${count.addAndGet(1)}})") } // No need to return a body if it's HEAD if (hasNoBody(r.method) && r.response.contentObject !is RouteResponseEmptyContent) { response.end() } // If the route is responsible for returning a file to download else if (r.response.contentObject is RouteResponseFileDownload) { response .putHeader(HttpHeaders.CONTENT_TYPE, "text/plain") .putHeader("Content-Disposition", "attachment; filename=\"${r.response.content()}\"") .putHeader(HttpHeaders.TRANSFER_ENCODING, "chunked") .sendFile(r.response.content()) } else { response.end(r.response.content()) } } } } } @ServerNeatDslMarker class GlobalHeaders { val globalHeaders : MutableMap<String, String> = mutableMapOf() fun header(name: String, value: String) { globalHeaders[name] = value } fun header(name: String, value: MockUnit<*>) { globalHeaders[name] = value.mapToString().get() } } @ServerNeatDslMarker class Route(val method: HttpMethod) { lateinit var path : String var response : RouteResponse = RouteResponse() fun response(init: RouteResponse.() -> Unit) { this.response.apply(init) } }
11
Kotlin
0
18
13e34a1e4cab05dade445f1ad5495cb3956e97fc
4,634
serverneat
Apache License 2.0
app/src/main/java/com/wwy/android/ui/homeplaza/MainWeChatNumFragment.kt
wwy863399246
209,758,901
false
null
package com.wwy.android.ui.homeplaza import android.view.View import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.viewpager2.widget.ViewPager2 import com.angcyo.tablayout.delegate2.ViewPager2Delegate import com.jeremyliao.liveeventbus.LiveEventBus import com.wwy.android.R import com.wwy.android.adapter.MyFragmentPagerAdapter import com.wwy.android.ext.MAIN_PLAZA_CUT import com.wwy.android.ext.inflate import com.wwy.android.ui.base.BaseVMFragment import com.wwy.android.view.loadpage.BasePageViewForStatus import com.wwy.android.view.loadpage.SimplePageViewForStatus import com.wwy.android.vm.WeChatNumViewModel import kotlinx.android.synthetic.main.fragment_main_project.* import org.jetbrains.anko.sdk27.coroutines.onClick import org.koin.androidx.viewmodel.ext.android.getViewModel /** *@创建者wwy *@创建时间 2020/6/1 11:43 *@描述 公众号主页 */ class MainWeChatNumFragment : BaseVMFragment<WeChatNumViewModel>() { override fun setLayoutResId(): Int = R.layout.fragment_main_project override fun initVM(): WeChatNumViewModel = getViewModel() private val mFragmentList = mutableListOf<Fragment>() private val loadPageViewForStatus: BasePageViewForStatus = SimplePageViewForStatus() override fun initView() { llMainProjectLoadPageViewForStatus.failTextView().onClick { mViewModel.loadBlogType() } ViewPager2Delegate(vpMainProject, tlMainProject) vpMainProject.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { private var currentPosition = 0 //当前滑动位置 private var oldPosition = 0 //上一个滑动位置 override fun onPageScrollStateChanged(state: Int) { if (state == 0) { if (currentPosition == oldPosition) { if (currentPosition == 0) LiveEventBus.get(MAIN_PLAZA_CUT).post("") } oldPosition = currentPosition } } override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { currentPosition = position } }) } override fun initData() { mViewModel.loadBlogType() } override fun startObserve() { mViewModel.run { mBlogTypeListModel.observe(this@MainWeChatNumFragment, Observer { it -> it.loadPageStatus?.value?.let { loadPageStatus -> llMainProjectLoadPageViewForStatus.visibility = View.VISIBLE loadPageViewForStatus.convert(llMainProjectLoadPageViewForStatus, loadPageStatus) } it.showSuccess?.let { list -> mFragmentList.clear() llMainProjectLoadPageViewForStatus.visibility = View.GONE tlMainProject.removeAllViews() list.toMutableList().apply { forEach { tlMainProject?.let { tlMainProject -> tlMainProject.inflate(R.layout.layout_project_tab, false).apply { findViewById<TextView>(R.id.tvTabLayoutTitle)?.text = it.name tlMainProject.addView(this) } } mFragmentList.add( WeChatNumTypeFragment.newInstance(it.id) ) } } activity?.let { activity -> vpMainProject.adapter = MyFragmentPagerAdapter(activity, mFragmentList) } } }) } } }
0
Kotlin
9
71
672b054b5c1aba0b323e8e082a3dea13b25bf971
3,869
WanAndroid
Apache License 2.0
android/classic/src/main/kotlin/studio/forface/covid/android/classic/ClassicRouter.kt
4face-studi0
245,708,616
false
null
package studio.forface.covid.android.classic import androidx.fragment.app.FragmentActivity import studio.forface.covid.android.Router import studio.forface.covid.android.classic.ui.CountryStatActivity import studio.forface.covid.android.classic.ui.SearchActivity import studio.forface.covid.domain.entity.CountryId /** * This object will navigate though the pages of the App. * Implements [Router] * * @author <NAME> */ class ClassicRouter(private val activity: FragmentActivity) : Router { override fun toHome() { toSearch() activity.finish() } override fun toSearch() { SearchActivity.launch(activity) } override fun toCountryStat(id: CountryId) { CountryStatActivity.launch(activity, id) } override fun countryStatIntent(id: CountryId) = CountryStatActivity.intent(activity, id) } fun FragmentActivity.Router() = ClassicRouter(this)
2
Kotlin
0
6
ebabaf30bcb5d9cd46bfb7132a6046cc56f86362
908
Covid19
Apache License 2.0
src/main/kotlin/lib/InputDownloader.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 28575}
package lib import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.request.* import io.ktor.client.statement.* import java.io.File class InputDownloader { private val session = File("src/main/resources/session").readText() suspend fun downloadInput(day: Int, year: Int): String = download(day, year, "/input") suspend fun downloadDescription(day: Int, year: Int) : String = download(day, year, "") suspend fun download(day: Int, year: Int, suffix: String): String { val client = HttpClient(CIO) val resp: HttpResponse = client.get("https://adventofcode.com/$year/day/$day$suffix") {cookie("session", session)} client.close() return resp.bodyAsText() } suspend fun createInputFile(day: Int, year: Int) = createFile(day, year, "input.txt", downloadInput(day, year)) suspend fun createDescriptionFile(day: Int, year: Int) = createFile(day, year, "description.html", downloadDescription(day, year)) fun createFile(day: Int, year: Int, fileName: String, content: String) { val f = File("src/main/kotlin/aoc$year/day$day/$fileName") if(!f.isFile) { f.parentFile.mkdirs() f.writeText(content.replace("\n", System.lineSeparator())) } } companion object { val instance: InputDownloader = InputDownloader() } }
0
Kotlin
0
0
482052531188c2b3a6e4042d7fcb3f206865720f
1,374
AoC-2023-DDJ
MIT License
utils/ui/src/test/java/com/grappim/hateitorrateit/utils/ui/NativeTextTest.kt
Grigoriym
704,244,986
false
{"Kotlin": 500015}
package com.grappim.hateitorrateit.core import com.grappim.hateitorrateit.ui.R import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import kotlin.test.assertEquals @RunWith(RobolectricTestRunner::class) class NativeTextTest { private val context = RuntimeEnvironment.getApplication() @Test fun `empty NativeText should return empty string`() { val empty = NativeText.Empty assertEquals(empty.asString(context), "") } @Test fun `simple NativeText should return provided text`() { val text = "some text to check" val simple = NativeText.Simple(text) assertEquals(simple.asString(context), text) } @Test fun `multi NativeText should return correct text`() { val multi = NativeText.Multi( listOf( NativeText.Simple("simple"), NativeText.Empty, NativeText.Simple("text") ) ) assertEquals(multi.asString(context), "simpletext") } @Test fun `resource NativeText should return provided text`() { val idRes = R.string.add_picture_from val simple = NativeText.Resource(idRes) assertEquals(simple.asString(context), context.getString(idRes)) } }
7
Kotlin
0
1
6d34205597a6934f0f71b7120abfb5003997e8db
1,346
HateItOrRateIt
Apache License 2.0
src/main/kotlin/no/nav/k9/los/integrasjon/k9/K9SakServiceSystemClient.kt
navikt
238,874,021
false
{"Kotlin": 1669919, "JavaScript": 741, "Shell": 659, "Dockerfile": 343, "PLpgSQL": 167}
package no.nav.k9.los.integrasjon.k9 import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult import com.github.kittinunf.fuel.httpPost import io.ktor.http.* import kotlinx.coroutines.runBlocking import no.nav.helse.dusseldorf.ktor.core.Retry import no.nav.helse.dusseldorf.ktor.metrics.Operation import no.nav.helse.dusseldorf.oauth2.client.AccessTokenClient import no.nav.helse.dusseldorf.oauth2.client.CachedAccessTokenClient import no.nav.k9.los.Configuration import no.nav.k9.los.integrasjon.rest.NavHeaders import no.nav.k9.los.utils.Cache import no.nav.k9.los.utils.CacheObject import no.nav.k9.los.utils.LosObjectMapper import no.nav.k9.sak.kontrakt.behandling.BehandlingIdDto import no.nav.k9.sak.kontrakt.behandling.BehandlingIdListe import org.slf4j.LoggerFactory import java.time.Duration import java.time.LocalDateTime import java.util.* open class K9SakServiceSystemClient constructor( val configuration: Configuration, val accessTokenClient: AccessTokenClient, val scope: String ) : IK9SakService { private val log = LoggerFactory.getLogger("K9SakService")!! private val cachedAccessTokenClient = CachedAccessTokenClient(accessTokenClient) private val url = configuration.k9Url() private val scopes = setOf(scope) private val cache = Cache<UUID, Boolean>(cacheSize = 10000) private val cacheObjectDuration = Duration.ofHours(12) override suspend fun refreshBehandlinger(behandlingUuid: Collection<UUID>) { val nå = LocalDateTime.now() log.info("Forespørsel om refresh av ${behandlingUuid.size} behandlinger") val uoppfriskedeBehandlingUuider = behandlingUuid.filterNot { cache.containsKey(it, nå) } log.info("Kommer til å refreshe ${uoppfriskedeBehandlingUuider.size} behandlinger etter sjekk mot cache av oppfriskede behandlinger, i bolker på 100 stykker") for (uuids in uoppfriskedeBehandlingUuider.chunked(100)) { utførRefreshKallOgOppdaterCache(uuids) } } private suspend fun utførRefreshKallOgOppdaterCache(behandlinger: Collection<UUID>) { log.info("Trigger refresh av ${behandlinger.size} behandlinger") log.info("Behandlinger som refreshes: $behandlinger") val dto = BehandlingIdListe(behandlinger.map { BehandlingIdDto(it) }) val body = LosObjectMapper.instance.writeValueAsString(dto) val httpRequest = "${url}/behandling/backend-root/refresh" .httpPost() .body( body ) .header( HttpHeaders.Authorization to cachedAccessTokenClient.getAccessToken(scopes).asAuthoriationHeader(), HttpHeaders.Accept to "application/json", HttpHeaders.ContentType to "application/json", NavHeaders.CallId to UUID.randomUUID().toString() ) Retry.retry( operation = "refresh oppgave", initialDelay = Duration.ofMillis(200), factor = 2.0, logger = log ) { val (request, _, result) = Operation.monitored( app = "k9-los-api", operation = "hent-ident", resultResolver = { 200 == it.second.statusCode } ) { httpRequest.awaitStringResponseResult() } result.fold( { success -> registrerICache(behandlinger, LocalDateTime.now()) success }, { error -> log.error("Error response = '${error.response.body().asString("text/plain")}' fra '${request.url}'") log.error(error.toString()) } ) } } private fun registrerICache(behandingUuid: Collection<UUID>, now: LocalDateTime) { for (uuid in behandingUuid) { cache.set(uuid, CacheObject(true, now.plus(cacheObjectDuration))) } log.info("La til ${behandingUuid.size} behandlinger i cache") } }
8
Kotlin
0
0
f606f3e4f6619c941c610b0307dca73598aa0a02
4,004
k9-los-api
MIT License
views/src/test/java/com/guhungry/views/recyclerview/BindableViewHolderTest.kt
guhungry
142,478,766
false
null
package com.guhungry.views.recyclerview import android.view.View import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.IsEqual.equalTo import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.mockito.Mockito.mock class BindableViewHolderTest : Spek({ given("a default BaseLoadMoreAdapter") { val view by memoized { mock(View::class.java) } val sut by memoized { MockViewHolder(view) } on("bindData") { val expected = 555 sut.bindData(expected) it("should recieve correct data") { assertThat(sut.data, equalTo(expected)) } } on("onRecycled") { sut.onRecycled() it("should recieve correct data") { assertThat(sut.countRecycledCalled, equalTo(1)) } } } }) { private class MockViewHolder(view: View) : BindableViewHolder<Int>(view) { var data = 0 var countRecycledCalled = 0 override fun bindData(data: Int) { this.data = data } override fun onRecycled() { countRecycledCalled++ } } }
0
Kotlin
0
0
5a4c4c4d428bef602949399de0fbb9198122e8fd
1,260
android-customviews
MIT License
sqlite-open-helper/src/commonMain/kotlin/internal/SQLiteGlobal.kt
illarionov
769,429,996
false
null
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.internal import ru.pixnews.wasm.sqlite.open.helper.sqlite.common.api.SqliteDatabaseJournalMode import ru.pixnews.wasm.sqlite.open.helper.sqlite.common.api.SqliteDatabaseSyncMode /** * Provides access to SQLite functions that affect all database connection, * such as memory management. * * The native code associated with SQLiteGlobal is also sets global configuration options * using sqlite3_config() then calls sqlite3_initialize() to ensure that the SQLite * library is properly initialized exactly once before any other framework or application * code has a chance to run. * * Verbose SQLite logging is enabled if the "log.tag.SQLiteLog" property is set to "V". * (per [SQLiteDebug.DEBUG_SQL_LOG]). * */ @Suppress("OBJECT_NAME_INCORRECT") internal object SQLiteGlobal { /** * When opening a database, if the WAL file is larger than this size, we'll truncate it. * * (If it's 0, we do not truncate.) */ const val WAL_TRUNCATE_SIZE: Long = 1048576 // values derived from: // https://android.googlesource.com/platform/frameworks/base.git/+/master/core/res/res/values/config.xml const val DEFAULT_PAGE_SIZE: Int = 1024 /** * Gets the journal size limit in bytes. */ const val JOURNAL_SIZE_LIMIT: Int = 524288 /** * Gets the WAL auto-checkpoint integer in database pages. */ const val WAL_AUTO_CHECKPOINT: Int = 1000 /** * Gets the connection pool size when in WAL mode. */ const val WAL_CONNECTION_POOL_SIZE: Int = 10 /** * Amount of heap memory that will be by all database connections within a single process. * * Set to 8MB in AOSP. * * https://www.sqlite.org/c3ref/hard_heap_limit64.html */ const val SOFT_HEAP_LIMIT: Long = 8 * 1024 * 1024 /** * Gets the default journal mode when WAL is not in use. */ val DEFAULT_JOURNAL_MODE: SqliteDatabaseJournalMode = SqliteDatabaseJournalMode.TRUNCATE /** * Gets the default database synchronization mode when WAL is not in use. */ val DEFAULT_SYNC_MODE: SqliteDatabaseSyncMode = SqliteDatabaseSyncMode.FULL /** * Gets the database synchronization mode when in WAL mode. */ val WAL_SYNC_MODE: SqliteDatabaseSyncMode = SqliteDatabaseSyncMode.NORMAL }
0
null
1
3
5f513e2413987ce681f12ea8e14a2aff2c56a7fd
2,619
wasm-sqlite-open-helper
Apache License 2.0
adoptium-marketplace-server/adoptium-marketplace-persistence/src/main/kotlin/net/adoptium/marketplace/dataSources/persitence/mongo/MongoClient.kt
adoptium
707,379,717
false
{"Kotlin": 158856, "Java": 57343, "Shell": 1954, "Dockerfile": 1844, "CSS": 992, "HTML": 576}
package net.adoptium.marketplace.dataSources.persitence.mongo import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.mongodb.ConnectionString import com.mongodb.MongoClientSettings import org.litote.kmongo.coroutine.CoroutineDatabase import org.litote.kmongo.coroutine.coroutine import org.litote.kmongo.id.jackson.IdJacksonModule import org.litote.kmongo.reactivestreams.KMongo import org.litote.kmongo.util.KMongoConfiguration import org.slf4j.LoggerFactory import javax.inject.Singleton interface MongoClient { fun getDatabase(): CoroutineDatabase } @Singleton class MongoClientImpl : MongoClient { private var db: CoroutineDatabase? = null companion object { @JvmStatic private val LOGGER = LoggerFactory.getLogger(this::class.java) private const val DEFAULT_DBNAME = "api-data" private const val DEFAULT_HOST = "localhost" private const val DEFAULT_PORT = "27017" private const val DEFAULT_SERVER_SELECTION_TIMEOUT_MILLIS = "100" fun createConnectionString( dbName: String, username: String? = null, password: String? = null, host: String? = DEFAULT_HOST, port: String? = DEFAULT_PORT, serverSelectionTimeoutMills: String? = DEFAULT_SERVER_SELECTION_TIMEOUT_MILLIS ): String { val hostNonNull = host ?: DEFAULT_HOST val portNonNull = port ?: DEFAULT_PORT val serverSelectionTimeoutMillsNonNull = serverSelectionTimeoutMills ?: DEFAULT_SERVER_SELECTION_TIMEOUT_MILLIS val usernamePassword = if (username != null && password != null) { "$username:$password@" } else { "" } val server = "$hostNonNull:$portNonNull" return System.getProperty("MONGODB_TEST_CONNECTION_STRING")?.plus("/$dbName") ?: if (username != null && password != null) { LOGGER.info("Connecting to mongodb://$username:a-password@$server/$dbName") "mongodb://$usernamePassword$server/$dbName" } else { val developmentConnectionString = "mongodb://$usernamePassword$server/?serverSelectionTimeoutMS=$serverSelectionTimeoutMillsNonNull" LOGGER.info("Using development connection string - $developmentConnectionString") developmentConnectionString } } } fun createDb(): CoroutineDatabase { val dbName = System.getenv("MONGODB_DBNAME") ?: DEFAULT_DBNAME val connectionString = createConnectionString( dbName, username = System.getenv("MONGODB_USER"), password = System.getenv("MONGODB_PASSWORD"), host = System.getenv("MONGODB_HOST"), port = System.getenv("MONGODB_PORT"), serverSelectionTimeoutMills = System.getenv("MONGODB_SERVER_SELECTION_TIMEOUT_MILLIS") ) var settingsBuilder = MongoClientSettings.builder() .applyConnectionString(ConnectionString(connectionString)) val sslEnabled = System.getenv("MONGODB_SSL")?.toBoolean() if (sslEnabled == true) { settingsBuilder = settingsBuilder.applyToSslSettings { it.enabled(true).invalidHostNameAllowed(true) } } KMongoConfiguration.registerBsonModule(IdJacksonModule()) KMongoConfiguration.registerBsonModule(Jdk8Module()) KMongoConfiguration.registerBsonModule(JavaTimeModule()) KMongoConfiguration.bsonMapper.disable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID) KMongoConfiguration.bsonMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) KMongoConfiguration.bsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) val client = KMongo.createClient(settingsBuilder.build()).coroutine return client.getDatabase(dbName) } override fun getDatabase(): CoroutineDatabase { if (db == null) { db = createDb(); } return db!! } }
7
Kotlin
3
4
40289a01c90c3dc38fb715d6007aef368c260ff0
4,261
marketplace-api.adoptium.net
Apache License 2.0
src/Day05.kt
MarkRunWu
573,656,261
false
{"Kotlin": 25971}
import java.lang.Math.abs import java.util.Stack fun main() { fun parseStacks(input: List<String>): List<Stack<String>> { val stackStrings = input.joinToString("\n") { it }.split( "\n\n" )[0].split("\n") val labelLine = stackStrings.last().split(" ") val stacks = labelLine.map { Stack<String>() } val stackSize = stacks.size val stackValues = stackStrings.subList(0, stackStrings.size - 1).reversed() .map { val items = arrayListOf<String>() for (i in 0 until stackSize) { if (i * 4 + 3 <= it.length) { items.add(it.slice(i * 4 until i * 4 + 3).trim()) } else { items.add("") } } items } for (values in stackValues) { for (i in 0 until stackSize) { if (values[i].isEmpty()) { continue } stacks[i].push(values[i]) } } return stacks } data class Movement(val steps: Int, val fromIndex: Int, val toIndex: Int) fun parseMovementList(commands: List<String>): List<Movement> { val pattern = Regex("^move (\\d+) from (\\d+) to (\\d+)") return commands.map { pattern.findAll(it) }.map { Movement( it.first().groups[1]!!.value.toInt(), it.first().groups[2]!!.value.toInt() - 1, it.first().groups[3]!!.value.toInt() - 1 ) } } fun part1(input: List<String>): String { val stacks = parseStacks(input) val movementList = parseMovementList(input.joinToString("\n") { it }.split("\n\n").last().split("\n")) movementList.forEach { for (i in 0 until it.steps) { stacks[it.toIndex].push(stacks[it.fromIndex].pop()) } } return stacks.map { it.last() }.joinToString("") { it }.replace("[", "").replace("]", "") } fun part2(input: List<String>): String { val stacks = parseStacks(input) val movementList = parseMovementList(input.joinToString("\n") { it }.split("\n\n").last().split("\n")) val tmpStack = Stack<String>() movementList.forEach { tmpStack.clear() for (i in 0 until it.steps) { tmpStack.push(stacks[it.fromIndex].pop()) } for (i in 0 until it.steps) { stacks[it.toIndex].push(tmpStack.pop()) } } return stacks.map { it.last() }.joinToString("") { it }.replace("[", "").replace("]", "") } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ced885dcd6b32e8d3c89a646dbdcf50b5665ba65
2,883
AOC-2022
Apache License 2.0
yenaly_libs/src/main/java/com/yenaly/yenaly_libs/utils/DeviceUtil.kt
YenalyLiew
524,046,895
false
{"Kotlin": 723868, "Java": 88900}
@file:Suppress("unused") package com.yenaly.yenaly_libs.utils import android.annotation.SuppressLint import android.content.res.Configuration import android.content.res.Resources import androidx.core.util.TypedValueCompat /** * 通过dp获取相应px值 */ val Number.dp: Int @JvmName("dpToPx") get() = TypedValueCompat.dpToPx( this.toFloat(), applicationContext.resources.displayMetrics ).toInt() /** * 通过sp获取相应px值 */ val Number.sp: Int @JvmName("spToPx") get() = TypedValueCompat.spToPx( this.toFloat(), applicationContext.resources.displayMetrics ).toInt() /** * 获取本地储存状态栏高度px */ val statusBarHeight: Int @SuppressLint("DiscouragedApi", "InternalInsetResource") get() { val resources: Resources = applicationContext.resources val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android") return resources.getDimensionPixelSize(resourceId) } /** * 获取本地储存导航栏高度px */ val navBarHeight: Int @SuppressLint("DiscouragedApi", "InternalInsetResource") get() { val resources: Resources = applicationContext.resources val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android") return resources.getDimensionPixelSize(resourceId) } /** * 判断当前是否横屏 */ val isOrientationLandscape: Boolean get() { return applicationContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE }
21
Kotlin
78
999
b0fa1a9e50b1567e4b5a504dcb6579d5f35427fa
1,481
Han1meViewer
Apache License 2.0
app/src/main/java/cn/saymagic/begonia/ui/activity/ViewPhotoActivity.kt
saymagic
140,292,136
false
null
package cn.saymagic.begonia.ui.activity import android.Manifest import android.app.SearchManager import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.widget.SearchView import android.widget.Toast import cn.saymagic.begonia.R import cn.saymagic.begonia.fundamental.into import cn.saymagic.begonia.repository.Status import cn.saymagic.begonia.util.Constants import cn.saymagic.begonia.viewmodel.PhotoListViewModel import cn.saymagic.begonia.viewmodel.ViewPhotoModel import kotlinx.android.synthetic.main.activity_view_photo.* import android.support.v4.app.ActivityCompat import android.content.pm.PackageManager class ViewPhotoActivity : AppCompatActivity() { lateinit var photoModel: ViewPhotoModel lateinit var menu: Menu private val REQUEST_EXTERNAL_STORAGE = 1 private val PERMISSIONS_STORAGE = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_view_photo) val photoId = intent.getStringExtra(Constants.PHOTO_ID) if (photoId == null) { finish() return } photoModel = ViewModelProviders.of(this).get(ViewPhotoModel::class.java) photoModel.photo.observe(this, Observer { photoImg.setImageBitmap(it) val inflater = menuInflater inflater.inflate(R.menu.view_photo_menu, menu) menu.findItem(R.id.set_as_desktop)?.setOnMenuItemClickListener { photoModel.setWallpaper() true } menu.findItem(R.id.save_to_system)?.setOnMenuItemClickListener { val permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) if (permission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE) } else { photoModel.saveToPhotoAlbum() } true } }) photoModel.networkState.observe(this, Observer { when (it?.status) { Status.FAILED -> viewPhotoProgressLayout.showError(R.drawable.ic_error_black_24dp, getString(R.string.error_title), it?.msg?.message, getString(R.string.constant_retry), { photoModel.rerty?.invoke() }) Status.RUNNING -> viewPhotoProgressLayout.showLoading() Status.SUCCESS -> viewPhotoProgressLayout.showContent() } }) photoModel.toastTip.observe(this, Observer { Toast.makeText(this, it, Toast.LENGTH_LONG).show() }) photoModel.getPhoto(photoId) } override fun onCreateOptionsMenu(menu: Menu): Boolean { this.menu = menu return true } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_EXTERNAL_STORAGE && grantResults[0] == PackageManager.PERMISSION_GRANTED) { photoModel.saveToPhotoAlbum() } } }
0
Kotlin
13
56
92d75320f516731d9ea3be8fd495b9708b352024
3,570
Begonia
The Unlicense
app/src/main/java/io/github/alanrb/tikiassignment/data/KeywordRepositoryImpl.kt
alanrb
162,383,977
false
null
package io.github.alanrb.tikiassignment.data import io.github.alanrb.tikiassignment.data.remote.HttpService import io.github.alanrb.tikiassignment.domain.KeywordRepository import io.reactivex.Single class KeywordRepositoryImpl(private val httpService: HttpService) : KeywordRepository { override fun keywords(): Single<List<String>> { return httpService.getKeyword() } }
0
Kotlin
0
2
74fb51f73c41ea3a60a544a11f3165131ef61a78
389
TIKI-Assignment
Apache License 2.0
app/src/main/java/com/qdot/mylandai/HomeActivity.kt
JoyMajumdar2001
832,791,430
false
{"Kotlin": 23427}
package com.qdot.mylandai import android.Manifest import android.content.pm.PackageManager import android.graphics.Color import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import coil.load import com.google.ai.client.generativeai.GenerativeModel import com.google.android.gms.location.LocationServices import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.mapbox.mapboxsdk.Mapbox import com.mapbox.mapboxsdk.annotations.MarkerOptions import com.mapbox.mapboxsdk.annotations.PolygonOptions import com.mapbox.mapboxsdk.camera.CameraPosition import com.mapbox.mapboxsdk.geometry.LatLng import com.permissionx.guolindev.PermissionX import com.qdot.mylandai.databinding.ActivityHomeBinding import io.appwrite.Client import io.appwrite.ID import io.appwrite.Query import io.appwrite.services.Account import io.appwrite.services.Databases import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import org.json.JSONObject class HomeActivity : AppCompatActivity() { private lateinit var binding: ActivityHomeBinding private lateinit var databases : Databases private lateinit var account : Account private lateinit var generativeModel: GenerativeModel private val polygonPoints: ArrayList<LatLng> = ArrayList() private val gson : Gson = Gson() private lateinit var okHttpClient : OkHttpClient private lateinit var styleUrl : String private val jsonType = "application/json".toMediaType() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Mapbox.getInstance(this) binding = ActivityHomeBinding.inflate(layoutInflater) setContentView(binding.root) val key = BuildConfig.MAPTILER_API_KEY val mapId = "satellite" styleUrl = "https://api.maptiler.com/maps/$mapId/style.json?key=$key" val client = Client(this) .setEndpoint("https://cloud.appwrite.io/v1") .setProject("PROJECT_ID") .setSelfSigned(true) okHttpClient = OkHttpClient() account = Account(client) databases = Databases(client) generativeModel = GenerativeModel( modelName = "gemini-1.5-flash", apiKey = "API_KEY" ) PermissionX.init(this) .permissions(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION) .onExplainRequestReason { scope, deniedList -> scope.showRequestReasonDialog(deniedList, "Core fundamental are based on these permissions", "OK", "Cancel") } .request{ allGranted, _, _ -> if(allGranted){ updateUi(styleUrl) } } } private fun updateUi(styleType : String) { binding.addFieldBtn.visibility = View.GONE binding.saveFieldBtn.visibility = View.GONE binding.clearFieldBtn.visibility = View.GONE binding.weatherCard.visibility= View.GONE val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { return } fusedLocationClient.lastLocation .addOnSuccessListener { location -> binding.mapView.getMapAsync { it.setStyle(styleType) it.cameraPosition = CameraPosition.Builder() .target(LatLng(location.latitude,location.longitude)) .zoom(15.0).build() } } CoroutineScope(Dispatchers.IO).launch { val user = account.get() val result = databases.listDocuments( databaseId = "669df1e1000d18adda57", collectionId = "669df1fc0029448b6bef", queries = listOf( Query.equal("userid",user.id) ) ) if (result.documents.isEmpty() ){ withContext(Dispatchers.Main) { binding.addFieldBtn.visibility = View.VISIBLE binding.addFieldBtn.setOnClickListener { binding.addFieldBtn.visibility = View.GONE binding.saveFieldBtn.visibility = View.VISIBLE binding.clearFieldBtn.visibility = View.VISIBLE binding.mapView.getMapAsync { mapbox -> mapbox.addOnMapLongClickListener { lt -> polygonPoints.add(lt) mapbox.addMarker(MarkerOptions() .position(lt)) if (polygonPoints.size >= 4) { val ploy = PolygonOptions() .addAll(polygonPoints) .strokeColor(Color.RED) .fillColor(Color.argb(50, 255, 0, 0)) mapbox.addPolygon(ploy) } return@addOnMapLongClickListener true } binding.clearFieldBtn.setOnClickListener { polygonPoints.clear() mapbox.clear() mapbox.removeOnMapLongClickListener { return@removeOnMapLongClickListener true } binding.addFieldBtn.visibility = View.VISIBLE binding.saveFieldBtn.visibility = View.GONE binding.clearFieldBtn.visibility = View.GONE } binding.saveFieldBtn.setOnClickListener { CoroutineScope(Dispatchers.IO).launch { val pl = gson.toJson(polygonPoints) val llList : MutableList<MutableList<Double>> = mutableListOf() polygonPoints.map { llList.add(mutableListOf(it.longitude,it.latitude)) } llList.add(mutableListOf(polygonPoints[0].longitude,polygonPoints[0].latitude)) val agModel = SendPolyModel( name = user.id, geo_json = GeoJson( type = "Feature", properties = JSONObject("{}"), geometry = Geometry( type = "Polygon", coordinates = listOf(llList.toList()) ) ) ) val body = gson.toJson(agModel).toRequestBody(jsonType) val req = Request.Builder() .header("Content-Type","application/json") .url("http://api.agromonitoring.com/agro/1.0/polygons?appid=API_KEY") .post(body) .build() val resp = okHttpClient.newCall(req).execute() val jsp = JSONObject(resp.body!!.string()) databases.createDocument( databaseId = "669df1e1000d18adda57", collectionId = "669df1fc0029448b6bef", documentId = ID.unique(), data = PolyModel(userid = user.id, ploygon = pl, id = jsp.getString("id")) ) withContext(Dispatchers.Main){ binding.addFieldBtn.visibility = View.GONE binding.saveFieldBtn.visibility = View.GONE binding.clearFieldBtn.visibility = View.GONE updateUi(styleUrl) } } } } } } }else{ val polygonId = result.documents[0].data["id"].toString() val dta = result.documents[0].data["ploygon"].toString() val type = object : TypeToken<ArrayList<LatLng>>() {}.type val polyList : ArrayList<LatLng> = gson.fromJson(dta,type) val req = Request.Builder() .header("Content-Type","application/json") .url("http://api.agromonitoring.com/agro/1.0/polygons/${polygonId}?appid=API_KEY") .build() val resp = okHttpClient.newCall(req).execute() val jsp = JSONObject(resp.body!!.string()) val lon = jsp.getJSONArray("center")[0] as Double val lat = jsp.getJSONArray("center")[1] as Double val area = jsp.getDouble("area") val req1 = Request.Builder() .header("Content-Type","application/json") .url("https://api.agromonitoring.com/agro/1.0/weather?lat=${lat}&lon=${lon}&appid=API_KEY") .build() val resp1 = okHttpClient.newCall(req1).execute() val wJson = JSONObject(resp1.body!!.string()) val imgWeather = wJson.getJSONArray("weather").getJSONObject(0).getString("icon") val textWeather = wJson.getJSONArray("weather").getJSONObject(0).getString("main") val temp = wJson.getJSONObject("main").getDouble("temp") val pressure = wJson.getJSONObject("main").getDouble("pressure") val humidity = wJson.getJSONObject("main").getDouble("humidity") val wSpeed = wJson.getJSONObject("wind").getDouble("speed") val wDir = wJson.getJSONObject("wind").getDouble("deg") val clouds = wJson.getJSONObject("clouds").getDouble("all") val req2 = Request.Builder() .header("Content-Type","application/json") .url("http://api.agromonitoring.com/agro/1.0/soil?polyid=${polygonId}&appid=API_KEY") .build() val resp2 = okHttpClient.newCall(req2).execute() val soilJson = JSONObject(resp2.body!!.string()) val soilTemp10 = soilJson.getDouble("t10") val soilMos = soilJson.getDouble("moisture") val soilTemp = soilJson.getDouble("t0") val gimPrompt = "Assume you are an agriculture bot." + " I have a farm land with location lat=${lat}°, long=${lon}°. " + "Area of the land is $area ha. "+ "The weather current now is like temperature: $temp degrees, " + "wind: $wSpeed m/s, humidity: $humidity%, air pressure: $pressure hPa and cloud percentage is $clouds%. " + "The soil information is like Temperature on the 10 centimeters depth is ${soilTemp10}k, " + "Soil moisture is $soilMos m3/m3 and Surface temperature is $soilTemp k. " + "So suggest me top 5 crop for this farm field in a json format with a percentage of suitability " + "and also 5 top tips for on how to improve the farm land based on the data given. " + "Give only json output noting other. The json object should contain a json array named crops and under which there will be jsonobjects with two value crop and suitability " + "on the other hand there will be another json array named tips under which 5 json objects with name tip" val gimResponse = generativeModel.generateContent(gimPrompt) val fieldInfo = FieldInfoModel( lat,lon,area,temp,humidity,pressure, wSpeed,wDir,clouds,soilTemp10,soilTemp, soilMos,gimResponse.text.toString() ) withContext(Dispatchers.Main) { val btmSheet = FieldSheet(fieldInfo) binding.addFieldBtn.visibility = View.GONE binding.mapView.getMapAsync { mapbox -> mapbox.addMarker(MarkerOptions() .position(LatLng(lat, lon)) .title("Your Field")) val ploy1 = PolygonOptions() .addAll(polyList) .strokeColor(Color.RED) .fillColor(Color.argb(50, 255, 0, 0)) mapbox.addPolygon(ploy1) mapbox.setOnPolygonClickListener { btmSheet.show(supportFragmentManager,"FIELD") } } binding.weatherCard.visibility = View.VISIBLE binding.weatheImage.load("https://openweathermap.org/img/wn/${imgWeather}@2x.png") binding.weatheInfo.text = textWeather } } } } }
0
Kotlin
0
0
cbf906830ba12d1d364e14e6faed0d85320bd256
14,434
MyLandAi
MIT License
widgetssdk/src/main/java/com/glia/widgets/chat/controller/ChatController.kt
salemove
312,288,713
false
{"Kotlin": 1297050, "Java": 726043, "Shell": 1802}
package com.glia.widgets.chat.controller import android.net.Uri import android.view.View import com.glia.androidsdk.GliaException import com.glia.androidsdk.Operator import com.glia.androidsdk.chat.AttachmentFile import com.glia.androidsdk.chat.SingleChoiceAttachment import com.glia.androidsdk.chat.SingleChoiceOption import com.glia.androidsdk.chat.VisitorMessage import com.glia.androidsdk.comms.MediaDirection import com.glia.androidsdk.comms.MediaUpgradeOffer import com.glia.androidsdk.comms.OperatorMediaState import com.glia.androidsdk.engagement.EngagementFile import com.glia.androidsdk.engagement.Survey import com.glia.androidsdk.omnicore.OmnicoreEngagement import com.glia.androidsdk.site.SiteInfo import com.glia.widgets.Constants import com.glia.widgets.GliaWidgets import com.glia.widgets.chat.ChatManager import com.glia.widgets.chat.ChatType import com.glia.widgets.chat.ChatView import com.glia.widgets.chat.ChatViewCallback import com.glia.widgets.chat.domain.GliaOnOperatorTypingUseCase import com.glia.widgets.chat.domain.GliaSendMessagePreviewUseCase import com.glia.widgets.chat.domain.GliaSendMessageUseCase import com.glia.widgets.chat.domain.IsAuthenticatedUseCase import com.glia.widgets.chat.domain.IsFromCallScreenUseCase import com.glia.widgets.chat.domain.IsSecureConversationsChatAvailableUseCase import com.glia.widgets.chat.domain.IsShowSendButtonUseCase import com.glia.widgets.chat.domain.SiteInfoUseCase import com.glia.widgets.chat.domain.UpdateFromCallScreenUseCase import com.glia.widgets.chat.domain.gva.DetermineGvaButtonTypeUseCase import com.glia.widgets.chat.model.ChatItem import com.glia.widgets.chat.model.ChatState import com.glia.widgets.chat.model.CustomCardChatItem import com.glia.widgets.chat.model.Gva import com.glia.widgets.chat.model.GvaButton import com.glia.widgets.chat.model.OperatorMessageItem import com.glia.widgets.chat.model.OperatorStatusItem import com.glia.widgets.chat.model.Unsent import com.glia.widgets.core.callvisualizer.domain.IsCallVisualizerUseCase import com.glia.widgets.core.chathead.domain.HasPendingSurveyUseCase import com.glia.widgets.core.chathead.domain.SetPendingSurveyUsedUseCase import com.glia.widgets.core.dialog.DialogController import com.glia.widgets.core.dialog.domain.IsShowOverlayPermissionRequestDialogUseCase import com.glia.widgets.core.engagement.domain.GetEngagementStateFlowableUseCase import com.glia.widgets.core.engagement.domain.GliaEndEngagementUseCase import com.glia.widgets.core.engagement.domain.GliaOnEngagementEndUseCase import com.glia.widgets.core.engagement.domain.GliaOnEngagementUseCase import com.glia.widgets.core.engagement.domain.IsOngoingEngagementUseCase import com.glia.widgets.core.engagement.domain.IsQueueingEngagementUseCase import com.glia.widgets.core.engagement.domain.SetEngagementConfigUseCase import com.glia.widgets.core.engagement.domain.UpdateOperatorDefaultImageUrlUseCase import com.glia.widgets.core.engagement.domain.model.EngagementStateEvent import com.glia.widgets.core.engagement.domain.model.EngagementStateEventVisitor import com.glia.widgets.core.engagement.domain.model.EngagementStateEventVisitor.OperatorVisitor import com.glia.widgets.core.fileupload.domain.AddFileAttachmentsObserverUseCase import com.glia.widgets.core.fileupload.domain.AddFileToAttachmentAndUploadUseCase import com.glia.widgets.core.fileupload.domain.GetFileAttachmentsUseCase import com.glia.widgets.core.fileupload.domain.RemoveFileAttachmentObserverUseCase import com.glia.widgets.core.fileupload.domain.RemoveFileAttachmentUseCase import com.glia.widgets.core.fileupload.domain.SupportedFileCountCheckUseCase import com.glia.widgets.core.fileupload.model.FileAttachment import com.glia.widgets.core.mediaupgradeoffer.MediaUpgradeOfferRepository import com.glia.widgets.core.mediaupgradeoffer.MediaUpgradeOfferRepository.Submitter import com.glia.widgets.core.mediaupgradeoffer.MediaUpgradeOfferRepositoryCallback import com.glia.widgets.core.mediaupgradeoffer.domain.AcceptMediaUpgradeOfferUseCase import com.glia.widgets.core.mediaupgradeoffer.domain.AddMediaUpgradeOfferCallbackUseCase import com.glia.widgets.core.mediaupgradeoffer.domain.RemoveMediaUpgradeOfferCallbackUseCase import com.glia.widgets.core.notification.domain.CallNotificationUseCase import com.glia.widgets.core.operator.GliaOperatorMediaRepository.OperatorMediaStateListener import com.glia.widgets.core.operator.domain.AddOperatorMediaStateListenerUseCase import com.glia.widgets.core.queue.domain.GliaCancelQueueTicketUseCase import com.glia.widgets.core.queue.domain.GliaQueueForChatEngagementUseCase import com.glia.widgets.core.queue.domain.QueueTicketStateChangeToUnstaffedUseCase import com.glia.widgets.core.queue.domain.exception.QueueingOngoingException import com.glia.widgets.core.secureconversations.domain.IsSecureEngagementUseCase import com.glia.widgets.core.survey.OnSurveyListener import com.glia.widgets.core.survey.domain.GliaSurveyUseCase import com.glia.widgets.di.Dependencies import com.glia.widgets.filepreview.domain.usecase.DownloadFileUseCase import com.glia.widgets.filepreview.domain.usecase.IsFileReadyForPreviewUseCase import com.glia.widgets.helper.Logger import com.glia.widgets.helper.TAG import com.glia.widgets.helper.TimeCounter import com.glia.widgets.helper.TimeCounter.FormattedTimerStatusListener import com.glia.widgets.helper.formattedName import com.glia.widgets.helper.imageUrl import com.glia.widgets.view.MessagesNotSeenHandler import com.glia.widgets.view.MinimizeHandler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.Observer internal class ChatController( chatViewCallback: ChatViewCallback, private val mediaUpgradeOfferRepository: MediaUpgradeOfferRepository, private val callTimer: TimeCounter, private val minimizeHandler: MinimizeHandler, private val dialogController: DialogController, private val messagesNotSeenHandler: MessagesNotSeenHandler, private val callNotificationUseCase: CallNotificationUseCase, private val queueForChatEngagementUseCase: GliaQueueForChatEngagementUseCase, private val getEngagementUseCase: GliaOnEngagementUseCase, private val engagementEndUseCase: GliaOnEngagementEndUseCase, private val onOperatorTypingUseCase: GliaOnOperatorTypingUseCase, private val sendMessagePreviewUseCase: GliaSendMessagePreviewUseCase, private val sendMessageUseCase: GliaSendMessageUseCase, private val addOperatorMediaStateListenerUseCase: AddOperatorMediaStateListenerUseCase, private val cancelQueueTicketUseCase: GliaCancelQueueTicketUseCase, private val endEngagementUseCase: GliaEndEngagementUseCase, private val addFileToAttachmentAndUploadUseCase: AddFileToAttachmentAndUploadUseCase, private val addFileAttachmentsObserverUseCase: AddFileAttachmentsObserverUseCase, private val removeFileAttachmentObserverUseCase: RemoveFileAttachmentObserverUseCase, private val getFileAttachmentsUseCase: GetFileAttachmentsUseCase, private val removeFileAttachmentUseCase: RemoveFileAttachmentUseCase, private val supportedFileCountCheckUseCase: SupportedFileCountCheckUseCase, private val isShowSendButtonUseCase: IsShowSendButtonUseCase, private val isShowOverlayPermissionRequestDialogUseCase: IsShowOverlayPermissionRequestDialogUseCase, private val downloadFileUseCase: DownloadFileUseCase, private val siteInfoUseCase: SiteInfoUseCase, private val surveyUseCase: GliaSurveyUseCase, private val getGliaEngagementStateFlowableUseCase: GetEngagementStateFlowableUseCase, private val isFromCallScreenUseCase: IsFromCallScreenUseCase, private val updateFromCallScreenUseCase: UpdateFromCallScreenUseCase, private val ticketStateChangeToUnstaffedUseCase: QueueTicketStateChangeToUnstaffedUseCase, private val isQueueingEngagementUseCase: IsQueueingEngagementUseCase, private val addMediaUpgradeCallbackUseCase: AddMediaUpgradeOfferCallbackUseCase, private val removeMediaUpgradeCallbackUseCase: RemoveMediaUpgradeOfferCallbackUseCase, private val isSecureEngagementUseCase: IsSecureEngagementUseCase, private val isOngoingEngagementUseCase: IsOngoingEngagementUseCase, private val engagementConfigUseCase: SetEngagementConfigUseCase, private val isSecureEngagementAvailableUseCase: IsSecureConversationsChatAvailableUseCase, private val hasPendingSurveyUseCase: HasPendingSurveyUseCase, private val setPendingSurveyUsedUseCase: SetPendingSurveyUsedUseCase, private val isCallVisualizerUseCase: IsCallVisualizerUseCase, private val isFileReadyForPreviewUseCase: IsFileReadyForPreviewUseCase, private val acceptMediaUpgradeOfferUseCase: AcceptMediaUpgradeOfferUseCase, private val determineGvaButtonTypeUseCase: DetermineGvaButtonTypeUseCase, private val isAuthenticatedUseCase: IsAuthenticatedUseCase, private val updateOperatorDefaultImageUrlUseCase: UpdateOperatorDefaultImageUrlUseCase, private val chatManager: ChatManager ) : GliaOnEngagementUseCase.Listener, GliaOnEngagementEndUseCase.Listener, OnSurveyListener { private var backClickedListener: ChatView.OnBackClickedListener? = null private var viewCallback: ChatViewCallback? = null private var mediaUpgradeOfferRepositoryCallback: MediaUpgradeOfferRepositoryCallback? = null private var timerStatusListener: FormattedTimerStatusListener? = null private var engagementStateEventDisposable: Disposable? = null private val disposable = CompositeDisposable() private val operatorMediaStateListener = OperatorMediaStateListener { onNewOperatorMediaState(it) } private val sendMessageCallback: GliaSendMessageUseCase.Listener = object : GliaSendMessageUseCase.Listener { override fun messageSent(message: VisitorMessage?) { Logger.d(TAG, "messageSent: $message, id: ${message?.id}") message?.also { chatManager.onChatAction(ChatManager.Action.MessageSent(it)) } scrollChatToBottom() } override fun onMessageValidated() { viewCallback?.clearMessageInput() emitViewState { chatState.setLastTypedText("").setShowSendButton(isShowSendButtonUseCase("")) } } override fun errorOperatorNotOnline(message: Unsent) { onSendMessageOperatorOffline(message) } override fun error(ex: GliaException, message: Unsent) { onMessageSendError(ex, message) } } private var isVisitorEndEngagement = false @Volatile private var isChatViewPaused = false private var shouldHandleEndedEngagement = false // TODO pending photoCaptureFileUri - need to move some place better var photoCaptureFileUri: Uri? = null private val fileAttachmentObserver = Observer { _, _ -> viewCallback?.apply { emitUploadAttachments(getFileAttachmentsUseCase.execute()) emitViewState { chatState.setShowSendButton(isShowSendButtonUseCase(chatState.lastTypedText)) .setIsAttachmentButtonEnabled(supportedFileCountCheckUseCase.execute()) } } } @Volatile private var chatState: ChatState private val isSecureEngagement get() = isSecureEngagementUseCase() private val isQueueingOrOngoingEngagement get() = isQueueingEngagementUseCase() || isOngoingEngagementUseCase() fun initChat( companyName: String?, queueId: String?, visitorContextAssetId: String?, chatType: ChatType ) { val queueIds = if (queueId != null) arrayOf(queueId) else emptyArray() engagementConfigUseCase(chatType, queueIds) updateOperatorDefaultImageUrlUseCase() if (!hasPendingSurveyUseCase.invoke()) { ensureSecureMessagingAvailable() if (chatState.integratorChatStarted || dialogController.isShowingChatEnderDialog) { if (isSecureEngagement) { emitViewState { chatState.setSecureMessagingState() } } chatManager.onChatAction(ChatManager.Action.ChatRestored) return } emitViewState { chatState.initChat(companyName, queueId, visitorContextAssetId) } initChatManager() } } private fun ensureSecureMessagingAvailable() { if (!isSecureEngagement) return disposable.add( isSecureEngagementAvailableUseCase().subscribe({ if (it) { Logger.d(TAG, "Messaging is available") } else { Logger.d(TAG, "Messaging is unavailable") dialogController.showMessageCenterUnavailableDialog() } }, { Logger.e(TAG, "Checking for Messaging availability failed", it) dialogController.showUnexpectedErrorDialog() }) ) } private fun prepareChatComponents() { addFileAttachmentsObserverUseCase.execute(fileAttachmentObserver) initMediaUpgradeCallback() mediaUpgradeOfferRepository.addCallback(mediaUpgradeOfferRepositoryCallback) minimizeHandler.addListener { minimizeView() } createNewTimerCallback() callTimer.addFormattedValueListener(timerStatusListener) updateAllowFileSendState() } private fun queueForEngagement() { Logger.d(TAG, "queueForEngagement") disposable.add( queueForChatEngagementUseCase .execute(chatState.queueId, chatState.visitorContextAssetId) .subscribe({ queueForEngagementStarted() }) { queueForEngagementError(it) } ) } @Synchronized private fun emitViewState(callback: () -> ChatState?) { val state = callback() ?: return if (setState(state) && viewCallback != null) { Logger.d(TAG, "Emit state:\n$state") viewCallback?.emitState(chatState) } } fun onDestroy(retain: Boolean) { Logger.d(TAG, "onDestroy, retain:$retain") dialogController.dismissMessageCenterUnavailableDialog() destroyView() // viewCallback is accessed from multiple threads // and must be protected from race condition synchronized(this) { viewCallback = null } backClickedListener = null if (!retain) { disposable.clear() mediaUpgradeOfferRepository.stopAll() mediaUpgradeOfferRepositoryCallback = null timerStatusListener = null callTimer.clear() minimizeHandler.clear() getEngagementUseCase.unregisterListener(this) engagementEndUseCase.unregisterListener(this) onOperatorTypingUseCase.unregisterListener() removeFileAttachmentObserverUseCase.execute(fileAttachmentObserver) shouldHandleEndedEngagement = false chatManager.reset() } } fun onPause() { isChatViewPaused = true messagesNotSeenHandler.onChatWentBackground() surveyUseCase.unregisterListener(this) mediaUpgradeOfferRepositoryCallback?.let { removeMediaUpgradeCallbackUseCase(it) } } fun onImageItemClick(item: AttachmentFile, view: View) { if (isFileReadyForPreviewUseCase(item)) { viewCallback?.navigateToPreview(item, view) } else { viewCallback?.fileIsNotReadyForPreview() } } fun onMessageTextChanged(message: String) { emitViewState { chatState .setLastTypedText(message) .setShowSendButton(isShowSendButtonUseCase(message)) } sendMessagePreview(message) } fun sendMessage(message: String) { Logger.d(TAG, "Send MESSAGE: $message") clearMessagePreview() sendMessageUseCase.execute(message, sendMessageCallback) addQuickReplyButtons(emptyList()) } private fun sendMessagePreview(message: String) { if (chatState.isOperatorOnline) { sendMessagePreviewUseCase.execute(message) } } private fun clearMessagePreview() { // An empty string has to be sent to clear the message preview. sendMessagePreview("") } private fun onMessageSendError(ignore: GliaException, message: Unsent) { Logger.d(TAG, "messageSent exception") chatManager.onChatAction(ChatManager.Action.MessageSendError(message)) scrollChatToBottom() } private fun onSendMessageOperatorOffline(message: Unsent) { appendUnsentMessage(message) if (!chatState.engagementRequested) { queueForEngagement() } } private fun appendUnsentMessage(message: Unsent) { Logger.d(TAG, "appendUnsentMessage: $message") chatManager.onChatAction(ChatManager.Action.UnsentMessageReceived(message)) scrollChatToBottom() } private fun onOperatorTyping(isOperatorTyping: Boolean) { emitViewState { chatState.setIsOperatorTyping(isOperatorTyping) } } fun show() { Logger.d(TAG, "show") if (!chatState.isVisible) { emitViewState { chatState.changeVisibility(true) } } } fun onBackArrowClicked() { Logger.d(TAG, "onBackArrowClicked") if (isQueueingOrOngoingEngagement) { emitViewState { chatState.changeVisibility(false) } messagesNotSeenHandler.chatOnBackClicked() } navigateBack() } private fun navigateBack() { if (isFromCallScreenUseCase.isFromCallScreen) { viewCallback?.backToCall() } else { backClickedListener?.onBackClicked() onDestroy(isQueueingOrOngoingEngagement || isAuthenticatedUseCase()) Dependencies.getControllerFactory().destroyCallController() } updateFromCallScreenUseCase.updateFromCallScreen(false) } fun noMoreOperatorsAvailableDismissed() { Logger.d(TAG, "noMoreOperatorsAvailableDismissed") stop() dialogController.dismissCurrentDialog() } fun unexpectedErrorDialogDismissed() { Logger.d(TAG, "unexpectedErrorDialogDismissed") stop() dialogController.dismissCurrentDialog() } fun endEngagementDialogYesClicked() { Logger.d(TAG, "endEngagementDialogYesClicked") isVisitorEndEngagement = true stop() dialogController.dismissDialogs() } fun endEngagementDialogDismissed() { Logger.d(TAG, "endEngagementDialogDismissed") dialogController.dismissCurrentDialog() } fun leaveChatClicked() { Logger.d(TAG, "leaveChatClicked") if (chatState.isOperatorOnline) dialogController.showExitChatDialog(chatState.formattedOperatorName) } fun onXButtonClicked() { Logger.d(TAG, "onXButtonClicked") if (isQueueingEngagementUseCase()) { dialogController.showExitQueueDialog() } else { Dependencies.getControllerFactory().destroyControllers() } } val isChatVisible: Boolean get() = chatState.isVisible // viewCallback is accessed from multiple threads // and must be protected from race condition @Synchronized fun setViewCallback(chatViewCallback: ChatViewCallback) { Logger.d(TAG, "setViewCallback") viewCallback = chatViewCallback viewCallback?.emitState(chatState) viewCallback?.emitUploadAttachments(getFileAttachmentsUseCase.execute()) // always start in bottom emitViewState { chatState.isInBottomChanged(true).changeVisibility(true) } viewCallback?.scrollToBottomImmediate() chatState.pendingNavigationType?.also { viewCallback?.navigateToCall(it) } } fun setOnBackClickedListener(finishCallback: ChatView.OnBackClickedListener?) { this.backClickedListener = finishCallback } fun onResume() { Logger.d(TAG, "onResume") if (hasPendingSurveyUseCase.invoke()) { shouldHandleEndedEngagement = true surveyUseCase.registerListener(this) return } if (shouldHandleEndedEngagement) { // Engagement has been started if (!isOngoingEngagementUseCase.invoke()) { // Engagement has ended surveyUseCase.registerListener(this) } else { // Engagement is ongoing onResumeSetup() } } else { // New session onResumeSetup() } } private fun onResumeSetup() { isChatViewPaused = false messagesNotSeenHandler.callChatButtonClicked() subscribeToEngagementStateChange() surveyUseCase.registerListener(this) mediaUpgradeOfferRepositoryCallback?.let { addMediaUpgradeCallbackUseCase(it) } if (isShowOverlayPermissionRequestDialogUseCase.execute()) { dialogController.showOverlayPermissionsDialog() } } private fun subscribeToEngagementStateChange() { engagementStateEventDisposable?.dispose() engagementStateEventDisposable = getGliaEngagementStateFlowableUseCase .execute() .subscribe({ onEngagementStateChanged(it) }) { Logger.e(TAG, it.message) } disposable.add(engagementStateEventDisposable!!) } private fun onEngagementStateChanged(engagementState: EngagementStateEvent) { val visitor: EngagementStateEventVisitor<Operator> = OperatorVisitor() when (engagementState.type!!) { EngagementStateEvent.Type.ENGAGEMENT_OPERATOR_CHANGED -> onOperatorChanged( visitor.visit(engagementState) ) EngagementStateEvent.Type.ENGAGEMENT_OPERATOR_CONNECTED -> { shouldHandleEndedEngagement = true onOperatorConnected(visitor.visit(engagementState)) } EngagementStateEvent.Type.ENGAGEMENT_TRANSFERRING -> onTransferring() EngagementStateEvent.Type.ENGAGEMENT_ONGOING -> onEngagementOngoing( visitor.visit(engagementState) ) EngagementStateEvent.Type.ENGAGEMENT_ENDED -> { Logger.d(TAG, "Engagement Ended") if (!isOngoingEngagementUseCase.invoke()) { dialogController.dismissDialogs() } } EngagementStateEvent.Type.NO_ENGAGEMENT -> { Logger.d(TAG, "NoEngagement") } } } private fun onEngagementOngoing(operator: Operator) { emitViewState { chatState.operatorConnected(operator.formattedName, operator.imageUrl) } } private fun onOperatorConnected(operator: Operator) { operatorConnected(operator.formattedName, operator.imageUrl) } private fun onOperatorChanged(operator: Operator) { operatorChanged(operator.formattedName, operator.imageUrl) } private fun onTransferring() { emitViewState { chatState.transferring() } chatManager.onChatAction(ChatManager.Action.Transferring) } fun overlayPermissionsDialogDismissed() { Logger.d(TAG, "overlayPermissionsDialogDismissed") dialogController.dismissCurrentDialog() emitViewState { chatState } } fun acceptUpgradeOfferClicked(offer: MediaUpgradeOffer) { Logger.d(TAG, "upgradeToAudioClicked") messagesNotSeenHandler.chatUpgradeOfferAccepted() acceptMediaUpgradeOfferUseCase(offer, Submitter.CHAT) dialogController.dismissCurrentDialog() } fun declineUpgradeOfferClicked(offer: MediaUpgradeOffer) { Logger.d(TAG, "closeUpgradeDialogClicked") mediaUpgradeOfferRepository.declineOffer(offer, Submitter.CHAT) dialogController.dismissCurrentDialog() } @Synchronized private fun setState(state: ChatState): Boolean { if (chatState == state) return false chatState = state return true } private fun error(error: Throwable?) { error?.also { error(it.toString()) } } private fun error(error: String) { Logger.e(TAG, error) dialogController.showUnexpectedErrorDialog() emitViewState { chatState.stop() } } private fun initMediaUpgradeCallback() { mediaUpgradeOfferRepositoryCallback = object : MediaUpgradeOfferRepositoryCallback { override fun newOffer(offer: MediaUpgradeOffer) { when { isChatViewPaused -> return offer.video == MediaDirection.NONE && offer.audio == MediaDirection.TWO_WAY -> { // audio call Logger.d(TAG, "audioUpgradeRequested") if (chatState.isOperatorOnline) { dialogController.showUpgradeAudioDialog(offer, chatState.formattedOperatorName) } } offer.video == MediaDirection.TWO_WAY -> { // video call Logger.d(TAG, "2 way videoUpgradeRequested") if (chatState.isOperatorOnline) { dialogController.showUpgradeVideoDialog2Way(offer, chatState.formattedOperatorName) } } offer.video == MediaDirection.ONE_WAY -> { Logger.d(TAG, "1 way videoUpgradeRequested") if (chatState.isOperatorOnline) { dialogController.showUpgradeVideoDialog1Way(offer, chatState.formattedOperatorName) } } } } override fun upgradeOfferChoiceSubmitSuccess( offer: MediaUpgradeOffer, submitter: Submitter ) { Logger.d(TAG, "upgradeOfferChoiceSubmitSuccess") if (submitter == Submitter.CHAT) { val requestedMediaType: String = if (offer.video != null && offer.video != MediaDirection.NONE) { GliaWidgets.MEDIA_TYPE_VIDEO } else { GliaWidgets.MEDIA_TYPE_AUDIO } emitViewState { chatState.setPendingNavigationType(requestedMediaType) } viewCallback?.apply { navigateToCall(requestedMediaType) Logger.d(TAG, "navigateToCall") } } } override fun upgradeOfferChoiceDeclinedSuccess( submitter: Submitter ) { Logger.d(TAG, "upgradeOfferChoiceDeclinedSuccess") } } } private fun viewInitQueueing() { Logger.d(TAG, "viewInitQueueing") chatManager.onChatAction(ChatManager.Action.QueuingStarted(chatState.companyName.orEmpty())) emitViewState { chatState.queueingStarted() } } private fun updateQueueing(items: MutableList<ChatItem>) { (chatState.operatorStatusItem as? OperatorStatusItem.InQueue)?.also { items.remove(it) items.add(OperatorStatusItem.InQueue(chatState.companyName)) } } private fun destroyView() { viewCallback?.apply { Logger.d(TAG, "destroyingView") destroyView() } } private fun minimizeView() { viewCallback?.minimizeView() } private fun operatorConnected(formattedOperatorName: String, profileImgUrl: String?) { chatManager.onChatAction( ChatManager.Action.OperatorConnected( chatState.companyName.orEmpty(), formattedOperatorName, profileImgUrl ) ) emitViewState { chatState.operatorConnected(formattedOperatorName, profileImgUrl).setLiveChatState() } } private fun operatorChanged(formattedOperatorName: String, profileImgUrl: String?) { chatManager.onChatAction( ChatManager.Action.OperatorJoined( chatState.companyName.orEmpty(), formattedOperatorName, profileImgUrl ) ) emitViewState { chatState.operatorConnected(formattedOperatorName, profileImgUrl) } } private fun stop() { chatManager.reset() Logger.d(TAG, "Stop, engagement ended") disposable.add( cancelQueueTicketUseCase.execute() .subscribe({ queueForEngagementStopped() }) { Logger.e(TAG, "cancelQueueTicketUseCase error: ${it.message}") } ) endEngagementUseCase() mediaUpgradeOfferRepository.stopAll() emitViewState { chatState.stop() } } private fun initGliaEngagementObserving() { getEngagementUseCase.execute(this) engagementEndUseCase.execute(this) } private fun addQuickReplyButtons(options: List<GvaButton>) { emitViewState { chatState.copy(gvaQuickReplies = options) } } private fun startTimer() { Logger.d(TAG, "startTimer") callTimer.startNew(Constants.CALL_TIMER_DELAY, Constants.CALL_TIMER_INTERVAL_VALUE) } private fun upgradeMediaItemToVideo() { Logger.d(TAG, "upgradeMediaItem") emitViewState { chatState.upgradeMedia(true) } chatManager.onChatAction(ChatManager.Action.OnMediaUpgradeToVideo) } private fun createNewTimerCallback() { timerStatusListener?.also { callTimer.removeFormattedValueListener(it) } timerStatusListener = object : FormattedTimerStatusListener { override fun onNewFormattedTimerValue(formatedValue: String) { if (chatState.isMediaUpgradeStarted) { chatManager.onChatAction( ChatManager.Action.OnMediaUpgradeTimerUpdated( formatedValue ) ) } } override fun onFormattedTimerCancelled() { if (chatState.isMediaUpgradeStarted) { emitViewState { chatState.upgradeMedia(null) } chatManager.onChatAction(ChatManager.Action.OnMediaUpgradeCanceled) } } } } fun singleChoiceOptionClicked( item: OperatorMessageItem.ResponseCard, selectedOption: SingleChoiceOption ) { Logger.d(TAG, "singleChoiceOptionClicked, id: ${item.id}") sendMessageUseCase.execute(selectedOption.asSingleChoiceResponse(), sendMessageCallback) chatManager.onChatAction(ChatManager.Action.ResponseCardClicked(item)) } fun sendCustomCardResponse(customCard: CustomCardChatItem, text: String, value: String) { val attachment = SingleChoiceAttachment.from(value, text) sendMessageUseCase.execute(attachment, sendMessageCallback) chatManager.onChatAction(ChatManager.Action.CustomCardClicked(customCard, attachment)) } private fun sendGvaResponse(singleChoiceAttachment: SingleChoiceAttachment) { addQuickReplyButtons(emptyList()) sendMessageUseCase.execute(singleChoiceAttachment, sendMessageCallback) } fun onRecyclerviewPositionChanged(isBottom: Boolean) { if (isBottom) { Logger.d(TAG, "onRecyclerviewPositionChanged, isBottom = true") emitViewState { chatState.isInBottomChanged(true).messagesNotSeenChanged(0) } } else { Logger.d(TAG, "onRecyclerviewPositionChanged, isBottom = false") emitViewState { chatState.isInBottomChanged(false) } } } fun newMessagesIndicatorClicked() { Logger.d(TAG, "newMessagesIndicatorClicked") viewCallback?.smoothScrollToBottom() } init { Logger.d(TAG, "constructor") // viewCallback is accessed from multiple threads // and must be protected from race condition synchronized(this) { viewCallback = chatViewCallback } chatState = ChatState() } override fun newEngagementLoaded(engagement: OmnicoreEngagement) { Logger.d(TAG, "newEngagementLoaded") onOperatorTypingUseCase.execute { onOperatorTyping(it) } addOperatorMediaStateListenerUseCase.execute(operatorMediaStateListener) mediaUpgradeOfferRepository.startListening() emitViewState { chatState.engagementStarted() } chatManager.reloadHistoryIfNeeded() } private fun initChatManager() { chatManager.initialize(::onHistoryLoaded, ::addQuickReplyButtons, ::updateUnSeenMessagesCount) .subscribe(::emitItems, ::error) .also(disposable::add) } private fun updateUnSeenMessagesCount(count: Int) { emitViewState { val notSeenCount = chatState.messagesNotSeen chatState.messagesNotSeenChanged(if (chatState.isChatInBottom) 0 else notSeenCount + count) } } private fun onHistoryLoaded(hasHistory: Boolean) { Logger.d(TAG, "historyLoaded") if (!hasHistory) { if (!chatState.engagementRequested && !isSecureEngagement) { queueForEngagement() } else { Logger.d(TAG, "Opened empty Secure Conversations chat") } } if (isSecureEngagement) { emitViewState { chatState.setSecureMessagingState() } } else { emitViewState { chatState.historyLoaded() } } prepareChatComponents() initGliaEngagementObserving() } private fun emitItems(items: List<ChatItem>) { viewCallback?.emitItems(items) } override fun engagementEnded() { Logger.d(TAG, "engagementEnded") stop() } override fun onSurveyLoaded(survey: Survey?) { Logger.d(TAG, "newSurveyLoaded") setPendingSurveyUsedUseCase.invoke() when { viewCallback != null && survey != null -> { // Show survey viewCallback!!.navigateToSurvey(survey) Dependencies.getControllerFactory().destroyControllers() } shouldHandleEndedEngagement && !isVisitorEndEngagement -> { // Show "Engagement ended" pop-up shouldHandleEndedEngagement = false dialogController.showEngagementEndedDialog() } else -> { // Close chat screen Dependencies.getControllerFactory().destroyControllers() destroyView() } } } private fun onNewOperatorMediaState(operatorMediaState: OperatorMediaState?) { Logger.d(TAG, "newOperatorMediaState: $operatorMediaState") if (chatState.isAudioCallStarted && operatorMediaState?.video != null) { upgradeMediaItemToVideo() } else if (!chatState.isMediaUpgradeStarted) { addMediaUpgradeItemToChatItems(operatorMediaState) if (!callTimer.isRunning) { startTimer() } } callNotificationUseCase(operatorMedia = operatorMediaState) } private fun addMediaUpgradeItemToChatItems(operatorMediaState: OperatorMediaState?) { val isVideo = when { operatorMediaState?.video == null && operatorMediaState?.audio != null -> false operatorMediaState?.video != null -> true else -> null } ?: return emitViewState { chatState.upgradeMedia(isVideo) } chatManager.onChatAction(ChatManager.Action.OnMediaUpgradeStarted(isVideo)) } fun notificationDialogDismissed() { dialogController.dismissCurrentDialog() } private fun queueForEngagementStarted() { Logger.d(TAG, "queueForEngagementStarted") if (chatState.isOperatorOnline) { return } observeQueueTicketState() viewInitQueueing() } private fun queueForEngagementStopped() { Logger.d(TAG, "queueForEngagementStopped") } private fun queueForEngagementError(exception: Throwable?) { (exception as? GliaException)?.also { Logger.e(TAG, it.toString()) when (it.cause) { GliaException.Cause.QUEUE_CLOSED, GliaException.Cause.QUEUE_FULL -> dialogController.showNoMoreOperatorsAvailableDialog() else -> dialogController.showUnexpectedErrorDialog() } emitViewState { chatState.stop() } } ?: (exception as? QueueingOngoingException)?.also { queueForEngagementStarted() } } fun onRemoveAttachment(attachment: FileAttachment) { removeFileAttachmentUseCase.execute(attachment) } fun onAttachmentReceived(file: FileAttachment) { addFileToAttachmentAndUploadUseCase.execute( file, object : AddFileToAttachmentAndUploadUseCase.Listener { override fun onFinished() { Logger.d(TAG, "fileUploadFinished") } override fun onStarted() { Logger.d(TAG, "fileUploadStarted") } override fun onError(ex: Exception) { Logger.e(TAG, "Upload file failed: " + ex.message) } override fun onSecurityCheckStarted() { Logger.d(TAG, "fileUploadSecurityCheckStarted") } override fun onSecurityCheckFinished(scanResult: EngagementFile.ScanResult?) { Logger.d(TAG, "fileUploadSecurityCheckFinished result=$scanResult") } } ) } fun onFileDownloadClicked(attachmentFile: AttachmentFile) { disposable.add( downloadFileUseCase(attachmentFile) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ fileDownloadSuccess(attachmentFile) }) { fileDownloadError(attachmentFile, it) } ) } private fun fileDownloadError(attachmentFile: AttachmentFile, error: Throwable) { viewCallback?.fileDownloadError(attachmentFile, error) } private fun fileDownloadSuccess(attachmentFile: AttachmentFile) { viewCallback?.fileDownloadSuccess(attachmentFile) } private fun updateAllowFileSendState() { siteInfoUseCase.execute { siteInfo: SiteInfo?, _ -> onSiteInfoReceived(siteInfo) } } private fun onSiteInfoReceived(siteInfo: SiteInfo?) { emitViewState { chatState.allowSendAttachmentStateChanged(siteInfo == null || siteInfo.allowedFileSenders.isVisitorAllowed) } } private fun observeQueueTicketState() { Logger.d(TAG, "observeQueueTicketState") disposable.add( ticketStateChangeToUnstaffedUseCase.execute() .subscribe({ dialogController.showNoMoreOperatorsAvailableDialog() }) { Logger.e(TAG, "Error happened while observing queue state : $it") } ) } fun isCallVisualizerOngoing(): Boolean { return isCallVisualizerUseCase() } fun onGvaButtonClicked(button: GvaButton) { when (val buttonType: Gva.ButtonType = determineGvaButtonTypeUseCase(button)) { Gva.ButtonType.BroadcastEvent -> viewCallback?.showBroadcastNotSupportedToast() is Gva.ButtonType.Email -> viewCallback?.requestOpenEmailClient(buttonType.uri) is Gva.ButtonType.Phone -> viewCallback?.requestOpenDialer(buttonType.uri) is Gva.ButtonType.PostBack -> sendGvaResponse(buttonType.singleChoiceAttachment) is Gva.ButtonType.Url -> viewCallback?.requestOpenUri(buttonType.uri) } } fun onMessageClicked(messageId: String) { chatManager.onChatAction(ChatManager.Action.MessageClicked(messageId)) } private fun scrollChatToBottom() { emitViewState { chatState.copy(isChatInBottom = true) } viewCallback?.smoothScrollToBottom() } }
6
Kotlin
1
5
ed3e21e234223ccf38e212f4f3e6efd5f7cf441c
40,517
android-sdk-widgets
MIT License
src/main/kotlin/com/amazon/opendistroforelasticsearch/indexmanagement/indexstatemanagement/resthandler/RestRemovePolicyAction.kt
changsongyang
367,441,169
true
{"Kotlin": 1908596, "Python": 1396}
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ /* * Copyright 2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.resthandler import com.amazon.opendistroforelasticsearch.indexmanagement.IndexManagementPlugin.Companion.ISM_BASE_URI import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.transport.action.removepolicy.RemovePolicyAction import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.transport.action.removepolicy.RemovePolicyRequest import org.opensearch.client.node.NodeClient import org.opensearch.common.Strings import org.opensearch.rest.BaseRestHandler import org.opensearch.rest.RestHandler.Route import org.opensearch.rest.RestRequest import org.opensearch.rest.RestRequest.Method.POST import org.opensearch.rest.action.RestToXContentListener import java.io.IOException class RestRemovePolicyAction : BaseRestHandler() { override fun routes(): List<Route> { return listOf( Route(POST, REMOVE_POLICY_BASE_URI), Route(POST, "$REMOVE_POLICY_BASE_URI/{index}") ) } override fun getName(): String = "remove_policy_action" @Suppress("SpreadOperator") // There is no way around dealing with java vararg without spread operator. @Throws(IOException::class) override fun prepareRequest(request: RestRequest, client: NodeClient): RestChannelConsumer { val indices: Array<String> = Strings.splitStringByCommaToArray(request.param("index")) if (indices.isNullOrEmpty()) { throw IllegalArgumentException("Missing indices") } val removePolicyRequest = RemovePolicyRequest(indices.toList()) return RestChannelConsumer { channel -> client.execute(RemovePolicyAction.INSTANCE, removePolicyRequest, RestToXContentListener(channel)) } } companion object { const val REMOVE_POLICY_BASE_URI = "$ISM_BASE_URI/remove" } }
0
null
0
0
062658a6862dfadac9247a8a27b4af2fb4773c58
2,788
opensearch-project-index-management
Apache License 2.0
app/src/main/java/com/shehuan/wanandroid/ui/chapter/chapterDetail/ChapterDetailPresenterImpl.kt
shehuan
153,994,354
false
null
package com.shehuan.wanandroid.ui.chapter.chapterDetail import com.shehuan.wanandroid.apis.WanAndroidApis import com.shehuan.wanandroid.base.BasePresenter import com.shehuan.wanandroid.base.net.RequestManager import com.shehuan.wanandroid.base.net.RetrofitManager import com.shehuan.wanandroid.base.net.exception.ResponseException import com.shehuan.wanandroid.base.net.observer.BaseObserver import com.shehuan.wanandroid.base.net.observer.LoadingObserver import com.shehuan.wanandroid.bean.chapter.ChapterArticleBean class ChapterDetailPresenterImpl(view: ChapterDetailContract.View) : BasePresenter<ChapterDetailContract.View>(view), ChapterDetailContract.Presenter { override fun uncollect(id: Int) { RequestManager.execute(this, RetrofitManager.create(WanAndroidApis::class.java).uncollectArticle(id), object : LoadingObserver<String>(context) { override fun onSuccess(data: String) { view.onUncollectSuccess(data) } override fun onError(e: ResponseException) { view.onUncollectError(e) } }) } override fun collect(id: Int) { RequestManager.execute(this, RetrofitManager.create(WanAndroidApis::class.java).collectArticle(id), object : LoadingObserver<String>(context) { override fun onSuccess(data: String) { view.onCollectSuccess(data) } override fun onError(e: ResponseException) { view.onCollectError(e) } }) } override fun getChapterArticleList(chapterId: Int, pageNum: Int) { RequestManager.execute(this, RetrofitManager.create(WanAndroidApis::class.java).chapterArticleList(chapterId, pageNum), object : BaseObserver<ChapterArticleBean>() { override fun onSuccess(data: ChapterArticleBean) { view.onChapterArticleListSuccess(data) } override fun onError(e: ResponseException) { view.onChapterArticleListError(e) } }) } override fun queryChapterArticle(chapterId: Int, pageNum: Int, k: String) { RequestManager.execute(this, RetrofitManager.create(WanAndroidApis::class.java).queryChapterArticle(chapterId, pageNum, k), object : BaseObserver<ChapterArticleBean>() { override fun onSuccess(data: ChapterArticleBean) { view.onQueryChapterArticleListSuccess(data) } override fun onError(e: ResponseException) { view.onQueryChapterArticleListError(e) } }) } }
1
Kotlin
10
39
6d8e12117dc0b5cdf3df98f28df2e7a8dd3e03fd
2,877
WanAndroid
Apache License 2.0
design/src/main/kotlin/com/kotlinground/design/creationalpatterns/factory/gui/App.kt
BrianLusina
113,182,832
false
null
package com.kotlinground.design.creationalpatterns.factory.gui import com.kotlinground.design.creationalpatterns.factory.gui.mac.MacFactory import com.kotlinground.design.creationalpatterns.factory.gui.win.WinFactory import java.util.* class App(val factory: GUIFactory) { private val button: Button = factory.createButton() private val checkbox: Checkbox = factory.createCheckBox() fun paintButton() { button.paint() } fun paintCheckbox() { button.paint() } } data class Config(val os: String) fun readAppConfig(): Config { val os = System.getProperty("os.name") return Config(os.lowercase(Locale.getDefault())) } fun main() { val config = readAppConfig() val factory = if (config.os.contains("windows")) { WinFactory() } else if (config.os.contains("mac")) { MacFactory() } else { throw Exception("Unknown OS ${config.os}") } val app = App(factory) app.paintButton() app.paintCheckbox() }
0
Kotlin
1
2
abf4ff467a7ffe8bdac4ac5a846c56a6e797be44
1,003
KotlinGround
MIT License
src/jsTest/kotlin/dev/rhovas/interpreter/Platform.kt
Rhovas
249,287,295
false
{"Kotlin": 754050}
package dev.rhovas.interpreter actual object Platform { actual val TARGET: Target = Target.JS actual fun readFile(path: String): String { val fs = js("require('fs')") return fs.readFileSync(path, "utf8") as String } }
8
Kotlin
2
28
bbd1bd129a7ee129944cf1d4f53a5151fb047568
250
Interpreter
MIT License
project-course/kotlin-tutorial/src/kiz/learn/loops/Main.kt
vel02
261,988,454
false
{"Text": 1, "Ignore List": 59, "Markdown": 1, "XML": 511, "Kotlin": 200, "Java": 8, "Gradle": 25, "Java Properties": 16, "Shell": 8, "Batchfile": 8, "Proguard": 8}
package kiz.learn.loops fun main(args: Array<String>) { // val vel = Player("Ariel") // vel.weapon = Weapon("Sword", 20) // println(vel) // val chestArmor = Loot("+3 Chest Armor", LootType.ARMOR, 80.00) // val redPotion = Loot("Red Potion", LootType.POTION, 7.50) // vel.inventory.add(redPotion) // vel.inventory.add(chestArmor) // vel.inventory.add(Loot("Ring of Protection +2", LootType.RING, 40.25)) // vel.inventory.add(Loot("Invisibility Potion", LootType.RING, 35.95)) // vel.showInventory() // // val louise = Player("louise", 5) // louise.weapon = vel.weapon // louise.show() // // val yen = Player("Yen", 4, 8) // yen.show() // // val ru = Player("Ru", 2, 5, 1000) // ru.show() // val axe = Weapon("Axe", 12) // ru.weapon = axe // axe.damageInflicted = 24 // ru.show() // // yen.weapon = Weapon("Sword", 10) // yen.show() // // yen.weapon = Weapon("Spear", 14) // yen.show() //loop i in 1 to 10 //loop i in 0 until 10 //loop i in 10 downTo 0 //loop i in 10 downTo 0 step 2 for (i in 10 downTo 0 step 2) { println("$i square is ${i * i}") } //challenge for (i in 3..100) { if ((i % 3 == 0) and (i % 5 == 0)) print("$i ") } //using step println() for (i in 3..100 step 3) { if (i % 5 == 0) print("$i ") } }
1
null
1
1
7644d1911ff35fda44e45b1486bcce5d790fe7c0
1,393
learn-kotlin-android
MIT License
src/main/kotlin/automaton/constructor/utils/StringUtils.kt
spbu-se
460,362,528
false
{"Kotlin": 450397, "CSS": 78}
package automaton.constructor.utils import java.util.* fun String.capitalize(locale: Locale = I18N.locale): String = replaceFirstChar { it.titlecase(locale) }
4
Kotlin
0
8
008858326d8b70316a95bded8c927d5a635b1f3b
165
KotlinAutomataConstructor
Apache License 2.0
app/src/androidTest/java/com/ccb/proandroiddevreader/screens/MainActivityScreen.kt
curlx
723,311,151
false
{"Kotlin": 51613}
package com.ccb.proandroiddevreader.screens import androidx.compose.ui.semantics.SemanticsNode import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.SemanticsNodeInteractionsProvider import com.ccb.proandroiddevreader.extensions.LazyListItemPosition import io.github.kakaocup.compose.node.element.ComposeScreen import io.github.kakaocup.compose.node.element.KNode import io.github.kakaocup.compose.node.element.lazylist.KLazyListItemNode import io.github.kakaocup.compose.node.element.lazylist.KLazyListNode class MainActivityScreen( semanticsProvider: SemanticsNodeInteractionsProvider, ) : ComposeScreen<MainActivityScreen>( semanticsProvider = semanticsProvider, viewBuilderAction = { hasTestTag("MainScreen") } ) { class NewsListItemNode( semanticsNode: SemanticsNode, semanticsProvider: SemanticsNodeInteractionsProvider, ) : KLazyListItemNode<NewsListItemNode>(semanticsNode, semanticsProvider) { val title: KNode = child { useUnmergedTree = true hasTestTag("title") } val information: KNode = child { useUnmergedTree = true hasTestTag("information") } } val newsList = KLazyListNode( semanticsProvider = semanticsProvider, viewBuilderAction = { hasTestTag("newsList") }, itemTypeBuilder = { itemType(::NewsListItemNode) }, positionMatcher = { position -> SemanticsMatcher.expectValue(LazyListItemPosition, position) } ) }
0
Kotlin
0
0
eeb75f7d92057a70ff4cad65f765ec7448196516
1,541
proandroiddev-reader
Apache License 2.0
bbootimg/src/main/kotlin/Signer.kt
scarlet-glass
172,427,678
false
{"Gradle": 5, "Markdown": 5, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "YAML": 1, "Java": 4, "INI": 3, "Python": 2, "Makefile": 2, "Diff": 1, "C": 6, "C++": 1, "Kotlin": 40, "Text": 1}
package cfig import avb.AVBInfo import avb.alg.Algorithms import com.fasterxml.jackson.databind.ObjectMapper import org.apache.commons.exec.CommandLine import org.apache.commons.exec.DefaultExecutor import org.slf4j.LoggerFactory import java.io.File class Signer { companion object { private val log = LoggerFactory.getLogger(Signer::class.java) private val workDir = UnifiedConfig.workDir fun sign(avbtool: String, bootSigner: String) { log.info("Loading config from ${workDir}bootimg.json") val readBack = UnifiedConfig.readBack() val args = readBack[0] as ImgArgs when (args.verifyType) { ImgArgs.VerifyType.VERIFY -> { log.info("Signing with verified-boot 1.0 style") val sig = readBack[2] as ImgInfo.VeritySignature DefaultExecutor().execute(CommandLine.parse("java -jar $bootSigner " + "${sig.path} ${args.output}.clear ${sig.verity_pk8} ${sig.verity_pem} ${args.output}.signed")) } ImgArgs.VerifyType.AVB -> { log.info("Adding hash_footer with verified-boot 2.0 style") val sig = readBack[2] as ImgInfo.AvbSignature val ai = ObjectMapper().readValue(File(Avb.getJsonFileName(args.output)), AVBInfo::class.java) //val alg = Algorithms.get(ai.header!!.algorithm_type.toInt()) //our signer File(args.output + ".clear").copyTo(File(args.output + ".signed")) Avb().add_hash_footer(args.output + ".signed", sig.imageSize!!.toLong(), false, false, salt = sig.salt, hash_algorithm = sig.hashAlgorithm!!, partition_name = sig.partName!!, rollback_index = ai.header!!.rollback_index, common_algorithm = sig.algorithm!!, inReleaseString = ai.header!!.release_string) //original signer File(args.output + ".clear").copyTo(File(args.output + ".signed2")) val signKey = Algorithms.get(sig.algorithm!!) var cmdlineStr = "$avbtool add_hash_footer " + "--image ${args.output}.signed2 " + "--partition_size ${sig.imageSize} " + "--salt ${sig.salt} " + "--partition_name ${sig.partName} " + "--hash_algorithm ${sig.hashAlgorithm} " + "--algorithm ${sig.algorithm} " if (signKey!!.defaultKey.isNotBlank()) { cmdlineStr += "--key ${signKey!!.defaultKey}" } log.warn(cmdlineStr) val cmdLine = CommandLine.parse(cmdlineStr) cmdLine.addArgument("--internal_release_string") cmdLine.addArgument(ai.header!!.release_string, false) DefaultExecutor().execute(cmdLine) verifyAVBIntegrity(args, avbtool) } } } private fun verifyAVBIntegrity(args: ImgArgs, avbtool: String) { val tgt = args.output + ".signed" log.info("Verifying AVB: $tgt") DefaultExecutor().execute(CommandLine.parse("$avbtool verify_image --image $tgt")) log.info("Verifying image passed: $tgt") } fun mapToJson(m: LinkedHashMap<*, *>): String { val sb = StringBuilder() m.forEach { k, v -> if (sb.isNotEmpty()) sb.append(", ") sb.append("\"$k\": \"$v\"") } return "{ $sb }" } } }
1
null
1
1
482ab1f998a449f3d3cc1b71f8a52497ef6e742d
3,970
Android_boot_image_editor
Apache License 2.0
src/main/kotlin/org/radarbase/push/integration/garmin/util/RedisRemoteLockManager.kt
RADAR-base
307,485,421
false
null
package org.radarbase.output.accounting import org.slf4j.LoggerFactory import redis.clients.jedis.params.SetParams import java.util.* import kotlin.time.Duration.Companion.days class RedisRemoteLockManager( private val redisHolder: RedisHolder, private val keyPrefix: String, ) : RemoteLockManager { private val uuid: String = UUID.randomUUID().toString() init { logger.info("Managing locks as ID {}", uuid) } override suspend fun acquireLock(name: String): RemoteLockManager.RemoteLock? { val lockKey = "$keyPrefix/$name.lock" return redisHolder.execute { redis -> redis.set(lockKey, uuid, setParams)?.let { RemoteLock(lockKey) } } } private inner class RemoteLock( private val lockKey: String, ) : RemoteLockManager.RemoteLock { override suspend fun closeAndJoin() { redisHolder.execute { redis -> if (redis.get(lockKey) == uuid) { redis.del(lockKey) } } } } companion object { private val logger = LoggerFactory.getLogger(RedisRemoteLockManager::class.java) private val setParams = SetParams() .nx() // only set if not already set .px(1.days.inWholeMilliseconds) // limit the duration of a lock to 24 hours } }
9
null
2
2
1745929ccb91041bb03def684f95c60db5355b60
1,380
RADAR-PushEndpoint
Apache License 2.0
kotlin-react-core/src/main/kotlin/react/PropsWithRef.kt
JetBrains
93,250,841
false
null
package react external interface PropsWithRef<T : Any> : Props { var ref: Ref<T>? }
12
Kotlin
145
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
89
kotlin-wrappers
Apache License 2.0
streams-consumer/src/main/kotlin/no/nav/dagpenger/saksbehandling/streams/kafka/Serder.kt
navikt
571,475,339
false
{"Kotlin": 361937, "PLpgSQL": 7983, "Mustache": 4238, "HTML": 699, "Dockerfile": 77}
package no.nav.dagpenger.saksbehandling.streams.kafka import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde import org.apache.avro.specific.SpecificRecord import org.apache.kafka.common.serialization.Serde import org.apache.kafka.common.serialization.Serdes val stringSerde: Serde<String> = Serdes.String() fun <T : SpecificRecord> specificAvroSerde(): Serde<T> = SpecificAvroSerde<T>().apply { configure(KafkaConfiguration.kafkaSchemaRegistryConfiguration(), false) }
1
Kotlin
0
0
4ed26ab80727164289d64b81ee5ce1205acc3fd3
498
dp-saksbehandling
MIT License
src/main/kotlin/org/emgen/Expression.kt
emilancius
234,365,097
false
null
package org.emgen import java.math.BigDecimal import java.util.* data class Expression(val tokens: List<Token>) { fun evaluate(): BigDecimal { val stack = Stack<Operand>() tokens.forEach { if (it !is Operator) { stack.push(it as Operand) } else { val inputY = stack.pop() if (it.unary) { stack.push(it.evaluate(inputY)) } else { val inputX = stack.pop() stack.push(it.evaluate(inputX, inputY)) } } } return if (stack.empty()) BigDecimal.ZERO else stack.pop().value } }
1
Kotlin
2
0
f73f335268f6cc41f6ccb18c69036081514c3aa5
690
sono-core
MIT License