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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dexfile/src/main/kotlin/com/github/netomi/bat/dexfile/DexAccessFlags.kt
|
netomi
| 265,488,804
| false
| null |
/*
* Copyright (c) 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law, agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES, CONDITIONS OF ANY KIND, either express, implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.netomi.bat.dexfile
import com.github.netomi.bat.dexfile.DexAccessFlagTarget.*
import java.util.*
import kotlin.Array
import kotlin.Int
import kotlin.String
import kotlin.arrayOf
fun formatAccessFlagsAsHumanReadable(accessFlags: Int, target: DexAccessFlagTarget): String {
return DexAccessFlag.values().filter { it.target and target.value != 0 && it.value and accessFlags != 0 }
.joinToString(separator = " ") { it.name }
}
enum class DexAccessFlagTarget(val value: Int) {
CLASS (0x01),
FIELD (0x02),
METHOD(0x04)
}
enum class DexAccessFlag(val value: Int, val target: Int) {
PUBLIC(ACC_PUBLIC, arrayOf(CLASS, FIELD, METHOD)),
PRIVATE(ACC_PRIVATE, arrayOf(CLASS, FIELD, METHOD)),
PROTECTED(ACC_PROTECTED, arrayOf(CLASS, FIELD, METHOD)),
STATIC(ACC_STATIC, arrayOf(CLASS, FIELD, METHOD)),
FINAL(ACC_FINAL, arrayOf(CLASS, FIELD, METHOD)),
SYNCHRONIZED(ACC_SYNCHRONIZED, arrayOf(METHOD)),
VOLATILE(ACC_VOLATILE, arrayOf(FIELD)),
BRIDGE(ACC_BRIDGE, arrayOf(METHOD)),
TRANSIENT(ACC_TRANSIENT, arrayOf(FIELD)),
VARARGS(ACC_VARARGS, arrayOf(METHOD)),
NATIVE(ACC_NATIVE, arrayOf(METHOD)),
INTERFACE(ACC_INTERFACE, arrayOf(CLASS)),
ABSTRACT(ACC_ABSTRACT, arrayOf(CLASS, METHOD)),
STRICTFP(ACC_STRICT, arrayOf(METHOD)),
SYNTHETIC(ACC_SYNTHETIC, arrayOf(CLASS, FIELD, METHOD)),
ANNOTATION(ACC_ANNOTATION, arrayOf(CLASS)),
ENUM(ACC_ENUM, arrayOf(CLASS, FIELD)),
CONSTRUCTOR(ACC_CONSTRUCTOR, arrayOf(METHOD)),
DECLARED_SYNCHRONIZED(ACC_DECLARED_SYNCHRONIZED, arrayOf(METHOD));
constructor(value: Int, targets: Array<DexAccessFlagTarget>): this(value, targets.fold(0) { acc, t -> acc or t.value })
companion object {
fun of(input: String): DexAccessFlag {
val cleanedInput = input.replace("-".toRegex(), "_").uppercase(Locale.getDefault())
return valueOf(cleanedInput)
}
fun flagsByTarget(target: DexAccessFlagTarget): Collection<DexAccessFlag> {
return values().filter { it.target and target.value != 0 }
}
}
}
| 1
| null |
3
| 10
|
5f5ec931c47dd34f14bd97230a29413ef1cf219c
| 3,204
|
bat
|
Apache License 2.0
|
app/src/main/java/com/jamieadkins/nytimesdemo/ApiManager.kt
|
jamieadkins95
| 117,567,464
| false
| null |
package com.jamieadkins.nytimesdemo
import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.moczul.ok2curl.CurlInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
object ApiManager {
private var apiInstance: PulseliveApi? = null
private var gson: Gson? = null
fun getPulseliveApi(): PulseliveApi {
if (apiInstance == null) {
val service = Retrofit.Builder()
.baseUrl("http://dynamic.pulselive.com/test/native/")
.addConverterFactory(BufferedSourceConverterFactory())
.addConverterFactory(GsonConverterFactory.create(getGson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(getOkHttpClientBuilder().build())
.build()
apiInstance = service.create(PulseliveApi::class.java)
}
return apiInstance as PulseliveApi
}
fun getGson(): Gson {
if (gson == null) {
gson = GsonBuilder()
.create()
}
return gson as Gson
}
private fun getOkHttpClientBuilder(vararg interceptors: Interceptor): OkHttpClient.Builder {
val builder = OkHttpClient.Builder()
builder.connectTimeout(15, TimeUnit.SECONDS)
builder.readTimeout(15, TimeUnit.SECONDS)
//Add interceptors first, so that they will be included on the curl request output (debug)
for (i in interceptors) {
builder.addInterceptor(i)
}
//Log curl requests when in debug mode
if (BuildConfig.DEBUG) {
builder.addInterceptor(CurlInterceptor { message -> Log.d("Ok2Curl", message) })
}
return builder
}
}
| 0
|
Kotlin
|
0
| 0
|
b3b167ad5a30a053a984ffe91ddb84f085358a84
| 1,959
|
nytimes-demo
|
MIT License
|
src/main/kotlin/pro/gramcode/box2d/dsl/FixtureDsl.kt
|
Jkly
| 68,972,789
| false
| null |
package pro.gramcode.box2d.dsl
import com.badlogic.gdx.physics.box2d.Filter
import com.badlogic.gdx.physics.box2d.FixtureDef
@Box2dDslMarker
abstract class FixtureDsl(private val fixtureDef: FixtureDef) {
fun filter(configureFilter: Filter.() -> Unit = {}) {
configureFilter(fixtureDef.filter)
}
var friction: Float
get() = fixtureDef.friction
set(friction) {
fixtureDef.friction = friction
}
var restitution: Float
get() = fixtureDef.restitution
set(restitution) {
fixtureDef.restitution = restitution
}
var density: Float
get() = fixtureDef.density
set(density) {
fixtureDef.density = density
}
var isSensor: Boolean
get() = fixtureDef.isSensor
set(isSensor) {
fixtureDef.isSensor = isSensor
}
fun friction(friction:Float) {
fixtureDef.friction = friction
}
fun restitution(restitution: Float) {
fixtureDef.restitution = restitution
}
fun density(density: Float) {
fixtureDef.density = density
}
fun isSensor(isSensor: Boolean) {
fixtureDef.isSensor = isSensor
}
}
| 0
|
Kotlin
|
0
| 3
|
cd4f37a81b063008a36ed59e9188f7f0d8e087bf
| 1,216
|
gdx-box2d-kotlin
|
Apache License 2.0
|
app/src/main/java/com/piashcse/hilt_mvvm_compose_movie/ui/screens/moviedetail/MovieDetailViewModel.kt
|
piashcse
| 415,384,781
| false
|
{"Kotlin": 118247}
|
package com.piashcse.hilt_mvvm_compose_movie.ui.screens.moviedetail
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.piashcse.hilt_mvvm_compose_movie.data.model.BaseModel
import com.piashcse.hilt_mvvm_compose_movie.data.model.artist.Artist
import com.piashcse.hilt_mvvm_compose_movie.data.model.moviedetail.MovieDetail
import com.piashcse.hilt_mvvm_compose_movie.data.repository.MovieRepository
import com.piashcse.hilt_mvvm_compose_movie.utils.network.DataState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MovieDetailViewModel @Inject constructor(private val repo: MovieRepository) : ViewModel() {
val movieDetail: MutableState<DataState<MovieDetail>?> = mutableStateOf(null)
val recommendedMovie: MutableState<DataState<BaseModel>?> = mutableStateOf(null)
val artist: MutableState<DataState<Artist>?> = mutableStateOf(null)
fun movieDetailApi(movieId: Int) {
viewModelScope.launch {
repo.movieDetail(movieId).onEach {
movieDetail.value = it
}.launchIn(viewModelScope)
}
}
fun recommendedMovieApi(movieId: Int, page: Int) {
viewModelScope.launch {
repo.recommendedMovie(movieId, page).onEach {
recommendedMovie.value = it
}.launchIn(viewModelScope)
}
}
fun movieCredit(movieId: Int) {
viewModelScope.launch {
repo.movieCredit(movieId).onEach {
artist.value = it
}.launchIn(viewModelScope)
}
}
}
| 1
|
Kotlin
|
19
| 97
|
98c5621eb0077530f84437a947fc285b14115529
| 1,757
|
Hilt-MVVM-Compose-Movie
|
Apache License 2.0
|
sdk/src/main/java/io/wso2/android/api_authenticator/sdk/models/state/AuthenticationState.kt
|
Achintha444
| 731,559,375
| false
|
{"Kotlin": 253341, "Java": 1580}
|
package io.wso2.android.api_authenticator.sdk.models.state
import io.wso2.android.api_authenticator.sdk.models.authentication_flow.AuthenticationFlow
/**
* Authentication state of the application
* This sealed class is used to represent the different states of the authentication process
*
* States:
* - [Initial]: The initial state of the application
* - [Unauthenticated]: The user is not authenticated to access the application
* - [Authenticated]: The user is authenticated to access the application
* - [Loading]: The application is in the process of loading the authentication state
* - [Error]: An error occurred during the authentication process
*/
sealed class AuthenticationState {
object Initial : AuthenticationState()
data class Unauthenticated(val authenticationFlow: AuthenticationFlow?) : AuthenticationState()
object Authenticated : AuthenticationState()
object Loading : AuthenticationState()
data class Error(val throwable: Throwable) : AuthenticationState()
}
| 0
|
Kotlin
|
0
| 0
|
a4928ccd62e8ca1807e218d78c0270df65d96a5c
| 1,012
|
wso2-android-api-authenticator-sdk
|
Apache License 2.0
|
aws/sdk-codegen/src/test/kotlin/software/amazon/smithy/rustsdk/RegionDecoratorTest.kt
|
smithy-lang
| 308,027,791
| false
|
{"Rust": 4428309, "Kotlin": 3842117, "Smithy": 151231, "Python": 62946, "Shell": 49728, "TypeScript": 30713, "Dockerfile": 9790, "JavaScript": 5975, "Harbour": 5848, "Makefile": 5633, "CSS": 982, "RenderScript": 116}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rustsdk
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import software.amazon.smithy.rust.codegen.core.testutil.asSmithyModel
import kotlin.io.path.readText
class RegionDecoratorTest {
private val modelWithoutRegionParamOrSigV4AuthScheme =
"""
namespace test
use aws.api#service
use aws.protocols#awsJson1_0
use smithy.rules#endpointRuleSet
@awsJson1_0
@endpointRuleSet({
"version": "1.0",
"rules": [{ "type": "endpoint", "conditions": [], "endpoint": { "url": "https://example.com" } }],
"parameters": {}
})
@service(sdkId: "dontcare")
service TestService { version: "2023-01-01", operations: [SomeOperation] }
structure SomeOutput { something: String }
operation SomeOperation { output: SomeOutput }
""".asSmithyModel()
private val modelWithRegionParam =
"""
namespace test
use aws.api#service
use aws.protocols#awsJson1_0
use smithy.rules#endpointRuleSet
@awsJson1_0
@endpointRuleSet({
"version": "1.0",
"rules": [{ "type": "endpoint", "conditions": [], "endpoint": { "url": "https://example.com" } }],
"parameters": {
"Region": { "required": false, "type": "String", "builtIn": "AWS::Region" },
}
})
@service(sdkId: "dontcare")
service TestService { version: "2023-01-01", operations: [SomeOperation] }
structure SomeOutput { something: String }
operation SomeOperation { output: SomeOutput }
""".asSmithyModel()
private val modelWithSigV4AuthScheme =
"""
namespace test
use aws.auth#sigv4
use aws.api#service
use aws.protocols#awsJson1_0
use smithy.rules#endpointRuleSet
@auth([sigv4])
@sigv4(name: "dontcare")
@awsJson1_0
@endpointRuleSet({
"version": "1.0",
"rules": [{ "type": "endpoint", "conditions": [], "endpoint": { "url": "https://example.com" } }],
"parameters": {}
})
@service(sdkId: "dontcare")
service TestService { version: "2023-01-01", operations: [SomeOperation] }
structure SomeOutput { something: String }
operation SomeOperation { output: SomeOutput }
""".asSmithyModel()
@Test
fun `models without region built-in params or SigV4 should not have configurable regions`() {
val path =
awsSdkIntegrationTest(modelWithoutRegionParamOrSigV4AuthScheme) { _, _ ->
// it should generate and compile successfully
}
val configContents = path.resolve("src/config.rs").readText()
assertFalse(configContents.contains("fn set_region("))
}
@Test
fun `models with region built-in params should have configurable regions`() {
val path =
awsSdkIntegrationTest(modelWithRegionParam) { _, _ ->
// it should generate and compile successfully
}
val configContents = path.resolve("src/config.rs").readText()
assertTrue(configContents.contains("fn set_region("))
}
@Test
fun `models with SigV4 should have configurable regions`() {
val path =
awsSdkIntegrationTest(modelWithSigV4AuthScheme) { _, _ ->
// it should generate and compile successfully
}
val configContents = path.resolve("src/config.rs").readText()
assertTrue(configContents.contains("fn set_region("))
}
}
| 300
|
Rust
|
188
| 504
|
8d8e7ab7aa6c3b388ffb2365a29ab03f87c24507
| 3,833
|
smithy-rs
|
Apache License 2.0
|
CommonClient/src/commonMain/kotlin/by/cedon/skabs/multiplatform/model/network/ServerApi.kt
|
AinisSK
| 178,153,323
| false
|
{"C++": 1163504, "C": 1162274, "Objective-C": 750696, "Kotlin": 31845, "Swift": 3001, "Ruby": 768, "Shell": 108}
|
package by.cedon.skabs.multiplatform.model.network
import by.cedon.skabs.multiplatform.Api
import by.cedon.skabs.multiplatform.model.log.PlatformLogger
import io.ktor.client.HttpClient
import io.ktor.client.call.call
import io.ktor.client.features.UserAgent
import io.ktor.client.features.logging.LogLevel
import io.ktor.client.features.logging.Logger
import io.ktor.client.features.logging.Logging
import io.ktor.client.features.logging.SIMPLE
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.takeFrom
import kotlinx.io.core.use
class ServerApi(private val logger: PlatformLogger) {
// val endPoint = "https://cedon-prod.vapor.cloud"
val endPoint = "10.50.34.142:3000"
private val client = HttpClient {
expectSuccess = false
install(ExpectSuccess)
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.ALL
}
install(UserAgent) {
agent = "kotlinlibs"
}
}
suspend fun doJob(): Boolean {
val allApi = Api()
allApi.doCalc("jnjn")
logger.log("[COMMON]", "Send request to server to proceed")
client.call {
method = HttpMethod.Get
url {
takeFrom(endPoint)
}
}.response.use {
return it.status.value == HttpStatusCode.OK.value
}
}
}
| 0
|
C++
|
0
| 0
|
5c778c9607b25f6429d8f9340473be47710b4ef4
| 1,402
|
KotlinNative-Multiplatrofm
|
Apache License 2.0
|
app/src/main/java/com/mainstreetcode/teammate/fragments/main/StatRankFragment.kt
|
femzydoo
| 207,017,344
| true
|
{"Kotlin": 1468678, "Java": 67891}
|
/*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mainstreetcode.teammate.fragments.main
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.DiffUtil
import com.mainstreetcode.teammate.R
import com.mainstreetcode.teammate.adapters.StatRankAdapter
import com.mainstreetcode.teammate.adapters.viewholders.EmptyViewHolder
import com.mainstreetcode.teammate.baseclasses.MainActivityFragment
import com.mainstreetcode.teammate.model.Tournament
import com.mainstreetcode.teammate.model.enums.StatType
import com.mainstreetcode.teammate.util.ScrollManager
import com.mainstreetcode.teammate.util.simpleAdapterListener
import com.tunjid.androidbootstrap.recyclerview.InteractiveViewHolder
import com.tunjid.androidbootstrap.recyclerview.diff.Differentiable
class StatRankFragment : MainActivityFragment() {
private lateinit var type: StatType
private lateinit var tournament: Tournament
private lateinit var statRanks: List<Differentiable>
override val showsFab: Boolean get() = false
override fun getStableTag(): String {
val superResult = super.getStableTag()
val tempTournament = arguments!!.getParcelable<Tournament>(ARG_TOURNAMENT)
return if (tempTournament != null) superResult + "-" + tempTournament.hashCode()
else superResult
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tournament = arguments!!.getParcelable(ARG_TOURNAMENT)!!
statRanks = tournamentViewModel.getStatRanks(tournament)
type = StatType.empty().apply { update(tournament.sport.statTypeFromCode("")) }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_stat_rank, container, false)
val spinner = root.findViewById<Spinner>(R.id.spinner)
scrollManager = ScrollManager.with<InteractiveViewHolder<*>>(root.findViewById(R.id.list_layout))
.withPlaceholder(EmptyViewHolder(root, R.drawable.ic_medal_24dp, R.string.no_stat_ranks))
.withInconsistencyHandler(this::onInconsistencyDetected)
.withAdapter(StatRankAdapter(
statRanks,
simpleAdapterListener { statRank -> showFragment(UserEditFragment.newInstance(statRank.user)) }))
.withLinearLayoutManager()
.build()
scrollManager.setViewHolderColor(R.attr.alt_empty_view_holder_tint)
val statTypes = tournament.sport.stats.toTypedArray()
val adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, statTypes)
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
type.update(statTypes[position])
fetchStandings()
}
override fun onNothingSelected(parent: AdapterView<*>) = Unit
}
return root
}
override fun onResume() {
super.onResume()
fetchStandings()
}
override fun togglePersistentUi() = Unit /* Do nothing */
private fun fetchStandings() {
toggleProgress(true)
disposables.add(tournamentViewModel.getStatRank(tournament, type).subscribe(this::onTournamentsUpdated, defaultErrorHandler::invoke))
}
private fun onTournamentsUpdated(diff: DiffUtil.DiffResult) {
scrollManager.onDiff(diff)
toggleProgress(false)
}
companion object {
private const val ARG_TOURNAMENT = "tournament"
fun newInstance(tournament: Tournament): StatRankFragment = StatRankFragment().apply { arguments = bundleOf(ARG_TOURNAMENT to tournament) }
}
}
| 0
| null |
0
| 0
|
1f4255741aa65f64f67dbca446f1731ffe4db85f
| 5,176
|
teammate-android
|
MIT License
|
legacy-token-migration-sample/src/main/java/sample/okta/android/legacy/browser/BrowserViewModel.kt
|
okta
| 445,628,677
| false
|
{"Kotlin": 737721, "Shell": 884}
|
/*
* Copyright 2021-Present Okta, Inc.
*
* 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 sample.okta.android.legacy.browser
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.okta.authfoundation.client.OidcClientResult
import com.okta.authfoundationbootstrap.CredentialBootstrap
import com.okta.webauthenticationui.WebAuthenticationClient.Companion.createWebAuthenticationClient
import kotlinx.coroutines.launch
import sample.okta.android.legacy.BuildConfig
import timber.log.Timber
class BrowserViewModel : ViewModel() {
private val _state = MutableLiveData<BrowserState>(BrowserState.Idle)
val state: LiveData<BrowserState> = _state
fun login(context: Context) {
viewModelScope.launch {
_state.value = BrowserState.Loading
val webAuthenticationClient = CredentialBootstrap.oidcClient.createWebAuthenticationClient()
when (val result = webAuthenticationClient.login(context, BuildConfig.SIGN_IN_REDIRECT_URI)) {
is OidcClientResult.Error -> {
Timber.e(result.exception, "Failed to login.")
_state.value = BrowserState.Error("Failed to login.")
}
is OidcClientResult.Success -> {
CredentialBootstrap.defaultCredential().storeToken(token = result.result)
_state.value = BrowserState.Token
}
}
}
}
}
sealed class BrowserState {
object Idle : BrowserState()
object Loading : BrowserState()
data class Error(val message: String) : BrowserState()
object Token : BrowserState()
}
| 14
|
Kotlin
|
11
| 26
|
e3261c5826ad907d173bdadb34db36111fad4c77
| 2,285
|
okta-mobile-kotlin
|
Apache License 2.0
|
app/src/main/java/kittoku/mvc/unit/arp/ARPPacket.kt
|
kittoku
| 401,675,193
| false
| null |
package kittoku.mvc.unit.arp
import kittoku.mvc.debug.assertAlways
import kittoku.mvc.unit.DataUnit
import kittoku.mvc.unit.ethernet.ETHER_TYPE_IPv4
import java.nio.ByteBuffer
internal class ARPPacket : DataUnit {
internal var opcode: Short = 0
internal val senderMac = ByteArray(6)
internal val senderIp = ByteArray(4)
internal val targetMac = ByteArray(6)
internal val targetIp = ByteArray(4)
override val length = 28
override fun write(buffer: ByteBuffer) {
buffer.putShort(ARP_HARDWARE_TYPE_ETHERNET)
buffer.putShort(ETHER_TYPE_IPv4)
buffer.put(ARP_MAC_ADDRESS_SIZE)
buffer.put(ARP_IP_ADDRESS_SIZE)
buffer.putShort(opcode)
buffer.put(senderMac)
buffer.put(senderIp)
buffer.put(targetMac)
buffer.put(targetIp)
}
override fun read(buffer: ByteBuffer) {
assertAlways(buffer.short == ARP_HARDWARE_TYPE_ETHERNET)
assertAlways(buffer.short == ETHER_TYPE_IPv4)
assertAlways(buffer.get() == ARP_MAC_ADDRESS_SIZE)
assertAlways(buffer.get() == ARP_IP_ADDRESS_SIZE)
opcode = buffer.short
buffer.get(senderMac)
buffer.get(senderIp)
buffer.get(targetMac)
buffer.get(targetIp)
}
}
| 5
|
Kotlin
|
11
| 33
|
9f8be9802629684d0eb68fedb9f859e9df7339e2
| 1,265
|
Minimum-VPN-Client-for-SoftEther-VPN
|
Apache License 2.0
|
app/src/main/java/com/nuevo/gameness/ui/pages/personal/profile/settings/teaminvitations/TeamInvitationsViewModel.kt
|
arbabkh
| 873,814,880
| false
|
{"Kotlin": 538078}
|
package com.nuevo.gameness.ui.pages.personal.profile.settings.teaminvitations
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.nuevo.gameness.data.model.teamusers.TeamInviteDecisionRequest
import com.nuevo.gameness.data.repository.Repository
import com.nuevo.gameness.data.result.StateLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class TeamInvitationsViewModel @Inject constructor(
application: Application,
private val repository: Repository
) : AndroidViewModel(application) {
var teamInviteDecisionRequest:TeamInviteDecisionRequest? = null
val getTeamInviteList = StateLiveData(viewModelScope) {
repository.getTeamInviteList()
}
val acceptTeamInvitation = StateLiveData(viewModelScope) {
repository.sendTeamInvitationDecision(teamInviteDecisionRequest)
}
val rejectTeamInvitation = StateLiveData(viewModelScope) {
repository.sendTeamInvitationDecision(teamInviteDecisionRequest)
}
}
| 0
|
Kotlin
|
0
| 0
|
80d7b04385a2cd516b8157dbea19dd821c30fcc9
| 1,089
|
gameness-android
|
MIT License
|
app/src/main/java/cn/bluemobi/dylan/step/activity/MainActivity.kt
|
xrn1997
| 377,336,800
| true
|
{"Kotlin": 68068}
|
package cn.bluemobi.dylan.step.activity
import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import cn.bluemobi.dylan.step.R
import cn.bluemobi.dylan.step.step.UpdateUiCallBack
import cn.bluemobi.dylan.step.step.service.StepService
import cn.bluemobi.dylan.step.step.util.SharedPreferencesUtil
import cn.bluemobi.dylan.step.view.StepArcView
import com.permissionx.guolindev.PermissionX
/**
* 记步主页
*/
class MainActivity : AppCompatActivity(), View.OnClickListener {
private var tvData: TextView? = null
private var cc: StepArcView? = null
private var tvSet: TextView? = null
private var tvIsSupport: TextView? = null
private var sp: SharedPreferencesUtil? = null
private fun assignViews() {
tvData = findViewById(R.id.tv_data)
cc = findViewById(R.id.cc)
tvSet = findViewById(R.id.tv_set)
tvIsSupport = findViewById(R.id.tv_isSupport)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
assignViews()
initData()
addListener()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
permissionX()
}
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun permissionX() {
PermissionX
.init(this)
.permissions(allNeedPermissions())
.onExplainRequestReason { scope, deniedList ->
scope.showRequestReasonDialog(
deniedList,
"即将重新申请的权限是程序必须依赖的权限(请选择始终)",
"我已明白",
"取消"
)
}
.onForwardToSettings { scope, deniedList ->
scope.showForwardToSettingsDialog(
deniedList,
"您需要去应用程序设置当中手动开启权限",
"我已明白",
"取消"
)
}
.request { allGranted, _, _ ->
if (allGranted) {
Toast.makeText(this, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show()
} else {
finish()
}
}
}
/**
* 所有需要的权限
*/
@RequiresApi(Build.VERSION_CODES.Q)
private fun allNeedPermissions(): List<String> {
val permissions: MutableList<String> = ArrayList()
permissions.apply {
add(Manifest.permission.ACTIVITY_RECOGNITION)
}
return permissions
}
private fun addListener() {
tvSet!!.setOnClickListener(this)
tvData!!.setOnClickListener(this)
}
private fun initData() {
sp = SharedPreferencesUtil(this)
//获取用户设置的计划锻炼步数,没有设置过的话默认7000
val planWalkQTY = sp!!.getParam("planWalk_QTY", "7000") as String?
//设置当前步数为0
cc!!.setCurrentCount(planWalkQTY!!.toInt(), 0)
tvIsSupport!!.text = "计步中..."
setupService()
}
private var isBind = false
/**
* 开启计步服务
*/
private fun setupService() {
val intent = Intent(this, StepService::class.java)
isBind = bindService(intent, conn, BIND_AUTO_CREATE)
startService(intent)
}
/**
* 用于查询应用服务(application Service)的状态的一种interface,
* 更详细的信息可以参考Service 和 context.bindService()中的描述,
* 和许多来自系统的回调方式一样,ServiceConnection的方法都是进程的主线程中调用的。
*/
private var conn: ServiceConnection = object : ServiceConnection {
/**
* 在建立起于Service的连接时会调用该方法,目前Android是通过IBind机制实现与服务的连接。
* @param name 实际所连接到的Service组件名称
* @param service 服务的通信信道的IBind,可以通过Service访问对应服务
*/
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val stepService = (service as StepService.StepBinder).service
//设置初始化数据
val planWalkQTY = sp!!.getParam("planWalk_QTY", "7000") as String?
cc!!.setCurrentCount(planWalkQTY!!.toInt(), stepService.stepCount)
//设置步数监听回调
stepService.registerCallback(object : UpdateUiCallBack {
override fun updateUi(stepCount: Int) {
val temp = sp!!.getParam("planWalk_QTY", "7000") as String?
cc!!.setCurrentCount(temp!!.toInt(), stepCount)
}
})
}
/**
* 当与Service之间的连接丢失的时候会调用该方法,
* 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用,
* 此方法不会移除与Service的连接,当服务重新启动的时候仍然会调用 onServiceConnected()。
* @param name 丢失连接的组件名称
*/
override fun onServiceDisconnected(name: ComponentName) {}
}
override fun onClick(v: View) {
when (v.id) {
R.id.tv_set -> startActivity(Intent(this, SetPlanActivity::class.java))
R.id.tv_data -> startActivity(Intent(this, HistoryActivity::class.java))
}
}
public override fun onDestroy() {
super.onDestroy()
if (isBind) {
unbindService(conn)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
085f18f6d077a1d9fb55d00864e644a0f0cb6a5e
| 5,285
|
dylan-step-count
|
Do What The F*ck You Want To Public License
|
app/src/main/java/com/github/nothing2512/anticorona/ui/country/CountryLoading.kt
|
nothing2512
| 251,372,631
| false
| null |
/*
* Copyright 2020 Nothing
*
* 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.github.nothing2512.anticorona.ui.country
import com.github.nothing2512.anticorona.databinding.ActivityCountryBinding
import com.github.nothing2512.anticorona.parent.ParentLoading
/**
* [CountryLoading] class
* @author <NAME>
* @constructor [binding]
* @see ParentLoading
*/
class CountryLoading(private val binding: ActivityCountryBinding) : ParentLoading() {
/**
* start loading
* @see ParentLoading.start
*/
fun start() {
binding.apply { start(sfCountry, rvCountry) }
}
/**
* stop loading
* @see ParentLoading.stop
*/
fun stop() {
binding.apply { stop(sfCountry, rvCountry) }
}
}
| 0
|
Kotlin
|
0
| 1
|
8da04a8dd852c01673b75783e7e9047af5e2bcc2
| 1,264
|
AntiCoronaAndroid
|
Apache License 2.0
|
supreme/src/iosMain/kotlin/at/asitplus/signum/supreme/InteropUtils.kt
|
a-sit-plus
| 700,518,667
| false
|
{"Kotlin": 1106936, "Swift": 554}
|
@file:OptIn(ExperimentalForeignApi::class)
package at.asitplus.signum.supreme
import kotlinx.cinterop.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import platform.CoreFoundation.CFDictionaryCreateMutable
import platform.CoreFoundation.CFDictionaryGetValue
import platform.CoreFoundation.CFDictionaryRef
import platform.CoreFoundation.CFDictionarySetValue
import platform.CoreFoundation.CFErrorRefVar
import platform.CoreFoundation.CFMutableDictionaryRef
import platform.CoreFoundation.CFTypeRef
import platform.CoreFoundation.kCFBooleanFalse
import platform.CoreFoundation.kCFBooleanTrue
import platform.CoreFoundation.kCFTypeDictionaryKeyCallBacks
import platform.CoreFoundation.kCFTypeDictionaryValueCallBacks
import platform.Foundation.CFBridgingRelease
import platform.Foundation.CFBridgingRetain
import platform.Foundation.NSData
import platform.Foundation.NSError
import platform.Foundation.create
import platform.Security.SecCopyErrorMessageString
import platform.darwin.OSStatus
import platform.posix.memcpy
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.ref.createCleaner
@OptIn(ExperimentalNativeApi::class)
class AutofreeVariable<T: CPointer<*>> internal constructor(
arena: Arena,
private val variable: CPointerVarOf<T>) {
companion object {
internal inline operator fun <reified T: CPointer<*>> invoke(): AutofreeVariable<T> {
val arena = Arena()
val variable = arena.alloc<CPointerVarOf<T>>()
return AutofreeVariable<T>(arena, variable)
}
}
@Suppress("UNUSED")
private val cleaner = createCleaner(arena, Arena::clear)
internal val ptr get() = variable.ptr
internal val value get() = variable.value
}
internal fun NSData.toByteArray(): ByteArray = ByteArray(length.toInt()).apply {
usePinned {
memcpy(it.addressOf(0), bytes, length)
}
}
@OptIn(BetaInteropApi::class)
internal fun ByteArray.toNSData(): NSData = memScoped {
NSData.create(bytes = allocArrayOf(this@toNSData), length = this@toNSData.size.toULong())
}
private fun NSError.toNiceString(): String {
val sb = StringBuilder("[${if(domain != null) "$domain error, " else ""}code $code] $localizedDescription\n")
localizedFailureReason?.let { sb.append("Because: $it") }
localizedRecoverySuggestion?.let { sb.append("Try: $it") }
localizedRecoveryOptions?.let { sb.append("Try also:\n - ${it.joinToString("\n - ")}\n") }
return sb.toString()
}
class CFCryptoOperationFailed(thing: String, val osStatus: OSStatus) : CryptoOperationFailed(buildMessage(thing, osStatus)) {
companion object {
private fun buildMessage(thing: String, osStatus: OSStatus): String {
val errorMessage = SecCopyErrorMessageString(osStatus, null).takeFromCF<String?>()
return "Failed to $thing: [code $osStatus] ${errorMessage ?: "unspecified security error"}"
}
}
}
class CoreFoundationException(val nsError: NSError): Throwable(nsError.toNiceString())
internal class corecall private constructor(val error: CPointer<CFErrorRefVar>) {
/** Helper for calling Core Foundation functions, and bridging exceptions across.
*
* Usage:
* ```
* corecall { SomeCoreFoundationFunction(arg1, arg2, ..., error) }
* ```
* `error` is provided by the implicit receiver object, and will be mapped to a
* `CoreFoundationException` if an error occurs.
*/
companion object {
@OptIn(BetaInteropApi::class)
operator fun <T> invoke(call: corecall.()->T?) : T {
memScoped {
val errorH = alloc<CFErrorRefVar>()
val result = corecall(errorH.ptr).call()
val error = errorH.value
when {
(result != null) && (error == null) -> return result
(result == null) && (error != null) ->
throw CoreFoundationException(error.takeFromCF<NSError>())
else -> throw IllegalStateException("Invalid state returned by Core Foundation call")
}
}
}
}
}
class SwiftException(message: String): Throwable(message)
internal class swiftcall private constructor(val error: CPointer<ObjCObjectVar<NSError?>>) {
/** Helper for calling swift-objc-mapped functions, and bridging exceptions across.
*
* Usage:
* ```
* swiftcall { SwiftObj.func(arg1, arg2, .., argN, error) }
* ```
* `error` is provided by the implicit receiver object, and will be mapped to a
* `SwiftException` if the swift call throws.
*/
companion object {
@OptIn(BetaInteropApi::class)
operator fun <T> invoke(call: swiftcall.()->T?): T {
memScoped {
val errorH = alloc<ObjCObjectVar<NSError?>>()
val result = swiftcall(errorH.ptr).call()
val error = errorH.value
when {
(result != null) && (error == null) -> return result
(result == null) && (error != null) -> throw SwiftException(error.toNiceString())
else -> throw IllegalStateException("Invalid state returned by Swift")
}
}
}
}
}
internal class swiftasync<T> private constructor(val callback: (T?, NSError?)->Unit) {
/** Helper for calling swift-objc-mapped async functions, and bridging exceptions across.
*
* Usage:
* ```
* swiftasync { SwiftObj.func(arg1, arg2, .., argN, callback) }
* ```
* `error` is provided by the implicit receiver object, and will be mapped to a
* `SwiftException` if the swift call throws.
*/
companion object {
suspend operator fun <T> invoke(call: swiftasync<T>.()->Unit): T {
var result: T? = null
var error: NSError? = null
val mut = Mutex(true)
swiftasync<T> { res, err -> result = res; error = err; mut.unlock() }.call()
mut.withLock {
val res = result
val err = error
when {
(res != null) && (err == null) -> return res
(res == null) && (err != null) -> throw SwiftException(err.toNiceString())
else -> throw IllegalStateException("Invalid state returned by Swift")
}
}
}
}
}
internal inline fun <reified T: CFTypeRef?> Any?.giveToCF() = when(this) {
null -> this
is Boolean -> if (this) kCFBooleanTrue else kCFBooleanFalse
is CValuesRef<*> -> this
else -> CFBridgingRetain(this)
} as T
internal inline fun <reified T> CFTypeRef?.takeFromCF() = CFBridgingRelease(this) as T
internal fun MemScope.cfDictionaryOf(vararg pairs: Pair<*,*>): CFDictionaryRef {
val dict = CFDictionaryCreateMutable(null, pairs.size.toLong(),
kCFTypeDictionaryKeyCallBacks.ptr, kCFTypeDictionaryValueCallBacks.ptr)!!
defer { CFBridgingRelease(dict) } // free it after the memscope finishes
pairs.forEach { (k,v) -> dict[k] = v }
return dict
}
internal class CFDictionaryInitScope private constructor() {
private val pairs = mutableListOf<Pair<*,*>>()
fun map(pair: Pair<*,*>) { pairs.add(pair) }
infix fun Any?.mapsTo(other: Any?) { map(this to other) }
internal companion object {
fun resolve(scope: MemScope, fn: CFDictionaryInitScope.()->Unit) =
scope.cfDictionaryOf(*CFDictionaryInitScope().apply(fn).pairs.toTypedArray())
}
}
internal fun MemScope.createCFDictionary(pairs: CFDictionaryInitScope.()->Unit) =
CFDictionaryInitScope.resolve(this, pairs)
internal inline operator fun <reified T> CFDictionaryRef.get(key: Any?): T =
CFDictionaryGetValue(this, key.giveToCF()).takeFromCF<T>()
internal inline operator fun CFMutableDictionaryRef.set(key: Any?, value: Any?) =
CFDictionarySetValue(this, key.giveToCF(), value.giveToCF())
| 17
|
Kotlin
|
2
| 41
|
d40a11909be205a55e424699323cb0044433bf81
| 7,962
|
signum
|
Apache License 2.0
|
app/src/main/java/com/douglas/githubauth/di/AppComponent.kt
|
douglas-queiroz
| 186,172,907
| false
|
{"Kotlin": 56818}
|
package com.douglas.githubauth.di
import com.douglas.githubauth.di.module.*
import com.douglas.githubauth.module.core.CoreActivity
import com.douglas.githubauth.module.login.LoginFragment
import com.douglas.githubauth.module.repositoryList.RepositoryListFragment
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component (
modules = [
UtilModule::class,
LocalModule::class,
RemoteModule::class,
UseCaseModule::class,
ViewModelModule::class
]
)
interface AppComponent {
fun inject(coreActivity: CoreActivity)
fun inject(loginFragment: LoginFragment)
fun inject(repositoryListFragment: RepositoryListFragment)
}
| 0
|
Kotlin
|
0
| 0
|
063115e6f44e93e4f9ba0063bf43da6e02b77359
| 690
|
Github-Auth
|
Apache License 2.0
|
libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/ApolloUsedCoordinates.kt
|
ai-doma-android
| 434,554,147
| true
|
{"Kotlin": 2342073, "Java": 226626, "CSS": 26280, "ANTLR": 8213, "JavaScript": 1191}
|
package com.apollographql.apollo3.compiler
import com.apollographql.apollo3.ast.GQLFragmentDefinition
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.ast.parseAsGQLDocument
import com.apollographql.apollo3.ast.toUtf8
import com.apollographql.apollo3.compiler.codegen.ResolverInfo
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import okio.buffer
import okio.sink
import okio.source
import java.io.File
private val anyAdapter = Moshi.Builder()
.build()
.adapter(Any::class.java)
fun File.toUsedCoordinates(): Set<String> {
val result = source().buffer().use {
anyAdapter.fromJson(it)
}
check(result is List<*>) {
"Apollo: cannot read coordinates: $result"
}
@Suppress("UNCHECKED_CAST")
return result.toSet() as Set<String>
}
fun Set<String>.writeTo(file: File) {
file.sink().buffer().use {
anyAdapter.toJson(it, this.toList())
}
}
| 0
|
Kotlin
|
0
| 0
|
a2042b0397b4154b1e74ae0426dd6c20d0f0c5af
| 1,101
|
apollo-android
|
MIT License
|
src/main/kotlin/org/semonte/intellij/swagger/traversal/path/swagger/SchemaPathResolver.kt
|
semonte
| 692,733,249
| false
|
{"Kotlin": 511953, "Java": 219922, "HTML": 5081}
|
package org.semonte.intellij.swagger.traversal.path.swagger
import com.intellij.psi.PsiElement
class SchemaPathResolver : PathResolver {
override fun childOfSchema(psiElement: PsiElement): Boolean {
return hasPath(psiElement, "$")
}
override fun childOfSchemaItems(psiElement: PsiElement): Boolean {
return hasPath(psiElement, "$.**.items")
}
override fun childOfRequiredInSchema(psiElement: PsiElement): Boolean {
return hasPath(psiElement, "$.**.required")
}
}
| 0
|
Kotlin
|
0
| 0
|
52f4741b177b1fbc71c4fe8e5d00ef2d572d2154
| 516
|
openapi-plugin
|
MIT License
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/subsystem/IntakeArmSubsystem.kt
|
DevoltRobotics
| 702,717,251
| false
|
{"Gradle": 7, "Java Properties": 1, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "INI": 1, "Kotlin": 53, "XML": 11, "Java": 95, "JSON": 1}
|
package org.firstinspires.ftc.teamcode.subsystem
import com.acmerobotics.dashboard.config.Config
import com.acmerobotics.roadrunner.control.PIDCoefficients
import com.acmerobotics.roadrunner.control.PIDFController
import com.github.serivesmejia.deltacommander.DeltaSubsystem
import com.qualcomm.robotcore.hardware.DcMotor
import com.qualcomm.robotcore.hardware.DcMotorEx
import com.qualcomm.robotcore.hardware.Servo
import org.firstinspires.ftc.teamcode.command.intake.arm.IntakeArmStopCmd
@Config
class IntakeArmSubsystem(val armMotor: DcMotorEx, val wristServo: Servo) : DeltaSubsystem() {
var controller = createController()
private set
var downWristPosition = 0.53
private var previousCoeffs = pidfCoefficients.copy()
init {
}
override fun init() {
controller.targetPosition = armMotor.currentPosition.toDouble()
}
override fun loop() {
}
fun updateController() {
armMotor.power = controller.update(armMotor.currentPosition.toDouble())
}
fun reset() {
armMotor.mode = DcMotor.RunMode.STOP_AND_RESET_ENCODER
armMotor.mode = DcMotor.RunMode.RUN_WITHOUT_ENCODER
}
private fun createController() = PIDFController(pidfCoefficients, kV, kA, kStatic)
companion object {
@JvmStatic var pidfCoefficients = PIDCoefficients(0.01, 0.0001, 0.0001)
@JvmStatic var kV = 0.0
@JvmStatic var kA = 0.0
@JvmStatic var kStatic = 0.0
@JvmStatic var drivingTicksPerSecond = 320
@JvmStatic var ticksPerSecond = 100
@JvmStatic var ticksPerPerSecond = 60
}
}
| 0
|
Java
|
0
| 0
|
72a32f8475e43f97dc980909614559419848adcf
| 1,611
|
Phobos-CenterStage
|
BSD 3-Clause Clear License
|
src/main/kotlin/org/wagham/config/locale/components/MultiCharacterLocale.kt
|
kaironbot
| 566,988,243
| false
|
{"Kotlin": 590249, "Dockerfile": 253}
|
package org.wagham.config.locale.components
import dev.kord.common.Locale
import org.wagham.config.locale.LocaleEnum
enum class MultiCharacterLocale(val localeMap: Map<Locale, String>) : LocaleEnum {
DESCRIPTION(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Select the target character.",
Locale.ITALIAN to "Seleziona il personaggio target."
)
),
NO_SOURCE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "No source character specified.",
Locale.ITALIAN to "Nessun personaggio d'origine trovato."
)
),
INVALID_TARGET_NUMBER(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "Invalid number of targets.",
Locale.ITALIAN to "Numero di personaggi target non valido."
)
),
TITLE(
mapOf(
Locale.ENGLISH_GREAT_BRITAIN to "has more than one active character.",
Locale.ITALIAN to "ha più di un personaggio attivo."
)
);
override fun locale(language: String) = locale(Locale.fromString(language))
override fun locale(locale: Locale) = localeMap[locale] ?: localeMap[Locale.ENGLISH_GREAT_BRITAIN]!!
}
| 4
|
Kotlin
|
0
| 0
|
6d5217b5bbfcc2e1a30bf100a55c86bf3480a753
| 1,169
|
kairon-bot
|
MIT License
|
app/src/main/java/com/nhahv0902/notebook/ui/notebook/NotebookViewModel.kt
|
nhahv0902
| 98,270,423
| false
| null |
package com.nhahv0902.notebook.ui.notebook
import com.nhahv0902.notebook.ui.BaseViewModel
/**
* Exposes the data to be used in the Notebook screen.
*/
class NotebookViewModel : BaseViewModel(){
override fun onStart() {
}
override fun onStop() {
}
}
| 0
|
Kotlin
|
0
| 0
|
b73634e30cfc6700afcf51394a8e30bcd4c284d0
| 272
|
Kotlin_Notebook_MVVM
|
Apache License 2.0
|
app/src/main/java/ar/edu/unlam/mobile/scaffolding/ScaffoldingApplication.kt
|
unlam-tec-movil
| 853,823,205
| false
|
{"Kotlin": 16776}
|
package ar.edu.unlam.mobile.scaffolding
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ScaffoldingApplication : Application()
| 2
|
Kotlin
|
0
| 1
|
282d11401b07b747b3c1bfd3d721f18e23c38f25
| 176
|
a2-2024-h2-e1
|
MIT License
|
canvas-annotation-lib/src/main/kotlin/CanvasItem.kt
|
lambcode
| 123,732,200
| false
|
{"HTML": 223847, "Kotlin": 35948}
|
import org.w3c.dom.CanvasRenderingContext2D
internal interface CanvasItem: Drawable {
val bounds: Rectangle
}
internal interface Drawable {
fun draw(context: CanvasRenderingContext2D)
}
| 0
|
HTML
|
0
| 0
|
7e84616c1696ad385b4c0a917ac74f41655c945a
| 197
|
canvas-annotation
|
MIT License
|
.teamcity/builds/apiReferences/kotlinx/metadataJvm/KotlinxMetadataJvmBuildSearchIndex.kt
|
LiYing2010
| 56,597,384
| true
|
{"JavaScript": 193817, "SCSS": 133216, "Python": 112181, "TypeScript": 86401, "HTML": 53266, "CSS": 41389, "Shell": 8807, "FreeMarker": 4692, "XSLT": 3883, "Dockerfile": 1276}
|
package builds.apiReferences.kotlinx.metadataJvm
import builds.apiReferences.dependsOnDokkaPagesJson
import builds.apiReferences.templates.BuildApiReferenceSearchIndex
import jetbrains.buildServer.configs.kotlin.BuildType
object KotlinxMetadataJvmBuildSearchIndex: BuildType({
name = "Build search index for kotlinx-metadata-jvm"
templates(BuildApiReferenceSearchIndex)
params {
param("env.ALGOLIA_INDEX_NAME", "kotlinx-metadata-jvm")
param("env.API_REFERENCE_URL", "/api/kotlinx-metadata-jvm")
}
dependencies {
dependsOnDokkaPagesJson(KotlinxMetadataJvmBuildApiReference)
}
})
| 0
|
JavaScript
|
18
| 91
|
919be695d31d4f00acfb20827d74d590830fcce2
| 607
|
kotlin-web-site
|
Apache License 2.0
|
modules/core/arrow-test/src/main/kotlin/arrow/test/laws/MonadDeferLaws.kt
|
clojj
| 343,913,289
| true
|
{"Kotlin": 3017035, "CSS": 85447, "JavaScript": 26157, "HTML": 22172, "Scala": 8073, "Shell": 6915, "Java": 4465, "Ruby": 1598}
|
package arrow.fx.test.laws
import arrow.Kind
import arrow.core.extensions.eq
import arrow.core.extensions.list.foldable.foldLeft
import arrow.core.k
import arrow.core.left
import arrow.core.right
import arrow.core.test.concurrency.SideEffect
import arrow.core.test.generators.GenK
import arrow.core.test.generators.intSmall
import arrow.core.test.generators.throwable
import arrow.core.test.laws.Law
import arrow.fx.typeclasses.MonadDefer
import arrow.typeclasses.Apply
import arrow.typeclasses.Eq
import arrow.typeclasses.EqK
import arrow.typeclasses.Functor
import arrow.typeclasses.Selective
import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll
import io.kotlintest.shouldBe
object MonadDeferLaws {
private fun <F> monadDeferLaws(
SC: MonadDefer<F>,
GENK: GenK<F>,
EQK: EqK<F>,
testStackSafety: Boolean = true,
iterations: Int = 20_000
): List<Law> {
val EQ = EQK.liftEq(Int.eq())
return listOf(
Law("MonadDefer laws: later constant equals pure") { SC.laterConstantEqualsPure(EQ) },
Law("MonadDefer laws: later throw equals raiseError") { SC.laterThrowEqualsRaiseError(EQ) },
Law("MonadDefer laws: later constant equals pure") { SC.deferConstantEqualsPure(EQ) },
Law("MonadDefer laws: laterOrRaise constant right equals pure") { SC.laterOrRaiseConstantRightEqualsPure(EQ) },
Law("MonadDefer laws: laterOrRaise constant left equals raiseError") { SC.laterOrRaiseConstantLeftEqualsRaiseError(EQ) },
Law("MonadDefer laws: propagate error through bind") { SC.propagateErrorsThroughBind(EQ) },
Law("MonadDefer laws: defer suspends evaluation") { SC.deferSuspendsEvaluation(EQ) },
Law("MonadDefer laws: later suspends evaluation") { SC.delaySuspendsEvaluation(EQ) },
Law("MonadDefer laws: flatMap suspends evaluation") { SC.flatMapSuspendsEvaluation(EQ) },
Law("MonadDefer laws: map suspends evaluation") { SC.mapSuspendsEvaluation(EQ) },
Law("MonadDefer laws: Repeated evaluation not memoized") { SC.repeatedSyncEvaluationNotMemoized(EQ) },
Law("MonadDefer laws: later should be consistent") { SC.derivedLaterConsistent(GENK, EQ) },
Law("MonadDefer laws: lazy should be consistent") { SC.derivedLazyConsistent(GENK, EQ) }
) + if (testStackSafety) {
listOf(
Law("MonadDefer laws: stack safety over repeated left binds") { SC.stackSafetyOverRepeatedLeftBinds(iterations, EQ) },
Law("MonadDefer laws: stack safety over repeated right binds") { SC.stackSafetyOverRepeatedRightBinds(iterations, EQ) },
Law("MonadDefer laws: stack safety over repeated attempts") { SC.stackSafetyOverRepeatedAttempts(iterations, EQ) },
Law("MonadDefer laws: stack safety over repeated maps") { SC.stackSafetyOnRepeatedMaps(iterations, EQ) }
)
} else {
emptyList()
}
}
fun <F> laws(
SC: MonadDefer<F>,
GENK: GenK<F>,
EQK: EqK<F>,
testStackSafety: Boolean = true,
iterations: Int = 5_000
): List<Law> =
BracketLaws.laws(SC, GENK, EQK, testStackSafety, iterations) +
MonadThrowLaws.laws(SC, GENK, EQK) +
monadDeferLaws(SC, GENK, EQK, testStackSafety, iterations)
fun <F> laws(
SC: MonadDefer<F>,
FF: Functor<F>,
AP: Apply<F>,
SL: Selective<F>,
GENK: GenK<F>,
EQK: EqK<F>,
testStackSafety: Boolean = true,
iterations: Int = 5_000
): List<Law> =
BracketLaws.laws(SC, FF, AP, SL, GENK, EQK, testStackSafety, iterations) +
MonadThrowLaws.laws(SC, SC, SC, SC, GENK, EQK) +
monadDeferLaws(SC, GENK, EQK, testStackSafety, iterations)
fun <F> MonadDefer<F>.derivedLaterConsistent(GK: GenK<F>, EQ: Eq<Kind<F, Int>>) {
forAll(50, GK.genK(Gen.int()), Gen.intSmall()) { fa: Kind<F, Int>, x: Int ->
later(fa).equalUnderTheLaw(defer { fa }, EQ)
}
}
fun <F> MonadDefer<F>.derivedLazyConsistent(GK: GenK<F>, EQ: Eq<Kind<F, Int>>) {
forAll(50, GK.genK(Gen.int())) { fa: Kind<F, Int> ->
lazy().flatMap { fa }.equalUnderTheLaw(later { }.flatMap { fa }, EQ)
}
}
fun <F> MonadDefer<F>.laterConstantEqualsPure(EQ: Eq<Kind<F, Int>>) {
forAll(50, Gen.intSmall()) { x ->
later { x }.equalUnderTheLaw(just(x), EQ)
}
}
fun <F> MonadDefer<F>.deferConstantEqualsPure(EQ: Eq<Kind<F, Int>>) {
forAll(50, Gen.intSmall()) { x ->
defer { just(x) }.equalUnderTheLaw(just(x), EQ)
}
}
fun <F> MonadDefer<F>.laterOrRaiseConstantRightEqualsPure(EQ: Eq<Kind<F, Int>>) {
forAll(50, Gen.intSmall()) { x ->
laterOrRaise { x.right() }.equalUnderTheLaw(just(x), EQ)
}
}
fun <F> MonadDefer<F>.laterOrRaiseConstantLeftEqualsRaiseError(EQERR: Eq<Kind<F, Int>>) {
forFew(5, Gen.throwable()) { t ->
laterOrRaise { t.left() }.equalUnderTheLaw(raiseError(t), EQERR)
}
}
fun <F> MonadDefer<F>.laterThrowEqualsRaiseError(EQERR: Eq<Kind<F, Int>>) {
forFew(5, Gen.throwable()) { t ->
later { throw t }.equalUnderTheLaw(raiseError(t), EQERR)
}
}
fun <F> MonadDefer<F>.propagateErrorsThroughBind(EQERR: Eq<Kind<F, Int>>) {
forFew(5, Gen.throwable()) { t ->
later { throw t }.flatMap<Int, Int> { a: Int -> just(a) }.equalUnderTheLaw(raiseError(t), EQERR)
}
}
fun <F> MonadDefer<F>.deferSuspendsEvaluation(EQ: Eq<Kind<F, Int>>) {
val sideEffect = SideEffect(counter = 0)
val df = defer { sideEffect.increment(); just(sideEffect.counter) }
Thread.sleep(10)
sideEffect.counter shouldBe 0
df.equalUnderTheLaw(just(1), EQ) shouldBe true
}
fun <F> MonadDefer<F>.delaySuspendsEvaluation(EQ: Eq<Kind<F, Int>>) {
val sideEffect = SideEffect(counter = 0)
val df = later { sideEffect.increment(); sideEffect.counter }
Thread.sleep(10)
sideEffect.counter shouldBe 0
df.equalUnderTheLaw(just(1), EQ) shouldBe true
}
fun <F> MonadDefer<F>.flatMapSuspendsEvaluation(EQ: Eq<Kind<F, Int>>) {
val sideEffect = SideEffect(counter = 0)
val df = just(0).flatMap { sideEffect.increment(); just(sideEffect.counter) }
Thread.sleep(10)
sideEffect.counter shouldBe 0
df.equalUnderTheLaw(just(1), EQ) shouldBe true
}
fun <F> MonadDefer<F>.mapSuspendsEvaluation(EQ: Eq<Kind<F, Int>>) {
val sideEffect = SideEffect(counter = 0)
val df = just(0).map { sideEffect.increment(); sideEffect.counter }
Thread.sleep(10)
sideEffect.counter shouldBe 0
df.equalUnderTheLaw(just(1), EQ) shouldBe true
}
fun <F> MonadDefer<F>.repeatedSyncEvaluationNotMemoized(EQ: Eq<Kind<F, Int>>) {
val sideEffect = SideEffect()
val df = later { sideEffect.increment(); sideEffect.counter }
df.flatMap { df }.flatMap { df }.equalUnderTheLaw(just(3), EQ) shouldBe true
}
fun <F> MonadDefer<F>.stackSafetyOverRepeatedLeftBinds(iterations: Int = 20_000, EQ: Eq<Kind<F, Int>>): Unit =
forAll(50, Gen.create { Unit }) {
(0..iterations).toList().k().foldLeft(just(0)) { def, x ->
def.flatMap { just(x) }
}.equalUnderTheLaw(just(iterations), EQ)
}
fun <F> MonadDefer<F>.stackSafetyOverRepeatedRightBinds(iterations: Int = 20_000, EQ: Eq<Kind<F, Int>>): Unit =
forAll(50, Gen.create { Unit }) {
(0..iterations).toList().foldRight(just(iterations)) { x, def ->
lazy().flatMap { def }
}.equalUnderTheLaw(just(iterations), EQ)
}
fun <F> MonadDefer<F>.stackSafetyOverRepeatedAttempts(iterations: Int = 20_000, EQ: Eq<Kind<F, Int>>): Unit =
forAll(50, Gen.create { Unit }) {
(0..iterations).toList().foldLeft(just(0)) { def, x ->
def.attempt().map { x }
}.equalUnderTheLaw(just(iterations), EQ)
}
fun <F> MonadDefer<F>.stackSafetyOnRepeatedMaps(iterations: Int = 20_000, EQ: Eq<Kind<F, Int>>): Unit =
forAll(50, Gen.create { Unit }) {
(0..iterations).toList().foldLeft(just(0)) { def, x ->
def.map { x }
}.equalUnderTheLaw(just(iterations), EQ)
}
}
| 0
| null |
0
| 0
|
754a4467f1fc1a9dcf7a0d5b890e70198a7f51b0
| 7,889
|
arrow
|
Apache License 2.0
|
app/src/main/java/com/cagudeloa/harrypotter/ui/viewmodel/ViewModelFactory.kt
|
casa98
| 296,815,895
| false
| null |
package com.cagudeloa.harrypotter.ui.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.cagudeloa.harrypotter.domain.Repository
class ViewModelFactory(private val repository: Repository): ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(Repository::class.java).newInstance(repository)
}
}
| 0
|
Kotlin
|
0
| 0
|
70292268d49613c47a23eb76c0ce3b672ae6f37e
| 433
|
Harry-Potter
|
MIT License
|
app/src/main/java/com/cagudeloa/harrypotter/ui/viewmodel/ViewModelFactory.kt
|
casa98
| 296,815,895
| false
| null |
package com.cagudeloa.harrypotter.ui.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.cagudeloa.harrypotter.domain.Repository
class ViewModelFactory(private val repository: Repository): ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(Repository::class.java).newInstance(repository)
}
}
| 0
|
Kotlin
|
0
| 0
|
70292268d49613c47a23eb76c0ce3b672ae6f37e
| 433
|
Harry-Potter
|
MIT License
|
app/src/main/java/com/dojo/moovies/interactor/HomeIntercator.kt
|
pgsilva
| 739,863,015
| false
|
{"Kotlin": 84359}
|
package com.dojo.moovies.interactor
import android.util.Log
import com.dojo.moovies.interactor.state.HomeInteractorState.HomeLoadState
import com.dojo.moovies.repository.MyListRepository
import com.dojo.moovies.repository.TheMovieDbRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class HomeIntercator(
private val apiRepository: TheMovieDbRepository,
private val dbRepository: MyListRepository
) {
suspend fun loadDiscoverMovies(): HomeLoadState = try {
apiRepository.getDiscoverMovies().let {
when {
it.isNotEmpty() -> HomeLoadState.Success(it)
else -> HomeLoadState.Error
}
}
} catch (e: Exception) {
Log.e(
"MOOVIES-THEMOVIEDBAPI",
"Api Discover Movie Error, response is not successful: ${e.printStackTrace()}"
)
HomeLoadState.Error
}
suspend fun loadDiscoverTv(): HomeLoadState = try {
apiRepository.getDiscoverTv().let {
when {
it.isNotEmpty() -> HomeLoadState.Success(it)
else -> HomeLoadState.Error
}
}
} catch (e: Exception) {
Log.e(
"MOOVIES-THEMOVIEDBAPI",
"Api Discover TV Error, response is not successful: ${e.printStackTrace()}"
)
HomeLoadState.Error
}
suspend fun loadPreviewMyList(): Flow<HomeLoadState> = flow {
dbRepository.findAllLimit20().collect {
emit(HomeLoadState.Success(it))
}
}
suspend fun loadPopularMovies(
): HomeLoadState = try {
apiRepository.getPopularMovies().let {
when {
it.isNotEmpty() -> HomeLoadState.Success(it)
else -> HomeLoadState.Error
}
}
} catch (e: Exception) {
Log.e(
"MOOVIES-THEMOVIEDBAPI",
"Api Popular Movies Error, response is not successful: ${e.printStackTrace()}"
)
HomeLoadState.Error
}
suspend fun loadPopularTv(
): HomeLoadState = try {
apiRepository.getPopularTv().let {
when {
it.isNotEmpty() -> HomeLoadState.Success(it)
else -> HomeLoadState.Error
}
}
} catch (e: Exception) {
Log.e(
"MOOVIES-THEMOVIEDBAPI",
"Api Popular Tv Error, response is not successful: ${e.printStackTrace()}"
)
HomeLoadState.Error
}
}
| 0
|
Kotlin
|
0
| 0
|
e4f5dd987488cae8beb86e22570ed1e939e2f324
| 2,495
|
moovies
|
MIT License
|
app/src/main/java/com/andruhavuho/man/like/notes/ui/EditNoteFragment.kt
|
Andrey-Kachow
| 453,088,485
| false
|
{"Kotlin": 21904}
|
package com.andruhavuho.man.like.notes.ui
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.viewModelScope
import com.andruhavuho.man.like.notes.App
import com.andruhavuho.man.like.notes.MainActivity
import com.andruhavuho.man.like.notes.R
import com.andruhavuho.man.like.notes.database.NotesViewModel
import kotlinx.coroutines.launch
class EditNoteFragment : Fragment(R.layout.fragment_edit_note) {
private var currentNoteId: Long = 0
private lateinit var etNoteTitle: TextView
private lateinit var etNoteDescription: TextView
private lateinit var vm : NotesViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
vm = (requireActivity().application as App).vm
arguments?.getLong(NOTE_ID)?.takeIf { it > 0 }?.let { noteId ->
currentNoteId = noteId
} ?: run {
Toast.makeText(requireActivity(), "Something Went Wrong", Toast.LENGTH_LONG).show()
requireActivity().onBackPressed()
}
etNoteTitle = view.findViewById(R.id.etNoteTitle)
etNoteDescription = view.findViewById(R.id.etNoteDescription)
vm.viewModelScope.launch {
val noteEntity = vm.getNote(currentNoteId)
if (noteEntity.name != "") {
etNoteTitle.text = noteEntity.name
}
if (noteEntity.description != "") {
etNoteDescription.text = noteEntity.description
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_edit_note, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.mi_done -> {
saveChangesAndReturn()
}
}
return super.onOptionsItemSelected(item)
}
private fun saveChangesAndReturn() {
vm.viewModelScope.launch {
val noteEntity = vm.getNote(currentNoteId)
noteEntity.apply {
name = etNoteTitle.text.toString()
description = etNoteDescription.text.toString()
vm.updateNote(this)
}
// noteEntity.name = etNoteTitle.text.toString()
// noteEntity.description = etNoteDescription.text.toString()
// vm.updateNote(noteEntity)
(requireActivity() as MainActivity).onBackPressed()
}
}
companion object {
const val NOTE_ID = "NOTE_ID"
fun newInstance(noteId: Long): EditNoteFragment {
return EditNoteFragment().apply {
arguments = bundleOf(NOTE_ID to noteId)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d82613afac94b3d458548afc780fade92affa9c6
| 3,066
|
BlueNotes
|
MIT License
|
jvm/src/main/kotlin/jp/ogiwara/anitube/method/GetTopVideosMethod.kt
|
Ogiwara-CostlierRain464
| 123,071,878
| false
|
{"JavaScript": 1686208, "Kotlin": 44675, "HTML": 702}
|
package jp.ogiwara.anitube.method
import jp.ogiwara.anitube.Anitube
import jp.ogiwara.anitube.http.getBody
import jp.ogiwara.anitube.makeVideo
import jp.ogiwara.anitube.model.Video
import org.jsoup.Jsoup
internal actual class GetTopVideosMethod actual constructor(val fragment: String) {
actual fun execute(): List<Video> {
val document = Jsoup.parse(getBody(Anitube.Url.TOP))
val fragments = document.getElementById(fragment)
val targetFragment = fragments.getElementById(fragment).getElementsByClass("mainList")
return targetFragment.map(Any::toString).mapNotNull(::makeVideo)
}
}
| 0
|
JavaScript
|
0
| 2
|
76db04ce41d1b197c29bc1c884be617184fa2fa2
| 624
|
AnitubeAPI
|
MIT License
|
sample/test-utils/src/androidMain/kotlin/StringDescExt.kt
|
icerockdev
| 204,874,263
| false
| null |
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import dev.icerock.moko.resources.desc.StringDesc
actual fun StringDesc.getString(): String {
val context = ApplicationProvider.getApplicationContext<Context>()
return toString(context)
}
| 37
|
Kotlin
|
33
| 285
|
31103b4fa7bca2445487b9f9aafa9cc8085af3ca
| 384
|
moko-resources
|
Apache License 2.0
|
android/features/login/src/main/java/io/newm/feature/login/screen/email/EmailState.kt
|
projectNEWM
| 435,674,758
| false
|
{"Kotlin": 326567, "Swift": 233616}
|
package io.newm.feature.login.screen.email
import androidx.core.util.PatternsCompat.EMAIL_ADDRESS
import io.newm.feature.login.screen.TextFieldState
class EmailState : TextFieldState(validator = ::isEmailValid, errorFor = ::emailValidationError)
/**
* Returns an error to be displayed or null if no error was found
*/
private fun emailValidationError(email: String): String {
return "Invalid email: $email"
}
private fun isEmailValid(email: String): Boolean {
return EMAIL_ADDRESS.matcher(email).matches()
}
| 1
|
Kotlin
|
8
| 9
|
98b9e2d2dfe9ce29d53cf31f73a5a0172f742717
| 521
|
newm-mobile
|
Apache License 2.0
|
shared/src/commonMain/kotlin/co/nimblehq/ic/kmm/suv/di/extensions/UseCase.kt
|
suho
| 523,936,897
| false
|
{"Kotlin": 232630, "Swift": 119332, "Ruby": 21329, "Shell": 81}
|
package co.nimblehq.ic.kmm.suv.di.extensions
import co.nimblehq.ic.kmm.suv.di.initKoin
import co.nimblehq.ic.kmm.suv.domain.usecase.*
import org.koin.core.Koin
import org.koin.core.KoinApplication
fun KoinApplication.Companion.start(): KoinApplication = initKoin()
// Define all UseCases here for iOS
val Koin.logInUseCase: LogInUseCase
get() = get()
val Koin.getProfileUseCase: GetProfileUseCase
get() = get()
val Koin.getSurveysUseCase: GetSurveysUseCase
get() = get()
val Koin.getSurveyDetailUseCase: GetSurveyDetailUseCase
get() = get()
val Koin.submitSurveyResponseUseCase: SubmitSurveyResponseUseCase
get() = get()
| 0
|
Kotlin
|
0
| 3
|
d34b39d4755770898c8236db0318535a5aa15dcf
| 648
|
kmm-ic
|
MIT License
|
app/src/main/java/com/lobo/userlist/domain/interactor/GetUsersList.kt
|
viniciuslobo21
| 435,084,879
| false
| null |
package com.lobo.userlist.domain.interactor
import com.lobo.userlist.core.util.Result
import com.lobo.userlist.domain.UserModel
import com.lobo.userlist.repository.UsersRepository
class GetUsersList(private val repository: UsersRepository) {
fun invoke(): Result<List<UserModel>, Exception> {
return repository.getUserList()
}
}
| 0
|
Kotlin
|
0
| 0
|
38a4e5ffc22d6107d8c1907332d93376a6f45227
| 347
|
FunAvatarApp
|
MIT License
|
app/src/main/java/com/auliaisb/weatherforecast/di/AppComponents.kt
|
auliaisb
| 201,660,219
| false
| null |
package com.auliaisb.weatherforecast.di
import com.auliaisb.weatherforecast.WeatherApp
import com.auliaisb.weatherforecast.db.DbModule
import com.auliaisb.weatherforecast.repo.WeatherRepo
import com.auliaisb.weatherforecast.viewmodel.MainViewModel
import com.auliaisb.weatherforecast.webservice.NetworkModule
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AppModule::class, NetworkModule::class, DbModule::class))
interface AppComponents {
fun inject(weatherApp: WeatherApp)
fun inject(weatherRepo: WeatherRepo)
fun inject(mainViewModel: MainViewModel)
}
| 0
|
Kotlin
|
0
| 0
|
f8302f5393f2e24b83b4ded575c4f025669cb69f
| 615
|
WeatherForecast
|
Apache License 2.0
|
lista1/app/src/main/java/br/senac/android/lista1/exercicio1.kt
|
ph-gonzaga
| 418,153,446
| false
|
{"Kotlin": 26350}
|
package br.senac.android.lista1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
class exercicio1 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_exercicio1)
var nome = findViewById<EditText>(R.id.fieldNome)
var telefone = findViewById<EditText>(R.id.fieldTelefone)
var email = findViewById<EditText>(R.id.fieldEmail)
var whatsapp = findViewById<EditText>(R.id.fieldApp)
var checkTele = findViewById<CheckBox>(R.id.checkTelefone)
var checkMail = findViewById<CheckBox>(R.id.checkEmail)
var checkApp = findViewById<CheckBox>(R.id.checkApp)
var btnValidar = findViewById<Button>(R.id.btnSalvar)
btnValidar.setOnClickListener {
var msg = """ Nome: ${nome.text}
| Telefone: ${telefone.text}
| E-mail: ${email.text}
| Whatsapp: ${whatsapp.text}
|
|Preferencia de contato
""".trimMargin()
if (checkTele.isChecked){
msg += "\n - Telefone"
}
if (checkMail.isChecked){
msg += "\n - Email"
}
if (checkApp.isChecked){
msg += "\n - Whatsapp"
}
alert("Informacoes inseridas com sucesso!", msg,this)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6391eff301823727814259c16c87eabb37b3fe20
| 1,558
|
atividades_android
|
MIT License
|
library/composables/src/commonMain/kotlin/com/tunjid/composables/pointeroffsetscroll/PointerOffsetScroll.kt
|
tunjid
| 767,617,473
| false
|
{"Kotlin": 86459}
|
package com.tunjid.composables.pointeroffsetscroll
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onPlaced
import com.tunjid.composables.scrollbars.valueOf
import kotlinx.coroutines.delay
/**
* State for utilizing [Modifier.pointerOffsetScroll].
*
* @param enabled The initial enabled state of the [PointerOffsetScrollState].
*
* @param scrollThresholdFraction The fraction that when crossed by
* [PointerOffsetScrollState.currentOffset], will trigger a scroll. It is relative to the center of
* the bound of the Composable [Modifier.pointerOffsetScroll] is attached to.
*
* @param scrollableState The scrollable state that will be scrolled when the offset threshold
* is crossed.
*
* @param orientation the [Orientation] used to determine the scroll speed when scrolling the
* [ScrollableState].
*/
@Stable
class PointerOffsetScrollState(
enabled: Boolean = true,
scrollThresholdFraction: Float = 0.5f,
internal val scrollableState: ScrollableState,
internal val orientation: Orientation,
) {
/**
* The current pointer [Offset] in the scrollable container. The closer it is to the extremes,
* the faster the scroll.
*/
var currentOffset by mutableStateOf(Offset.Zero)
/**
* Whether or not the [Modifier] is enabled.
*/
var enabled by mutableStateOf(enabled)
/**
* The fraction over which when crossed, scrolling will begin. The position is relative to
* the center of the bounding container.
*/
var scrollThresholdFraction by mutableFloatStateOf(scrollThresholdFraction)
internal var bottomEnd by mutableStateOf(Offset.Zero)
internal var scrollAmount by mutableFloatStateOf(0f)
}
/**
* A Modifier that scrolls a [ScrollableState] forwards or backwards when
* the [PointerOffsetScrollState.currentOffset] crosses the center of the Composable [this]
* [Modifier] is attached to by the threshold defined by
* [PointerOffsetScrollState.scrollThresholdFraction].
*
* @param state the state managing the [Modifier].
*/
@Composable
fun Modifier.pointerOffsetScroll(
state: PointerOffsetScrollState,
): Modifier {
LaunchedEffect(state.currentOffset, state.bottomEnd, state.scrollThresholdFraction) {
if (state.currentOffset == Offset.Unspecified) return@LaunchedEffect
val currentValue = state.orientation.valueOf(state.currentOffset)
val maxValue = state.orientation.valueOf(state.bottomEnd)
val lowerThreshold = (maxValue - (maxValue * state.scrollThresholdFraction)) / 2
val upperThreshold = maxValue - lowerThreshold
state.scrollAmount = when (currentValue) {
in Float.MIN_VALUE..lowerThreshold -> currentValue - lowerThreshold
in upperThreshold..Float.MAX_VALUE -> currentValue - upperThreshold
else -> 0f
}
}
LaunchedEffect(state.scrollAmount, state.enabled) {
if (state.scrollAmount == 0f || !state.enabled) return@LaunchedEffect
while (true) {
state.scrollableState.scrollBy(state.scrollAmount)
delay(POINTER_SCROLL_DELAY_MS)
}
}
return this then Modifier.onPlaced { coordinates ->
state.bottomEnd = coordinates.boundsInRoot().let {
Offset(it.width, it.height)
}
}
}
private const val POINTER_SCROLL_DELAY_MS = 10L
| 0
|
Kotlin
|
1
| 5
|
5b80b21e1bab34678d400c6f17fe8032a35c7301
| 3,924
|
composables
|
Apache License 2.0
|
y2015/src/main/kotlin/adventofcode/y2015/Day03.kt
|
Ruud-Wiegers
| 434,225,587
| false
|
{"Kotlin": 496180}
|
package adventofcode.y2015
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
object Day03 : AdventSolution(2015, 3, "Perfectly Spherical Houses in a Vacuum") {
override fun solvePartOne(input: String) = input.visitEach().size
override fun solvePartTwo(input: String): Int {
val route1 = input.filterIndexed { i, _ -> i % 2 == 0 }.visitEach()
val route2 = input.filterIndexed { i, _ -> i % 2 != 0 }.visitEach()
val visited = route1 + route2
return visited.size
}
private fun String.visitEach() = asSequence()
.map { it.toDirection() }
.map(Direction::vector)
.scan(Vec2.origin, Vec2::plus)
.toSet()
private fun Char.toDirection() = when (this) {
'>' -> Direction.RIGHT
'<' -> Direction.LEFT
'^' -> Direction.UP
'v' -> Direction.DOWN
else -> throw IllegalArgumentException()
}
}
| 0
|
Kotlin
|
0
| 3
|
71a4c9c3da05da45901bc0c80fdde49d64a9c0e5
| 979
|
advent-of-code
|
MIT License
|
client/slack-api-client/src/main/kotlin/com/kreait/slack/api/group/channels/ChannelsCreateMethod.kt
|
ironaraujo
| 249,748,914
| true
|
{"Kotlin": 1212878, "Shell": 935}
|
package com.kreait.slack.api.group.channels
import com.kreait.slack.api.contract.jackson.group.channels.ChannelsCreateRequest
import com.kreait.slack.api.contract.jackson.group.channels.ErrorChannelsCreateResponse
import com.kreait.slack.api.contract.jackson.group.channels.SuccessfulChannelsCreateResponse
import com.kreait.slack.api.group.ApiCallMethod
/**
* Abstract representation of an slack api operation
* Creates a channel
* https://api.slack.com/methods/channels.create
*/
abstract class ChannelsCreateMethod : ApiCallMethod<ChannelsCreateMethod, SuccessfulChannelsCreateResponse, ErrorChannelsCreateResponse, ChannelsCreateRequest>() {
}
| 0
| null |
0
| 0
|
07edb441421961b0d84d8f95e97f8b25f48a360e
| 655
|
slack-spring-boot-starter
|
MIT License
|
dslitem/src/main/java/com/angcyo/item/DslSegmentSolidTabItem.kt
|
angcyo
| 229,037,615
| false
|
{"Kotlin": 6616677, "JavaScript": 5194}
|
package com.angcyo.item
import com.angcyo.item.style.itemTabSelectIndexChangeAction
/**
* 块状颜色分段的[DslSegmentTabItem]
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/09/27
*/
open class DslSegmentSolidTabItem : DslSegmentTabItem() {
init {
itemLayoutId = R.layout.dsl_segment_solid_tab_item
//选项列表
itemSegmentList
//回调监听
itemTabSelectIndexChangeAction
}
}
| 0
|
Kotlin
|
4
| 3
|
6ce6ff1dc48e44243adbb75f62d0497ba4443e41
| 424
|
UICore
|
MIT License
|
core/utils/src/main/kotlin/top/chengdongqing/weui/core/utils/PermissionUtils.kt
|
chengdongqing
| 782,566,304
| false
|
{"Kotlin": 894390}
|
package top.chengdongqing.weui.core.utils
import android.Manifest
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun RequestMediaPermission(
extraPermissions: List<String> = emptyList(),
onRevoked: (() -> Unit)? = null,
content: @Composable () -> Unit
) {
val permissionState = rememberMultiplePermissionsState(buildList {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
addAll(
listOf(
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_VIDEO
)
)
} else {
add(Manifest.permission.READ_EXTERNAL_STORAGE)
}
if (extraPermissions.isNotEmpty()) {
addAll(extraPermissions)
}
}) { res ->
if (res.values.any { value -> !value }) {
onRevoked?.invoke()
}
}
LaunchedEffect(permissionState) {
if (!permissionState.allPermissionsGranted) {
permissionState.launchMultiplePermissionRequest()
}
}
if (permissionState.allPermissionsGranted) {
content()
}
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun RequestCameraPermission(
extraPermissions: List<String> = emptyList(),
onRevoked: (() -> Unit)? = null,
content: @Composable BoxScope.() -> Unit
) {
val permissionState = rememberMultiplePermissionsState(buildList {
add(Manifest.permission.CAMERA)
if (extraPermissions.isNotEmpty()) {
addAll(extraPermissions)
}
}) { res ->
if (res.values.any { value -> !value }) {
onRevoked?.invoke()
}
}
LaunchedEffect(permissionState) {
if (!permissionState.allPermissionsGranted) {
permissionState.launchMultiplePermissionRequest()
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
) {
if (permissionState.allPermissionsGranted) {
SetupFullscreen()
content()
}
}
}
| 0
|
Kotlin
|
3
| 8
|
eb773e75aacb801cb24adb41db9fe17224eb883a
| 2,621
|
WeUI
|
Apache License 2.0
|
src/main/kotlin/topic_3/StudAdmin.kt
|
GionRubitschung
| 708,739,829
| false
|
{"Kotlin": 8611}
|
package topic_3
import kotlin.random.Random
class Course {
private val students = ArrayList<Student>()
fun addStudent(student: Student) {
students.add(student)
}
fun removeStudent(student: Student) {
students.removeIf { it.id == student.id }
}
fun numberOfStudents() = students.size
fun averageGrade() = students.sumOf { it.grade } / students.size
override fun toString(): String {
var content = "${numberOfStudents()} students in this course\n"
content += "Average grade: ${averageGrade()}\n"
content += "Students in this course:\n"
for (student in students) content += "- $student\n"
return content
}
}
class Student(id: String, grade: Double) {
var id = id
private set
var grade = grade
private set(value) {
if (value < 1.0 || value > 6.0) throw Error("Grade has to be between 1.0 and 6.0")
field = value
}
override fun toString() = "Student $id has grade $grade"
}
fun main() {
val course = Course()
val students = ArrayList<Student>()
for (stud in 1..Random.nextInt(20, 100)) {
val student = Student("$stud", Random.nextDouble(1.0, 6.0))
course.addStudent(student)
students.add(student)
}
println(course.toString())
val randomStudent = students.random()
println("Number of students in course before student ${randomStudent.id} gets removed: ${course.numberOfStudents()} with average grade: ${course.averageGrade()}")
course.removeStudent(randomStudent)
println("Number of students in course after student ${randomStudent.id} got removed: ${course.numberOfStudents()} with average grade: ${course.averageGrade()}")
println(course.toString())
}
| 0
|
Kotlin
|
0
| 0
|
b42267a9c18fdeb75150bcadd5f7b264546b7f78
| 1,778
|
kotlin_1
|
MIT License
|
client/app/src/main/java/com/unina/natourkt/core/data/remote/dto/mapper/ReportCreationApiMapper.kt
|
archer-65
| 433,413,556
| false
| null |
package com.unina.natourkt.core.data.remote.dto.mapper
import com.unina.natourkt.core.data.remote.dto.ReportCreationDto
import com.unina.natourkt.core.domain.model.ReportCreation
import javax.inject.Inject
class ReportCreationApiMapper @Inject constructor() :
CreationApiMapper<ReportCreation, ReportCreationDto> {
override fun mapToDto(domainEntity: ReportCreation): ReportCreationDto {
return ReportCreationDto(
reportTitle = domainEntity.title,
reportDescription = domainEntity.description,
author = ReportCreationDto.Author(domainEntity.author?.id ?: -1),
reportedRoute = ReportCreationDto.ReportedRoute(domainEntity.reportedRouteId)
)
}
}
| 0
|
Kotlin
|
0
| 1
|
d0c4881e6b8432aff5cf1751d58350da2d5a4461
| 722
|
natour-2122
|
Apache License 2.0
|
Collections/Partition/src/Task.kt
|
teaforthecat
| 842,981,878
| false
|
{"Kotlin": 26830}
|
// Return customers who have more undelivered orders than delivered
fun Shop.getCustomersWithMoreUndeliveredOrders(): Set<Customer> {
return this.customers.filter{
val (del, undel) = it.orders.partition { it.isDelivered }
undel.size > del.size
}.toSet()
}
| 0
|
Kotlin
|
0
| 0
|
ba3c1e0df68ec972f203b090cc30b539e8ce10ce
| 280
|
Kotlin_Koans
|
MIT License
|
test.kts
|
dryproject
| 102,198,916
| false
| null |
#!/usr/bin/env kotlinc -script -classpath build/classes/main
import dry.*
println("OK")
| 0
|
Kotlin
|
0
| 4
|
b38650ed3e33ce4e1bb6b35aa1c47bd27cd48bb5
| 90
|
drylib.kt
|
The Unlicense
|
android/app/src/main/kotlin/neil/vine/retrospective_reminder/MainActivity.kt
|
NeilVine
| 437,246,525
| false
|
{"Dart": 19450, "Swift": 404, "Kotlin": 137, "Objective-C": 38}
|
package neil.vine.retrospective_reminder
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
2ef7b1d9f4f69792ef21a9b2488431a975f83c4b
| 137
|
retro-ideas
|
MIT License
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/responses/FullConversationResponse.kt
|
feelfreelinux
| 97,154,881
| false
| null |
package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.responses
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.common.ApiResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.common.WykopErrorResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.AuthorResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.PMMessageResponse
@JsonIgnoreProperties(ignoreUnknown = true)
class FullConversationResponse(
@JsonProperty("data") override val data: List<PMMessageResponse>?,
@JsonProperty("error") override val error: WykopErrorResponse?,
@JsonProperty("receiver") val receiver: AuthorResponse
) : ApiResponse<List<PMMessageResponse>>
| 47
|
Kotlin
|
51
| 166
|
ec6365b9570818a7ee00c5b512f01cedead30867
| 843
|
WykopMobilny
|
MIT License
|
app/src/main/kotlin/com/github/premnirmal/ticker/BaseApp.kt
|
dhartwich1991
| 53,314,399
| true
|
{"Kotlin": 151522, "Java": 15418}
|
package com.github.premnirmal.ticker
import android.support.multidex.MultiDexApplication
import com.github.premnirmal.tickerwidget.R
import uk.co.chrisjenx.calligraphy.CalligraphyConfig
/**
* Created by premnirmal on 2/26/16.
*/
abstract class BaseApp : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
instance = this
CalligraphyConfig.initDefault(CalligraphyConfig.Builder().setDefaultFontPath("fonts/Ubuntu-Regular.ttf").setFontAttrId(R.attr.fontPath).build())
Injector.init(this)
}
companion object {
var instance: BaseApp? = null
private set
}
}
| 0
|
Kotlin
|
0
| 0
|
3ede045776e6741a6b14b89d20b11736f2912ec5
| 642
|
StockTicker
|
MIT License
|
openai-client/client/src/commonMain/kotlin/com/xebia/functional/openai/models/CreateChatCompletionRequestModel.kt
|
xebia-functional
| 629,411,216
| false
|
{"Kotlin": 4211913, "TypeScript": 67083, "Mustache": 15021, "CSS": 6570, "Java": 4360, "JavaScript": 1935, "HTML": 395}
|
/**
* Please note: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress("ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport")
package com.xebia.functional.openai.models
import kotlinx.serialization.*
/**
* ID of the model to use. See the
* [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on
* which models work with the Chat API.
*
* Values:
* gptMinus4Minus1106MinusPreview,gptMinus4MinusVisionMinusPreview,gptMinus4,gptMinus4Minus0314,gptMinus4Minus0613,gptMinus4Minus32k,gptMinus4Minus32kMinus0314,gptMinus4Minus32kMinus0613,gptMinus3Period5MinusTurbo,gptMinus3Period5MinusTurboMinus16k,gptMinus3Period5MinusTurboMinus0301,gptMinus3Period5MinusTurboMinus0613,gptMinus3Period5MinusTurboMinus16kMinus0613
*/
@Serializable
enum class CreateChatCompletionRequestModel(val value: kotlin.String) {
@SerialName(value = "gpt-4-1106-preview") gptMinus4Minus1106MinusPreview("gpt-4-1106-preview"),
@SerialName(value = "gpt-4-vision-preview")
gptMinus4MinusVisionMinusPreview("gpt-4-vision-preview"),
@SerialName(value = "gpt-4") gptMinus4("gpt-4"),
@SerialName(value = "gpt-4-0314") gptMinus4Minus0314("gpt-4-0314"),
@SerialName(value = "gpt-4-0613") gptMinus4Minus0613("gpt-4-0613"),
@SerialName(value = "gpt-4-32k") gptMinus4Minus32k("gpt-4-32k"),
@SerialName(value = "gpt-4-32k-0314") gptMinus4Minus32kMinus0314("gpt-4-32k-0314"),
@SerialName(value = "gpt-4-32k-0613") gptMinus4Minus32kMinus0613("gpt-4-32k-0613"),
@SerialName(value = "gpt-3.5-turbo") gptMinus3Period5MinusTurbo("gpt-3.5-turbo"),
@SerialName(value = "gpt-3.5-turbo-16k") gptMinus3Period5MinusTurboMinus16k("gpt-3.5-turbo-16k"),
@SerialName(value = "gpt-3.5-turbo-0301")
gptMinus3Period5MinusTurboMinus0301("gpt-3.5-turbo-0301"),
@SerialName(value = "gpt-3.5-turbo-0613")
gptMinus3Period5MinusTurboMinus0613("gpt-3.5-turbo-0613"),
@SerialName(value = "gpt-3.5-turbo-16k-0613")
gptMinus3Period5MinusTurboMinus16kMinus0613("gpt-3.5-turbo-16k-0613");
/**
* Override [toString()] to avoid using the enum variable name as the value, and instead use the
* actual value defined in the API spec file.
*
* This solves a problem when the variable name and its value are different, and ensures that the
* client sends the correct enum values to the server always.
*/
override fun toString(): kotlin.String = value
companion object {
/** Converts the provided [data] to a [String] on success, null otherwise. */
fun encode(data: kotlin.Any?): kotlin.String? =
if (data is CreateChatCompletionRequestModel) "$data" else null
/** Returns a valid [CreateChatCompletionRequestModel] for [data], null otherwise. */
fun decode(data: kotlin.Any?): CreateChatCompletionRequestModel? =
data?.let {
val normalizedData = "$it".lowercase()
values().firstOrNull { value -> it == value || normalizedData == "$value".lowercase() }
}
}
}
| 40
|
Kotlin
|
11
| 117
|
91b282c6d50aee58b27ad2676eaa77bee4d4036c
| 3,057
|
xef
|
Apache License 2.0
|
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/config/ConfigRetriever.kt
|
Sammers21
| 142,990,532
| true
|
{"Kotlin": 1088656, "Java": 878672, "JavaScript": 76098, "Groovy": 22654, "Ruby": 14717, "FreeMarker": 254}
|
package io.vertx.kotlin.config
import io.vertx.config.ConfigChange
import io.vertx.config.ConfigRetriever
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.coroutines.awaitEvent
import io.vertx.kotlin.coroutines.awaitResult
/**
* Reads the configuration from the different
* and computes the final configuration.
*
* @param completionHandler handler receiving the computed configuration, or a failure if the configuration cannot be retrieved
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.config.ConfigRetriever original] using Vert.x codegen.
*/
suspend fun ConfigRetriever.getConfigAwait() : JsonObject {
return awaitResult{
this.getConfig(it)
}
}
/**
* Registers a listener receiving configuration changes. This method cannot only be called if
* the configuration is broadcasted.
*
* @param listener the listener
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.config.ConfigRetriever original] using Vert.x codegen.
*/
suspend fun ConfigRetriever.listenAwait() : ConfigChange {
return awaitEvent{
this.listen(it)
}
}
| 0
|
Kotlin
|
0
| 0
|
bdf349e87e39aeec85cfbd1a53bae3cb3e420c55
| 1,138
|
vertx-stack-generation
|
Apache License 2.0
|
app/src/main/java/com/dimowner/elections/AppConstants.kt
|
Dimowner
| 173,108,250
| false
| null |
/*
* Copyright 2019 <NAME>
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. The ASF licenses this
* file to you under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.dimowner.elections
class AppConstants {
companion object {
const val APPLICATION_NAME = "Elections"
const val REQUESTS_RECEIVER = "<EMAIL>"
const val LOCAL_DATABASE_NAME = "elections_db"
const val LOADING_TIMEOUT: Long = 120 //seconds
const val TIME_FORMAT_24H = 11
const val TIME_FORMAT_12H = 12
const val SHOW_INSTRUCTIONS_DELAY_MILLS = 800
}
}
| 0
|
Kotlin
|
1
| 1
|
ed6db9c18f1bba0c98bc7e091ea1190e0ff22a0f
| 1,207
|
Elections
|
Apache License 2.0
|
src/main/kotlin/de/davis/gradle/plugin/versioning/VersioningPlugin.kt
|
OffRange
| 805,398,300
| false
|
{"Kotlin": 11720}
|
package de.davis.gradle.plugin.versioning
import com.android.build.api.dsl.ApplicationExtension
import io.github.z4kn4fein.semver.Version
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Provider
import org.gradle.kotlin.dsl.*
import java.util.*
import javax.inject.Inject
class VersioningPlugin @Inject constructor(
private val objectFactory: ObjectFactory,
) : Plugin<Project> {
override fun apply(target: Project): Unit = with(target) {
val ext = extensions.create<VersioningExtension>(VersioningExtension.EXTENSION_NAME, rootDir, objectFactory)
afterEvaluate {
version = ext.computeVersion()
plugins.withId("com.android.application") {
extensions.getByType<ApplicationExtension>().apply {
defaultConfig {
logger.lifecycle("Setting android version")
versionName = version.toString()
versionCode = ext.run { (version as Version).versionCode }.toInt()
}
}
}
addDependencies()
createVersionProviderFile(ext.versionCodeGenerator)
tasks.register<VersionPrinter>("printVersion") {
versionCodeGenerator = ext.versionCodeGenerator
version = target.version as Version
}
}
tasks.register("generateVersionProviderFile") {
description =
"Generates a Kotlin file that provides functions to receive the version of the current project"
group = "versioning"
doLast {
createVersionProviderFile(ext.versionCodeGenerator)
}
}
}
private fun Project.addDependencies() {
val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")
dependencies {
implementation(libs.findLibrary("semantic-versioning").dependencyNotation())
}
}
private fun DependencyHandlerScope.implementation(dependencyNotation: Any) {
add("implementation", dependencyNotation)
}
private fun Optional<Provider<MinimalExternalModuleDependency>>.dependencyNotation() = get().get()
}
| 0
|
Kotlin
|
0
| 0
|
979576b179f64d1bd7971476f42a07d3f0e94eea
| 2,418
|
git-semver-gradle-plugin
|
MIT License
|
feature-detail/src/main/java/com/emrekizil/feature_detail/DetailViewModel.kt
|
emrekizil
| 843,741,704
| false
|
{"Kotlin": 85362}
|
package com.emrekizil.feature_detail
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.emrekizil.core_domain.DeleteMovieUseCase
import com.emrekizil.core_domain.GetMovieDetailByIdUseCase
import com.emrekizil.core_domain.GetSimilarMovieByIdUseCase
import com.emrekizil.core_domain.InsertMovieUseCase
import com.emrekizil.core_model.Movie
import com.emrekizil.core_model.ResponseState
import com.emrekizil.core_model.dto.detail.MovieDetailResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class DetailViewModel @Inject constructor(
private val getSimilarMovieByIdUseCase: GetSimilarMovieByIdUseCase,
private val getMovieDetailByIdUseCase: GetMovieDetailByIdUseCase,
private val getFavoriteMovieUseCase: com.emrekizil.core_domain.GetFavoriteMovieUseCase,
private val insertMovieUseCase: InsertMovieUseCase,
private val deleteMovieUseCase: DeleteMovieUseCase
) : ViewModel() {
private val _detailUiState: MutableStateFlow<MovieDetailScreenUiState> =
MutableStateFlow(MovieDetailScreenUiState.Loading)
val detailUiState: StateFlow<MovieDetailScreenUiState> = _detailUiState.asStateFlow()
private val _similarMovieUiState : MutableStateFlow<List<Movie>> = MutableStateFlow(emptyList())
val similarMovieUiState = _similarMovieUiState.asStateFlow()
fun getMovie(movieId: Int) {
viewModelScope.launch {
combine(
getMovieDetailByIdUseCase(movieId),
getFavoriteMovieUseCase()
) { movieResponseState, favoriteMovies ->
when (movieResponseState) {
is ResponseState.Error -> {
_detailUiState.update {
MovieDetailScreenUiState.Error(movieResponseState.message)
}
}
ResponseState.Loading -> {
_detailUiState.update {
MovieDetailScreenUiState.Loading
}
}
is ResponseState.Success -> {
val isFavorite = favoriteMovies.any { it.id == movieResponseState.data.id }
_detailUiState.update {
MovieDetailScreenUiState.Success(
MovieUiState(
id = movieResponseState.data.id!!,
overview = movieResponseState.data.overview!!,
backdropPath = movieResponseState.data.getPosterImageUrl(),
genres = movieResponseState.data.genres?.map {
it?.name!!
} ?: listOf(""),
voteAverage = movieResponseState.data.getRatingRounded(),
title = movieResponseState.data.title!!,
releaseDate = movieResponseState.data.releaseDate!!,
isFavorite = isFavorite,
onFavorite = {
changeFavoriteMovieState(
movieResponseState.data,
isFavorite
)
}
)
)
}
}
}
}.collect()
}
}
fun getSimilarMovie(movieId: Int) {
viewModelScope.launch {
getSimilarMovieByIdUseCase(movieId).collectLatest { response->
when (response) {
is ResponseState.Success -> {
_similarMovieUiState.update {
response.data
}
}
is ResponseState.Error -> {}
is ResponseState.Loading -> {}
}
}
}
}
private fun changeFavoriteMovieState(data: MovieDetailResponse, favorite: Boolean) {
viewModelScope.launch {
if (favorite){
deleteMovieUseCase(data.toMovieDetail())
} else {
insertMovieUseCase(data.toMovieDetail())
}
}
}
}
sealed class MovieDetailScreenUiState {
data object Loading : MovieDetailScreenUiState()
data class Error(val message: String) : MovieDetailScreenUiState()
data class Success(val data: MovieUiState) : MovieDetailScreenUiState()
}
data class MovieUiState(
val id: Int,
val overview: String,
val backdropPath: String,
val genres: List<String>,
val voteAverage: Double,
val title: String,
val releaseDate: String,
val isFavorite: Boolean,
val onFavorite: () -> Unit
)
| 0
|
Kotlin
|
0
| 0
|
a7fb637eb173e1d8c8b57821a226480fe4284e57
| 5,328
|
MovieApp
|
Apache License 2.0
|
app/src/main/java/com/example/pokedek/presentasion/fragment/item/ItemFragment.kt
|
Alstonargodi
| 442,473,206
| false
| null |
package com.example.pokedek.presentasion.fragment.item
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.pokedek.model.local.entity.Item.ItemList
import com.example.pokedek.presentasion.fragment.item.adapter.Itemrvadapter
import com.example.pokedek.presentasion.viewmodel.remote.ItemViewModel
import com.example.pokedek.databinding.FragmentItemBinding
class ItemFragment : Fragment() {
private val itemViewModel by viewModels<ItemViewModel>()
lateinit var binding : FragmentItemBinding
lateinit var adapter : Itemrvadapter
private var Itemlistsum = ArrayList<ItemList>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentItemBinding.inflate(layoutInflater)
val view = binding.root
Itemlistsum = arrayListOf()
adapter = Itemrvadapter()
val recview = binding.Recviewitem
recview.adapter = adapter
recview.layoutManager = LinearLayoutManager(requireContext())
binding.btnItemsort.setOnClickListener {
binding.Sortlayout.visibility =
if (binding.Sortlayout.visibility == View.GONE)
View.VISIBLE
else
View.GONE
}
binding.Itemspinner.onItemSelectedListener = object : AdapterView.OnItemClickListener , AdapterView.OnItemSelectedListener{
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
val position = p0?.getItemAtPosition(p2)
when(position){
"all"->{
Itemlistsum.clear()
readitem("",10)
}
"Berries"->{
Itemlistsum.clear()
readitem("medicine",10000)
}
"Pokeballs"->{
Itemlistsum.clear()
readitem("balls",10000)
}
}
}
override fun onNothingSelected(p0: AdapterView<*>?) {
readitem("",10)
}
}
readitem("",10)
return view
}
fun readitem(cari: String,item : Int){
binding.itemprogressbar.visibility = View.VISIBLE
// itemViewModel.getListItem(0,item)
// itemViewModel.itemListRespon.observe(viewLifecycleOwner, Observer { responlist ->
// try {
// if (responlist.isSuccessful){
// val data = responlist.body()?.berryListResults
// for (i in data!!.indices){
// val nama = data[i].name
//
// itemViewModel.getSummaryItem(nama)
// itemViewModel.itemSumRespon.observe(viewLifecycleOwner, Observer { responsum ->
// try {
// if (responsum.isSuccessful){
//
// val name = responsum.body()?.name.toString()
// val type = responsum.body()?.category?.name.toString()
//
// val fetch = ItemList(
// responsum.body()?.name.toString(),
// responsum.body()?.sprites?.default.toString(),
// responsum.body()?.category?.name.toString(),
// responsum.body()?.effectEntries?.get(0)?.effect.toString()
// )
//
// if(type.contains(cari)){
// Itemlistsum.add(fetch)
// adapter.setdata(Itemlistsum)
// binding.itemprogressbar.visibility = View.GONE
// }else if (cari.isEmpty()){
// Itemlistsum.add(fetch)
// adapter.setdata(Itemlistsum)
// binding.itemprogressbar.visibility = View.GONE
// }
//
// }else{
// Log.d("itemsum","cannot fetch data")
// }
// }catch (e : Exception){
// Log.d("itemsum",e.toString())
// }
// })
// }
// }else{
// Log.d("itemlist","cannot fetch data")
// }
// }catch (e : Exception){
// Log.d("itemlist",e.toString())
// }
// })
}
}
| 0
|
Kotlin
|
0
| 0
|
a548138a792ff8d4954328553f3100f28fec6525
| 5,206
|
Pokedex
|
Apache License 2.0
|
app/src/main/java/com/sakethh/arara/unreleased/currentMusicScreen/CurrentUnreleasedMusicScreen.kt
|
sakethpathike
| 517,053,630
| false
| null |
package com.sakethh.arara.unreleased.currentMusicScreen
import android.annotation.SuppressLint
import androidx.activity.compose.BackHandler
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.BottomSheetScaffoldState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.request.ImageRequest
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.sakethh.arara.R
import com.sakethh.arara.randomLostInternetImg
import com.sakethh.arara.ui.theme.*
import com.sakethh.arara.unreleased.ImageThing
import com.sakethh.arara.SharedViewModel
import com.sakethh.arara.unreleased.UnreleasedViewModel
import com.sakethh.arara.unreleased.UnreleasedViewModel.UnreleasedUtils.mediaPlayer
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun UnreleasedCurrentMusicScreen(
sharedViewModel: SharedViewModel,
navController: NavHostController,
scaffoldState: BottomSheetScaffoldState
) {
BackHandler {
sharedViewModel.isBottomNavVisible.value = true
navController.navigate("unreleased") {
popUpTo(0)
}
}
sharedViewModel.isBottomNavVisible.value = false
val systemUIController = rememberSystemUiController()
val coroutineScope = rememberCoroutineScope()
val currentMusicScreenViewModel: CurrentMusicScreenViewModel = viewModel()
LaunchedEffect(key1 = coroutineScope) {
coroutineScope.launch {
delay(100)
systemUIController.setStatusBarColor(color = md_theme_dark_surface)
}
}
MaterialTheme(typography = Typography) {
val startAndEndPadding = 20.dp
val constraintsSet = ConstraintSet {
val topBar = createRefFor("topBar")
val artWork = createRefFor("artWork")
val titleAndIconAndDescription = createRefFor("titleAndIconAndDescription")
val titleAndIcon = createRefFor("titleAndIcon")
val descriptionText = createRefFor("descriptionText")
val topSpaceHeader = createRefFor("topSpaceHeader")
val progressBarSpacer = createRefFor("progressBarSpacer")
val progressBarBox = createRefFor("progressBarBox")
val progressBar = createRefFor("progressBar")
val lyricsBox = createRefFor("lyricsBox")
constrain(topBar) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(topSpaceHeader) {
top.linkTo(topBar.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(artWork) {
top.linkTo(topSpaceHeader.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(titleAndIconAndDescription.top)
}
constrain(titleAndIconAndDescription) {
top.linkTo(artWork.bottom)
bottom.linkTo(lyricsBox.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(titleAndIcon) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(descriptionText) {
top.linkTo(titleAndIcon.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
constrain(progressBarSpacer) {
top.linkTo(titleAndIconAndDescription.bottom)
start.linkTo(titleAndIconAndDescription.start)
end.linkTo(titleAndIconAndDescription.end)
}
constrain(progressBarBox) {
top.linkTo(progressBarSpacer.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(progressBar) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(progressBarBox) {
top.linkTo(progressBarSpacer.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
constrain(lyricsBox) {
top.linkTo(progressBarBox.bottom)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
}
ConstraintLayout(
constraintSet = constraintsSet,
modifier = Modifier
.fillMaxSize()
.background(md_theme_dark_surface)
.verticalScroll(state = rememberScrollState(), enabled = true)
.animateContentSize()
.padding(bottom = 150.dp)
) {
SmallTopAppBar(
modifier = Modifier.layoutId("topBar"),
title = {},
colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = md_theme_dark_surface),
navigationIcon = {
IconButton(
onClick = {
navController.navigate("unreleased")
}, modifier = Modifier
.padding(start = 15.dp)
.size(30.dp)
) {
Image(
painter = painterResource(id = R.drawable.arrow_right),
contentDescription = null,
modifier = Modifier
.size(30.dp)
.rotate(180f)
)
}
}, actions = {
val image = remember { mutableListOf(0) }
val mediaIcons = currentMusicScreenViewModel.currentImageGifIcons
if (currentMusicScreenViewModel.currentIsImageIcon.value) {
image[0] = mediaIcons[0]
} else {
image[0] = mediaIcons[1]
}
IconButton(
onClick = {
currentMusicScreenViewModel.currentIsImageIcon.value =
!currentMusicScreenViewModel.currentIsImageIcon.value
}
) {
Image(
painter = painterResource(id = image[0]),
contentDescription = "gif/image can be selected from here",
modifier = Modifier.size(30.dp)
)
}
}
)
Spacer(
Modifier
.fillMaxWidth()
.height(50.dp)
.layoutId("topSpaceHeader")
)
ImageThing(
model = ImageRequest.Builder(LocalContext.current)
.data(sharedViewModel.dataForCurrentMusicScreen.value?.currentImgUrl)
.crossfade(true)
.build(),
contentDescription = "Image Of Current Music Which is Playing",
modifier = Modifier
.requiredSize(300.dp)
.layoutId("artWork")
.shadow(2.dp),
onError = painterResource(id = randomLostInternetImg())
)
BoxWithConstraints(
modifier = Modifier
.padding(start = startAndEndPadding, end = startAndEndPadding)
.fillMaxWidth()
.wrapContentHeight()
.layoutId("titleAndIconAndDescription")
.animateContentSize()
) {
ConstraintLayout(constraintSet = constraintsSet) {
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.layoutId("titleAndIcon")
) {
Box(
modifier = Modifier
.requiredWidthIn(min = 250.dp)
.wrapContentHeight(),
contentAlignment = Alignment.CenterStart
) {
Text(
text = sharedViewModel.dataForCurrentMusicScreen.value?.currentSongName!!,
style = MaterialTheme.typography.titleMedium,
color = md_theme_dark_onSurface,
maxLines = 1,
fontSize = 20.sp,
overflow = TextOverflow.Ellipsis
)
}
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
contentAlignment = Alignment.CenterEnd
) {
IconButton(onClick = {
currentMusicScreenViewModel.descriptionButtonClicked.value =
!currentMusicScreenViewModel.descriptionButtonClicked.value
}, modifier = Modifier.size(25.dp)) {
if (currentMusicScreenViewModel.descriptionButtonClicked.value) {
Image(
painter = painterResource(id = R.drawable.dropdown),
contentDescription = "Description",
modifier = Modifier
.rotate(180f)
.animateContentSize()
)
} else {
Image(
painter = painterResource(id = R.drawable.dropdown),
contentDescription = "Description"
)
}
}
}
}
if (currentMusicScreenViewModel.descriptionButtonClicked.value) {
Text(
text = "${sharedViewModel.dataForCurrentMusicScreen.value?.songDescription}\n\nDescription Via:- ${sharedViewModel.dataForCurrentMusicScreen.value?.descriptionBy} from ${sharedViewModel.dataForCurrentMusicScreen.value?.descriptionOrigin}.\nArtwork stolen from ${sharedViewModel.dataForCurrentMusicScreen.value?.artworkBy}:)",
fontSize = 16.sp,
lineHeight = 20.sp,
color = md_theme_dark_onSurface,
style = MaterialTheme.typography.bodySmall,
textAlign = TextAlign.Start,
modifier = Modifier
.padding(top = 5.dp)
.layoutId("descriptionText")
)
}
}
}
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(5.dp)
.layoutId("progressBarSpacer")
)
BoxWithConstraints(
modifier = Modifier
.padding(start = startAndEndPadding, end = startAndEndPadding, top = 5.dp)
.fillMaxWidth()
.wrapContentHeight()
.animateContentSize()
.layoutId("progressBarBox")
) {
ConstraintLayout(
constraintSet = constraintsSet, modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
if (currentMusicScreenViewModel.isMusicPlaying().collectAsState(initial = false).value as Boolean && !scaffoldState.bottomSheetState.isCollapsed) {
Slider(
value = currentMusicScreenViewModel.currentDurationFloatFlow().collectAsState(initial = 0f).value.toString()
.toFloat(),
onValueChange = {
mediaPlayer.seekTo(it.toInt())
},
valueRange = 0f..mediaPlayer.duration.toFloat(),
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.layoutId("progressBar"),
colors = SliderDefaults.colors(
thumbColor = md_theme_dark_onSurface,
activeTrackColor = md_theme_dark_onSurface,
inactiveTrackColor = md_theme_dark_secondary
)
)
}
Box(
modifier = Modifier
.padding(top = 15.dp)
.fillMaxWidth()
.wrapContentHeight(),
contentAlignment = Alignment.CenterStart
) {
Text(
text = currentMusicScreenViewModel.currentDurationFlow().collectAsState(initial = "00:00").value.toString(),
fontSize = 12.sp,
style = MaterialTheme.typography.bodySmall,
color = md_theme_dark_onSurface,
fontWeight = FontWeight.SemiBold,
modifier = Modifier
.padding(top = 26.dp)
)
}
Box(
modifier = Modifier
.padding(top = 15.dp)
.fillMaxWidth()
.wrapContentHeight(),
contentAlignment = Alignment.CenterEnd
) {
Text(
text = currentMusicScreenViewModel.actualDuration().collectAsState(initial = "00:00").value.toString(),
fontSize = 12.sp,
style = MaterialTheme.typography.bodySmall,
color = md_theme_dark_onSurface,
fontWeight = FontWeight.SemiBold,
modifier = Modifier
.padding(top = 26.dp)
)
}
}
}
// lyrics thing:
Box(
modifier = Modifier
.padding(
top = 35.dp,
bottom = 0.dp,
start = startAndEndPadding,
end = startAndEndPadding
)
.fillMaxWidth()
.height(350.dp)
.background(md_theme_dark_onSecondary, shape = RoundedCornerShape(10.dp))
.layoutId("lyricsBox")
) {
Text(
modifier = Modifier.padding(start = 15.dp, top = 15.dp),
text = "LYRICS",
textAlign = TextAlign.Start,
style = MaterialTheme.typography.titleMedium,
color = md_theme_dark_secondary
)
Column(
modifier = Modifier
.padding(start = 15.dp, end = 25.dp, bottom = 20.dp)
.fillMaxWidth()
.fillMaxHeight()
.padding(top = 45.dp)
.verticalScroll(
rememberScrollState()
)
) {
Text(
fontSize = 25.sp,
text = sharedViewModel.dataForCurrentMusicScreen.value?.currentLyrics!!.toString(),
textAlign = TextAlign.Start,
lineHeight = 30.sp,
style = MaterialTheme.typography.titleMedium,
color = md_theme_dark_secondary
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d0bffe832b47f6fac7d85831192a5a26e73158c0
| 18,161
|
arara-android
|
MIT License
|
src/com/oscuro/oscurojs/core/messaging/InboundMessage.kt
|
oscurojs
| 219,148,868
| false
|
{"JavaScript": 381005, "Kotlin": 91620, "HTML": 2123, "Shell": 135}
|
/*
MIT License
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.oscuro.oscurojs.core.messaging
import com.oscuro.oscurojs.core.events.EventDispatcher
import com.oscuro.oscurojs.core.events.Subscribable
import kotlin.js.Promise
/**
* This is a message stream reader, which can be used to read the whole message if desired, asynchronously or
* use the callback style to read each message's parameter.
*/
class InboundMessage(private val rl: dynamic, val fieldCount: Int, val command: String, val version: String)
: Subscribable<Pair<String, String>, Unit>
{
companion object {
private val fieldRegex = "([^:]+?) *: *(.*)".toRegex()
}
init {
rl.on("line", ::onLine)
}
private fun onLine(line: String) {
val result = fieldRegex.matchEntire(line) ?: return
val values = result.groupValues
if (values.size != 3) throw Error("Bad match ${result.groupValues}")
val (_, key, value) = values
consumed++
events.dispatch(Pair(key, value))
if (ended) rl.off("line", ::onLine)
}
private var consumed = 0
val ended get() = consumed >= fieldCount
private val events = EventDispatcher<Pair<String, String>, Unit>()
override fun add(listener: (event: Pair<String, String>) -> Unit) = events.add(listener)
override fun remove(listener: (event: Pair<String, String>) -> Unit) = events.remove(listener)
fun readAsync(): Promise<Message> {
return Promise { resolve, reject ->
if (ended) reject(Error("Message already consumed!"))
val pairs = mutableMapOf<String, String>()
add { (key, value) ->
pairs[key] = value
if (ended) {
resolve(Message(command, version, pairs.toMap()))
}
}
}
}
}
| 3
|
JavaScript
|
0
| 0
|
937f83770909cbbea3cb7fd6c7f7be926bb017dc
| 2,872
|
oscuro-js
|
MIT License
|
src/main/kotlin/mod/chloeprime/elytrabooster/common/util/RichTextSugar.kt
|
ChloePrime
| 369,410,062
| false
| null |
package mod.chloeprime.elytrabooster.common.util
import net.minecraft.network.chat.*
import java.util.*
import java.util.function.UnaryOperator
/**
* @UE4
*/
@Suppress("FunctionName")
fun TEXT(string: String): MutableComponent =
if(string.isEmpty()) EMPTY_TEXT else TextComponent(string)
/**
* 空字符串对应的TextComponent
*/
private val EMPTY_TEXT = TextComponent("")
/**
* 更简洁地构建翻译字符串
*/
fun translated(langKey: String): MutableComponent =
if (langKey.isEmpty()) EMPTY_TEXT else TranslatableComponent(langKey)
fun translated(langKey: String, vararg args: Any) =
TranslatableComponent(langKey, *args)
/**
* 针对MC富文本的字符串加法
*/
operator fun Component.plus(other: Component): Component =
this.cast().append(other)
/**
* 针对MC富文本的字符串加法
* 忽视空字符串
*/
operator fun Component.plus(other: String): Component {
if (other.isEmpty()) return this.cast()
return this.cast().append(other)
}
fun Component.withColor(c: Int): Component =
this.cast().withStyle { it.withColor(TextColor.fromRgb(c)) }
fun Component.applyStyle(action: StylePipeline.() -> Unit): Component {
val pipeline = StylePipeline()
pipeline.action()
return this.cast().withStyle(pipeline)
}
class StylePipeline internal constructor(): UnaryOperator<Style> {
fun setColor(c: Int) = pipeline.add {
it.withColor(TextColor.fromRgb(c))
}
fun setBold(b: Boolean?) = pipeline.add {
it.withBold(b)
}
fun setItalic(b: Boolean?) = pipeline.add {
it.withItalic(b)
}
fun setUnderlined(b: Boolean?) = pipeline.add {
it.withUnderlined(b)
}
fun setStrikethrough(b: Boolean?) = pipeline.add {
it.withStrikethrough(b)
}
fun setObfuscated(b: Boolean?) = pipeline.add {
it.withObfuscated(b)
}
private val pipeline = LinkedList<(Style) -> Style>()
override fun apply(p1: Style): Style {
var result = p1
pipeline.forEach {
result = it(result)
}
return result
}
}
private fun Component.cast(): MutableComponent =
if (this is MutableComponent) this
else TextComponent("").append(this)
| 1
|
Kotlin
|
0
| 2
|
6751b17bc3b77bf816b4db0c223d86a53d3f96db
| 2,133
|
ElytraBooster
|
MIT License
|
app/src/main/kotlin/uk/lobsterdoodle/namepicker/ui/OverviewCard.kt
|
fifersheep
| 21,071,767
| false
| null |
package uk.lobsterdoodle.namepicker.ui
import android.content.Context
import android.support.v4.content.ContextCompat.getColor
import android.support.v7.widget.CardView
import android.support.v7.widget.PopupMenu
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MenuItem
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import uk.lobsterdoodle.namepicker.R
import uk.lobsterdoodle.namepicker.application.util.As
import uk.lobsterdoodle.namepicker.overview.OverviewCardActionsCallback
import uk.lobsterdoodle.namepicker.overview.OverviewCardCellData
class OverviewCard : CardView {
@BindView(R.id.overview_card_title) lateinit var title: TextView
@BindView(R.id.overview_card_count) lateinit var count: TextView
@BindView(R.id.overview_card_overflow) lateinit var overflow: ImageView
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
init {
ButterKnife.bind(this, LayoutInflater.from(context).inflate(R.layout.overview_card, this, true))
setCardBackgroundColor(getColor(context, android.R.color.white))
useCompatPadding = true
cardElevation = As.px(context, 2).toFloat()
}
fun bind(callback: OverviewCardActionsCallback, data: OverviewCardCellData) {
title.text = data.listTitle
count.text = "${data.nameCount} names"
setOnClickListener { callback.launchSelectionScreen(data.groupId) }
val popup = PopupMenu(context, overflow)
popup.inflate(R.menu.menu_overview_card)
popup.setOnMenuItemClickListener { item ->
handle(item, data, callback)
true
}
overflow.setOnClickListener { popup.show() }
}
private fun handle(item: MenuItem, data: OverviewCardCellData, callback: OverviewCardActionsCallback) {
when (item.itemId) {
R.id.overview_card_overflow_edit_names -> callback.launchEditGroupNamesScreen(data.groupId)
R.id.overview_card_overflow_edit_group -> callback.launchEditGroupDetailsScreen(data.groupId)
R.id.overview_card_overflow_delete_group -> callback.deleteGroup(data.groupId)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
94e3776e3515f4ce7192c9199d87fe4f368f7355
| 2,413
|
android-names-in-a-hat
|
Apache License 2.0
|
coil-base/src/main/java/coil/memory/HardwareBitmapService.kt
|
hansenji
| 206,822,775
| true
|
{"Kotlin": 305721, "IDL": 2767, "Shell": 2591}
|
package coil.memory
import android.graphics.Bitmap
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.O
import android.os.Build.VERSION_CODES.O_MR1
import android.util.Log
import androidx.annotation.WorkerThread
import coil.size.PixelSize
import coil.size.Size
import coil.util.log
import java.io.File
/** Decides if a request can use [Bitmap.Config.HARDWARE]. */
internal sealed class HardwareBitmapService {
companion object {
operator fun invoke(): HardwareBitmapService {
return if (SDK_INT == O || SDK_INT == O_MR1) {
LimitedFileDescriptorHardwareBitmapService
} else {
EmptyHardwareBitmapService
}
}
}
/** Return true if we can currently use [Bitmap.Config.HARDWARE]. */
abstract fun allowHardware(size: Size): Boolean
}
/** A no-op [HardwareBitmapService], which always returns true. */
private object EmptyHardwareBitmapService : HardwareBitmapService() {
override fun allowHardware(size: Size) = true
}
/**
* Android O and O_MR1 have a limited number of file descriptors (1024) per-process.
* This limit was increased to a safe number in Android P (32768). Each hardware bitmap
* allocation consumes, on average, 2 file descriptors. In addition, other non-image loading
* operations can use file descriptors, which increases competition for these resources.
* This class exists to disable [Bitmap.Config.HARDWARE] allocation if this process gets
* too close to the limit, as passing the limit can cause crashes and/or rendering issues.
*
* NOTE: This must be a singleton since it tracks global file descriptor usage state for the entire process.
*
* Modified from Glide's HardwareConfigState.
*/
private object LimitedFileDescriptorHardwareBitmapService : HardwareBitmapService() {
private const val TAG = "LimitedFileDescriptorHardwareBitmapService"
private const val MIN_SIZE_DIMENSION = 100
private const val FILE_DESCRIPTOR_LIMIT = 750
private const val FILE_DESCRIPTOR_CHECK_INTERVAL = 50
private val fileDescriptorList = File("/proc/self/fd")
@Volatile private var decodesSinceLastFileDescriptorCheck = 0
@Volatile private var hasAvailableFileDescriptors = true
override fun allowHardware(size: Size): Boolean {
// Don't use up file descriptors on small bitmaps.
if (size is PixelSize && (size.width < MIN_SIZE_DIMENSION || size.height < MIN_SIZE_DIMENSION)) {
return false
}
return hasAvailableFileDescriptors()
}
@Synchronized
@WorkerThread
private fun hasAvailableFileDescriptors(): Boolean {
// Only check if we have available file descriptors after a
// set amount of decodes since it's expensive (1-2 milliseconds).
if (decodesSinceLastFileDescriptorCheck++ >= FILE_DESCRIPTOR_CHECK_INTERVAL) {
decodesSinceLastFileDescriptorCheck = 0
val numUsedFileDescriptors = fileDescriptorList.list().count()
hasAvailableFileDescriptors = numUsedFileDescriptors < FILE_DESCRIPTOR_LIMIT
if (hasAvailableFileDescriptors) {
log(TAG, Log.WARN) {
"Unable to allocate more hardware bitmaps. Number of used file descriptors: $numUsedFileDescriptors"
}
}
}
return hasAvailableFileDescriptors
}
}
| 0
| null |
0
| 0
|
f7264b38d24b4a3f05af8df1b0493fd161cbeec8
| 3,405
|
coil
|
Apache License 2.0
|
wrapper-dsl/src/main/kotlin/com/ooooonly/mybatisplus/dsl/KtQUpdateWrapperDslBuilder.kt
|
only52607
| 344,524,252
| false
| null |
package com.ooooonly.mybatisplus.dsl
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
/**
* ClassName: KtQUpdateWrapperDslBuilder
* Description:
* date: 2021/3/8 21:30
* @author ooooonly
* @version
*/
class KtUpdateWrapperDslBuilder<T : Any>(baseWrapper: KtUpdateWrapper<T>) : AbstractKtWrapperDslBuilder<T, KtUpdateWrapper<T>, KtUpdateWrapperDslBuilder<T>>(
baseWrapper
) {
override fun newInstance(baseWrapper: KtUpdateWrapper<T>): KtUpdateWrapperDslBuilder<T> = KtUpdateWrapperDslBuilder(baseWrapper)
infix fun set(sql: String){
baseWrapper.setSql(sql)
}
}
| 0
|
Kotlin
|
0
| 4
|
189222dbbaf75bff03d78aa769151aa58b46527b
| 607
|
mybatis-plus-ktx
|
Apache License 2.0
|
verik-compiler/src/main/kotlin/io/verik/compiler/target/declaration/TargetClass.kt
|
frwang96
| 269,980,078
| false
| null |
/*
* Copyright (c) 2021 Francis Wang
*
* 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 io.verik.compiler.target.declaration
import io.verik.compiler.ast.element.common.EElement
import io.verik.compiler.ast.property.Type
import io.verik.compiler.serialize.source.SerializedType
import io.verik.compiler.serialize.source.TypeSerializer
import io.verik.compiler.target.common.CompositeTargetClassDeclaration
import io.verik.compiler.target.common.PrimitiveTargetClassDeclaration
import io.verik.compiler.target.common.TargetPackage
import io.verik.compiler.target.common.TargetScope
object TargetClass : TargetScope(TargetPackage) {
val C_Void = object : PrimitiveTargetClassDeclaration(parent, "Void") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
return SerializedType("void")
}
}
val C_Int = object : PrimitiveTargetClassDeclaration(parent, "Int") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
return SerializedType("int")
}
}
val C_Boolean = object : PrimitiveTargetClassDeclaration(parent, "Boolean") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
return SerializedType("logic")
}
}
val C_String = object : PrimitiveTargetClassDeclaration(parent, "String") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
return SerializedType("string")
}
}
val C_Ubit = object : PrimitiveTargetClassDeclaration(parent, "Ubit") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
val value = typeArguments[0].asCardinalValue(element)
return SerializedType("logic", "[${value - 1}:0]", null)
}
}
val C_Sbit = object : PrimitiveTargetClassDeclaration(parent, "Sbit") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
val value = typeArguments[0].asCardinalValue(element)
return SerializedType("logic signed", "[${value - 1}:0]", null)
}
}
val C_Packed = object : PrimitiveTargetClassDeclaration(parent, "Packed") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
val serializedType = TypeSerializer.serialize(typeArguments[1], element)
var packedDimension = "[${typeArguments[0].asCardinalValue(element) - 1}:0]"
if (serializedType.packedDimension != null)
packedDimension += serializedType.packedDimension
return SerializedType(serializedType.base, packedDimension, serializedType.unpackedDimension)
}
}
val C_Unpacked = object : PrimitiveTargetClassDeclaration(parent, "Unpacked") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
val serializedType = TypeSerializer.serialize(typeArguments[1], element)
var unpackedDimension = "[${typeArguments[0].asCardinalValue(element) - 1}:0]"
if (serializedType.unpackedDimension != null)
unpackedDimension += serializedType.unpackedDimension
return SerializedType(serializedType.base, serializedType.packedDimension, unpackedDimension)
}
}
val C_Time = object : PrimitiveTargetClassDeclaration(parent, "Time") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
return SerializedType("time")
}
}
val C_Event = object : PrimitiveTargetClassDeclaration(parent, "Event") {
override fun serializeType(typeArguments: List<Type>, element: EElement): SerializedType {
return SerializedType("event")
}
}
val C_ArrayList = CompositeTargetClassDeclaration(
parent,
"ArrayList",
"class ArrayList #(type E = int);",
"E queue [${'$'}];",
"endclass : ArrayList"
)
}
| 0
|
Kotlin
|
1
| 5
|
f11e0e7404d0461ec8b8c5d5635b2a4f6278a1f6
| 4,656
|
verik
|
Apache License 2.0
|
src/main/kotlin/com/example/models/Biblioteca.kt
|
natalyaaragao
| 770,999,928
| false
|
{"Kotlin": 52544, "JavaScript": 25320, "CSS": 6508, "HTML": 361}
|
package com.example.models
import com.example.responses.BibliotecaResponse
import kotlinx.serialization.Serializable
@Serializable
data class Biblioteca(
val idBiblioteca: Int,
val nome: String,
val horarioFuncionamento: String,
val telefone: String,
val email: String,
val site: String,
val assuntos: String,
val areaConhecimento: String,
val recursos: String,
val rua: String,
val numero: Int,
val bairro: String,
val cidade: String,
val estado: String,
val cep: Int
)
fun Biblioteca.toBibliotecaResponse(): BibliotecaResponse {
return BibliotecaResponse(
idBiblioteca = idBiblioteca,
nome = nome,
horarioFuncionamento = horarioFuncionamento,
telefone = telefone,
email = email,
site = site,
assuntos = assuntos,
areaConhecimento = areaConhecimento,
recursos = recursos,
rua = rua,
numero = numero,
bairro = bairro,
cidade = cidade,
estado = estado,
cep = cep
)
}
| 7
|
Kotlin
|
0
| 0
|
6ac88d8a861b1b04ee36eecce92a3d996e7a7882
| 1,011
|
library-system
|
MIT License
|
domain/src/main/java/org/watsi/enrollment/domain/repositories/AdministrativeDivisionRepository.kt
|
Meso-Health
| 227,515,211
| false
| null |
package org.watsi.enrollment.domain.repositories
import io.reactivex.Completable
import io.reactivex.Flowable
import org.watsi.enrollment.domain.entities.AdministrativeDivision
interface AdministrativeDivisionRepository {
fun allWithLevel(level: String): Flowable<List<AdministrativeDivision>>
fun fetch(): Completable
fun deleteAll(): Completable
}
| 0
|
Kotlin
|
3
| 1
|
bba562b15e5e34d3239f417c45c6ec4755510c68
| 364
|
meso-enrollment
|
Apache License 2.0
|
app/src/main/java/antuere/how_are_you/di/AppModule.kt
|
antuere
| 526,507,044
| false
| null |
package antuere.how_are_you.di
import android.content.Context
import antuere.how_are_you.R
import antuere.how_are_you.presentation.base.ui_biometric_dialog.UIBiometricDialog
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
fun provideTransitionName(@ApplicationContext context: Context): String {
return context.getString(R.string.transition_name)
}
// @Provides
// @Singleton
// fun provideGlide(@ApplicationContext context: Context): RequestManager {
// return Glide.with(context)
// .setDefaultRequestOptions(
// RequestOptions()
// .circleCrop()
// .skipMemoryCache(true)
// .diskCacheStrategy(DiskCacheStrategy.NONE)
// .placeholder(R.drawable.cat_placeholder)
// .error(R.drawable.cat_black)
// )
// }
@Provides
@Singleton
fun provideFirebaseAuth(): FirebaseAuth {
return FirebaseAuth.getInstance()
}
@Provides
@Singleton
fun provideGoogleSignInClient(@ApplicationContext context: Context): GoogleSignInClient {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
.requestEmail()
.build()
return GoogleSignIn.getClient(context, gso)
}
@Provides
@Singleton
fun provideMyBiometricManager(
@ApplicationContext context: Context,
): UIBiometricDialog {
return UIBiometricDialog(context)
}
}
| 1
|
Kotlin
|
1
| 0
|
e4aaf07995c61026b296243fe7b9c629e0c5223e
| 2,057
|
HowAreYou
|
Apache License 2.0
|
sample/navigation/src/main/kotlin/com/turo/nibel/sample/navigation/FeatureCNavigation.kt
|
open-turo
| 667,584,375
| false
|
{"Kotlin": 102457}
|
package com.turo.nibel.sample.navigation
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import nibel.annotations.DestinationWithArgs
@Parcelize
data class FourthArgs(val inputText: String) : Parcelable
data class FourthScreenDestination(override val args: FourthArgs) : DestinationWithArgs<FourthArgs>
| 1
|
Kotlin
|
1
| 79
|
e66f29f9030fd6818d9cd2c15a78fc62c0885a23
| 322
|
nibel
|
MIT License
|
app/src/main/java/com/shinwan2/postmaker/util/BindingAdapters.kt
|
shinwan2
| 155,159,532
| false
| null |
package com.shinwan2.postmaker.util
import android.databinding.BindingAdapter
import android.support.design.widget.TextInputLayout
import android.support.v4.widget.SwipeRefreshLayout
import android.view.View
import android.view.ViewGroup
import java.util.ArrayDeque
@BindingAdapter("errorText")
fun setErrorMessage(view: TextInputLayout, errorMessage: String?) {
view.error = errorMessage
}
@BindingAdapter("isVisible")
fun setVisible(view: View, isVisible: Boolean?) {
view.visibility = if (isVisible == true) View.VISIBLE else View.GONE
}
@BindingAdapter("isRecursiveEnabled")
fun setRecursiveEnabled(view: View, isEnabled: Boolean?) {
val inspectedViews = ArrayDeque(listOf(view))
while (!inspectedViews.isEmpty()) {
val inspectedView = inspectedViews.poll()
inspectedView.isEnabled = isEnabled == true
if (inspectedView is ViewGroup) {
(0 until inspectedView.childCount).mapTo(inspectedViews) {
inspectedView.getChildAt(it)
}
}
}
}
@BindingAdapter("isRefreshing")
fun setRefreshing(view: SwipeRefreshLayout, isRefreshing: Boolean?) {
view.isRefreshing = isRefreshing ?: false
}
| 0
|
Kotlin
|
0
| 1
|
e8cf85907ee254f1c6234620a2f7be3e29b660f5
| 1,183
|
PostMaker
|
Apache License 2.0
|
KirraDungeonClient/src/main/kotlin/net/sakuragame/eternal/kirradungeon/client/compat/dragoncore/DungeonAPI.kt
|
Eternalland-Server
| 569,813,142
| false
| null |
package net.sakuragame.eternal.kirradungeon.client.compat.dragoncore
import com.google.common.collect.Lists
import com.taylorswiftcn.megumi.uifactory.generate.function.SubmitParams
import ink.ptms.zaphkiel.ZaphkielAPI
import net.sakuragame.eternal.dragoncore.network.PacketSender
import net.sakuragame.eternal.kirradungeon.client.KirraDungeonClient
import net.sakuragame.eternal.kirradungeon.client.compat.dragoncore.data.DungeonCategory
import net.sakuragame.eternal.kirradungeon.client.compat.dragoncore.data.screen.DungeonScreen
import net.sakuragame.eternal.kirradungeon.client.compat.dragoncore.data.screen.DungeonSubScreen
import net.sakuragame.eternal.kirradungeon.client.zone.Zone
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
object DungeonAPI {
const val triggerKey = "K"
enum class ParamType {
UPDATE, JOIN, CLOSE, PAGE
}
fun getDefaultScreen() = DungeonLoader.parentScreens[DungeonCategory.NORMAL]!![0]
fun getDefaultSubScreen(screen: DungeonScreen?): DungeonSubScreen {
if (screen == null) return getDefaultScreen().dungeonSubScreens[0]!!
return screen.dungeonSubScreens.values.find { it?.forceEmpty == false } ?: getDefaultScreen().dungeonSubScreens[0]!!
}
fun getPluginParams(
type: ParamType = ParamType.UPDATE,
toScreenData: String = "",
): SubmitParams {
return SubmitParams().apply {
addValue(KirraDungeonClient.plugin.name)
addValue(type.name)
// toScreenData
addValue(toScreenData)
// fromScreenData
add("global.dungeon_category")
add("global.dungeon_sub_category")
add("global.dungeon_current_selected")
add("global.dungeon_page")
}
}
fun getDungeonCategory(index: Int) = when (index) {
1 -> DungeonCategory.NORMAL
2 -> DungeonCategory.TEAM
3 -> DungeonCategory.ACTIVITY
4 -> DungeonCategory.SPECIAL
else -> error("out of dungeon category index, max is 4.")
}
fun getDungeonScreen(category: DungeonCategory, index: Int): DungeonScreen? {
val parent = category.getParentScreen()
return parent.getOrNull(index)
}
fun getMaxPage(droppedItems: List<String>): Int {
return Lists.partition(droppedItems, 6).size
}
fun sendDroppedItems(player: Player, droppedItems: List<String>, page: Int) {
val partition = Lists.partition(droppedItems, 6)
val split = partition.getOrNull(page - 1) ?: partition.getOrNull(0)
for (index in 1..6) {
val slotId = "dungeon_drop_$index"
val indexStr = split?.getOrNull(index - 1) ?: "null"
val item = ZaphkielAPI.getItemStack(indexStr) ?: ItemStack(Material.AIR)
PacketSender.putClientSlotItem(player, slotId, item)
}
}
fun getNumber(subScreen: DungeonSubScreen): Int {
val dungeonId = subScreen.teleportData
return Zone.getByID(dungeonId)?.num ?: 0
}
}
| 0
|
Kotlin
|
0
| 0
|
537f062f32d1b14cf26c89161a8efc178e596d14
| 3,061
|
KirraDungeon
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/com/ffaero/openrocketassembler/FileFormat.kt
|
wildcat-rocketry
| 313,389,669
| false
|
{"Kotlin": 162168}
|
package com.ffaero.openrocketassembler
import com.google.protobuf.ByteString
object FileFormat {
const val extension = "orka"
const val version = 2
val emptyORK: ByteString = ByteString.copyFrom(byteArrayOf(
0x1F, -0x75, 0x08, 0x00, 0x77, 0x19, -0x0A, 0x5F, 0x00, 0x03, -0x4D, -0x4F, -0x51, -0x38, -0x33,
0x51, 0x28, 0x4B, 0x2D, 0x2A, -0x32, -0x34, -0x31, -0x4D, 0x55, 0x32, -0x2C, 0x33, 0x50, 0x52,
0x48, -0x33, 0x4B, -0x32, 0x4F, -0x37, -0x34, 0x4B, -0x49, 0x55, 0x0A, 0x0D, 0x71, -0x2D, -0x4B,
0x50, -0x4E, -0x49, -0x1D, -0x1B, -0x4E, -0x37, 0x2F, 0x48, -0x33, 0x2B, -0x36, 0x4F, -0x32, 0x4E,
0x2D, 0x41, 0x55, 0x6D, 0x67, 0x03, 0x11, -0x4B, -0x4D, 0x29, 0x2E, 0x4D, 0x4A, -0x32, -0x31,
0x2D, -0x38, -0x31, 0x4B, -0x33, 0x2B, 0x29, 0x06, 0x72, 0x4B, 0x12, -0x2D, 0x53, -0x0B, -0x13,
0x6C, -0x0C, -0x2F, -0x3C, -0x0B, 0x61, -0x16, -0x0B, 0x11, 0x46, 0x02, 0x2D, 0x00, 0x00, -0x43,
0x0C, 0x20, -0x5C, -0x77, 0x00, 0x00, 0x00
))
}
| 5
|
Kotlin
|
0
| 0
|
4c12948ed3b2fd5656a88ceb0cb2fcaa72d738ef
| 1,018
|
openrocket-assembler
|
MIT License
|
src/year_2021/day_10/Day10Test.kt
|
scottschmitz
| 572,656,097
| false
|
{"Kotlin": 195562}
|
package year_2021.day_10
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class Day10Test {
private val sampleText = listOf(
"[({(<(())[]>[[{[]{<()<>>",
"[(()[<>])]({[<{<<[]>>(",
"{([(<{}[<>[]}>{[]{[(<()>",
"(((({<>}<{<{<>}{[]{[]{}",
"[[<[([]))<([[{}[[()]]]",
"[{[{({}]{}}([{[{{{}}([]",
"{<[[]]>}<{[{[{[]{()[[[]",
"[<(<(<(<{}))><([]([]()",
"<{([([[(<>()){}]>(<<{{",
"<{([{{}}[<[[[<>{}]]]>[]]",
)
@Test
fun testSolutionOne() {
val solutionOne = Day10.solutionOne(sampleText)
assertEquals(26397, solutionOne)
}
@Test
fun testSolutionTwo() {
val solutionTwo = Day10.solutionTwo(sampleText)
assertEquals(288957, solutionTwo)
}
}
| 0
|
Kotlin
|
0
| 0
|
3b5f3a14273e540a5b35f3ab1bcadc7ce76ddc5a
| 811
|
advent_of_code
|
Apache License 2.0
|
webinterface/src/jsMain/kotlin/App.kt
|
FraunhoferISST
| 768,670,035
| false
|
{"Kotlin": 344552, "Dockerfile": 914, "JavaScript": 773, "HTML": 285}
|
/*
* Copyright (c) 2023-2024 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
*
* This work is licensed under the Fraunhofer License (on the basis of the MIT license)
* that can be found in the LICENSE file.
*/
import io.kvision.Application
import io.kvision.BootstrapCssModule
import io.kvision.BootstrapModule
import io.kvision.BootstrapUploadModule
import io.kvision.CoreModule
import io.kvision.FontAwesomeModule
import io.kvision.html.h1
import io.kvision.html.span
import io.kvision.i18n.I18n.tr
import io.kvision.module
import io.kvision.panel.root
import io.kvision.panel.tab
import io.kvision.panel.tabPanel
import io.kvision.panel.vPanel
import io.kvision.startApplication
import io.kvision.utils.auto
import io.kvision.utils.em
import io.kvision.utils.perc
class App : Application() {
/** Initial method to load the default watermarker form */
override fun start() {
root("trend") {
vPanel {
// Styling
width = 90.perc
marginLeft = auto
marginRight = auto
paddingTop = 1.em
// Intro text
h1("TREND")
span(
"This tools allows you to hide a text-based watermark (word, name, " +
"sentence, etc.) in a text or file of your choice.",
) {
marginBottom = 1.em
}
tabPanel {
// border = Border(2.px, BorderStyle.SOLID)
tab(tr("Text"), "fas fa-tarp", route = "/watermarkText") {
add(WatermarkTextTab())
}
tab(tr("File"), "fas fa-file", route = "/watermarkFile") {
add(WatermarkFileTab())
}
tab(tr("Extract"), "fas fa-arrow-down", route = "/watermarkExtract") {
add(WatermarkExtractTab())
}
}
}
}
}
}
/** Main KVision method to load modules */
fun main() {
startApplication(
::App,
module.hot,
BootstrapModule,
BootstrapCssModule,
BootstrapUploadModule,
CoreModule,
FontAwesomeModule,
)
}
| 23
|
Kotlin
|
2
| 5
|
8434603ea68f9b454162a0273361fda58347d4de
| 2,304
|
TREND
|
MIT License
|
app/src/main/java/xyz/teamgravity/unittest/RegistrationUtil.kt
|
raheemadamboev
| 336,012,633
| false
|
{"Kotlin": 6410}
|
package xyz.teamgravity.unittest
object RegistrationUtil {
private val existingUsers = listOf("Raheem", "Nargeeza")
/**
* The input is not valid if...
* ...the username/password is empty
* ...the username is already taken
* ...the confirmed password is not same as the real password
* ...the password contains less than 2 digits
*/
fun validateRegistration(
username: String,
password1: String, password2: String
): Boolean {
if (username.isBlank() || password1.isBlank()) {
return false
}
if (username in existingUsers) {
return false
}
if (password1 != password2) {
return false
}
if (password1.count { it.isDigit() } < 2) {
return false
}
return true
}
}
| 0
|
Kotlin
|
0
| 0
|
96b95586c0a41ca878e6857ea2e577ecc26c87c5
| 852
|
junit-test-app
|
Apache License 2.0
|
RichText/src/main/java/com/sik/richtext/RichEditText.kt
|
SilverIceKey
| 672,860,437
| false
| null |
package com.sik.richtext
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.text.Editable
import android.text.Layout
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.style.AbsoluteSizeSpan
import android.text.style.AlignmentSpan
import android.text.style.CharacterStyle
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.sik.richtext.RichEditTextFormat.FORMAT_ALIGN_CENTER
import com.sik.richtext.RichEditTextFormat.FORMAT_ALIGN_LEFT
import com.sik.richtext.RichEditTextFormat.FORMAT_ALIGN_RIGHT
import com.sik.richtext.RichEditTextFormat.FORMAT_BOLD
import com.sik.richtext.RichEditTextFormat.FORMAT_FONT_COLOR
import com.sik.richtext.RichEditTextFormat.FORMAT_FONT_SIZE
import com.sik.richtext.RichEditTextFormat.FORMAT_HEADING_1
import com.sik.richtext.RichEditTextFormat.FORMAT_HEADING_2
import com.sik.richtext.RichEditTextFormat.FORMAT_HEADING_3
import com.sik.richtext.RichEditTextFormat.FORMAT_HEADING_4
import com.sik.richtext.RichEditTextFormat.FORMAT_HEADING_5
import com.sik.richtext.RichEditTextFormat.FORMAT_HEADING_REMOVE
import com.sik.richtext.RichEditTextFormat.FORMAT_ITALIC
import com.sik.richtext.RichEditTextFormat.FORMAT_STRIKETHROUGH
import com.sik.richtext.RichEditTextFormat.FORMAT_UNDERLINE
open class RichEditText @JvmOverloads constructor(
context: Context, attrs: AttributeSet
) : AppCompatEditText(context, attrs) {
private val mBackgroundLinePaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val mRect = Rect()
/**
* Spannable string builder
* 样式文本
*/
private var spannableStringBuilder: SpannableStringBuilder = SpannableStringBuilder()
/**
* Show background line
* 是否显示横线背景
*/
private var showBackgroundLine = false
/**
* On text size change listener
* 文本大小改变监听
*/
private var onTextSizeChangeListener: (line: Int) -> Unit = {}
/**
* Is bold enable
* 是否开启加粗
*/
private var isBoldEnable: Boolean = false
/**
* Is italic enable
* 是否开启斜体
*/
private var isItalicEnable: Boolean = false
/**
* Font color
* 字体颜色
*/
private var fontColor: Int = Color.parseColor("#414141")
/**
* Font size
* 字体大小
*/
private var fontSize: Float = textSize
/**
* Start input
* 开始输入的位置
*/
private var startInput: Int = 0
/**
* Count input
* 总输入的字符
*/
private var countInput: Int = 0
/**
* Is style change
* 样式修改
*/
var isStyleChange: Boolean = false
init {
mBackgroundLinePaint.style = Paint.Style.STROKE
mBackgroundLinePaint.color = Color.BLACK // 设置线的颜色
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
startInput = start
countInput = count
}
override fun afterTextChanged(s: Editable) {
if (!isStyleChange) {
isStyleChange = true
val finalSelectionStart = selectionStart
if (spannableStringBuilder != text) {
spannableStringBuilder = SpannableStringBuilder(text)
}
for (index in startInput until startInput + countInput) {
checkAndSetSpan(index)
}
text = spannableStringBuilder
setSelection(finalSelectionStart)
isStyleChange = false
}
}
}
addTextChangedListener(textWatcher)
}
private fun checkAndSetSpan(start: Int) {
if (isBoldEnable || isItalicEnable) {
spannableStringBuilder.setSpan(
StyleSpan(
if (isBoldEnable && isItalicEnable) {
Typeface.BOLD_ITALIC
} else if (isBoldEnable) {
Typeface.BOLD
} else {
Typeface.ITALIC
}
), start, start + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
spannableStringBuilder.setSpan(
AbsoluteSizeSpan(
fontSize.toInt()
), start, start + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
spannableStringBuilder.setSpan(
ForegroundColorSpan(
fontColor
), start, start + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
override fun onDraw(canvas: Canvas) {
if (showBackgroundLine) {
val count = lineCount
val r = mRect
val paint = mBackgroundLinePaint
var startY = paddingTop
for (index in 0 until count) {
getLineBounds(index, r)
val indexLineHeight = layout.getLineBottom(index) - layout.getLineTop(index)
canvas.drawLine(
r.left.toFloat(),
startY + indexLineHeight.toFloat(),
r.right.toFloat(),
startY + indexLineHeight.toFloat(),
paint
)
startY += indexLineHeight
}
}
super.onDraw(canvas)
}
/**
* Set show background line
* 设置是否显示横线背景
* @param showBackgroundLine
*/
fun setShowBackgroundLine(showBackgroundLine: Boolean) {
this.showBackgroundLine = showBackgroundLine
postInvalidate()
}
/**
* Check show background line
* 切换是否展示横线背景
*/
fun switchShowBackgroundLine() {
this.showBackgroundLine = !this.showBackgroundLine
postInvalidate()
}
/**
* Set on text size change listener
* 设置文本大小改变监听
* @param onTextSizeChangeListener
* @receiver
*/
fun setOnTextSizeChangeListener(onTextSizeChangeListener: (line: Int) -> Unit = {}) {
this.onTextSizeChangeListener = onTextSizeChangeListener
}
override fun setTextSize(unit: Int, size: Float) {
super.setTextSize(unit, size)
onTextSizeChangeListener(-1)
}
/**
* Format
* 格式化
* @param richEditTextFormat
* @param value
*/
@JvmOverloads
fun format(richEditTextFormat: RichEditTextFormat, value: Any? = null) {
isStyleChange = true
val finalSelectionStart = selectionStart
val finalSelectionEnd = selectionEnd
if (spannableStringBuilder != text) {
spannableStringBuilder = SpannableStringBuilder(text)
}
when (richEditTextFormat) {
FORMAT_HEADING_1 -> {
setHeading(1.5f)
}
FORMAT_HEADING_2 -> {
setHeading(1.4f)
}
FORMAT_HEADING_3 -> {
setHeading(1.3f)
}
FORMAT_HEADING_4 -> {
setHeading(1.2f)
}
FORMAT_HEADING_5 -> {
setHeading(1.1f)
}
FORMAT_HEADING_REMOVE -> {
val blockPosition = getBlockPosition()
removeSpan(
blockPosition.first, blockPosition.second, StyleSpan::class.java
)
removeSpan(
blockPosition.first, blockPosition.second, RelativeSizeSpan::class.java
)
}
FORMAT_BOLD -> {
isBoldEnable = !isBoldEnable
if (selectionStart != selectionEnd) {
val boldStyleSpan =
getSpans(selectionStart, selectionEnd, StyleSpan::class.java)
if (boldStyleSpan.isEmpty()) {
setBold(null)
} else {
val noSpans = getOutSidePosition(getSpansPosition(boldStyleSpan))
noSpans.forEach {
setBold(null, it.first, it.second)
}
boldStyleSpan.forEach {
setBold(it)
}
}
}
}
FORMAT_ITALIC -> {
isItalicEnable = !isItalicEnable
if (selectionStart != selectionEnd) {
val italicStyleSpan =
getSpans(selectionStart, selectionEnd, StyleSpan::class.java)
if (italicStyleSpan.isEmpty()) {
setItalic(null)
} else {
val noSpans = getOutSidePosition(getSpansPosition(italicStyleSpan))
noSpans.forEach {
setItalic(null, it.first, it.second)
}
italicStyleSpan.forEach {
setItalic(it)
}
}
}
}
FORMAT_UNDERLINE -> {
if (hasFormat(selectionStart, selectionEnd, UnderlineSpan::class.java)) {
removeSpan(selectionStart, selectionEnd, UnderlineSpan::class.java)
} else {
spannableStringBuilder.setSpan(
UnderlineSpan(),
selectionStart,
selectionEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
FORMAT_STRIKETHROUGH -> {
if (hasFormat(selectionStart, selectionEnd, StrikethroughSpan::class.java)) {
removeSpan(selectionStart, selectionEnd, StrikethroughSpan::class.java)
} else {
spannableStringBuilder.setSpan(
StrikethroughSpan(),
selectionStart,
selectionEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
FORMAT_FONT_SIZE -> {
fontSize = if (value is Int) {
value.toFloat()
} else if (value is Float) {
value.toFloat()
} else if (value is Double) {
value.toFloat()
} else {
textSize
}
if (hasFormat(selectionStart, selectionEnd, AbsoluteSizeSpan::class.java)) {
removeSpan(selectionStart, selectionEnd, AbsoluteSizeSpan::class.java)
}
if (value != null) {
spannableStringBuilder.setSpan(
AbsoluteSizeSpan(fontSize.toInt()),
selectionStart,
selectionEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
FORMAT_FONT_COLOR -> {
fontColor = if (value is String) {
Color.parseColor(value)
} else {
value as Int
}
if (hasFormat(selectionStart, selectionEnd, ForegroundColorSpan::class.java)) {
removeSpan(selectionStart, selectionEnd, ForegroundColorSpan::class.java)
}
spannableStringBuilder.setSpan(
ForegroundColorSpan(
fontColor
), selectionStart, selectionEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
FORMAT_ALIGN_LEFT -> {
setTextAlignmentSpan(0)
}
FORMAT_ALIGN_CENTER -> {
setTextAlignmentSpan(1)
}
FORMAT_ALIGN_RIGHT -> {
setTextAlignmentSpan(2)
}
}
text = spannableStringBuilder
isStyleChange = false
setSelection(finalSelectionStart, finalSelectionEnd)
onTextSizeChangeListener(getSelectionLine(finalSelectionStart))
}
/**
* Get spans position
* 获取样式的坐标
* @param spans
*/
private fun <T : CharacterStyle> getSpansPosition(spans: MutableList<T>): MutableList<Pair<Int, Int>> {
return mutableListOf<Pair<Int, Int>>().apply {
spans.forEach {
val spanStart = spannableStringBuilder.getSpanStart(it)
val spanEnd = spannableStringBuilder.getSpanEnd(it)
add(spanStart to spanEnd)
}
}
}
/**
* Get out side position
* 获取选中但是没有样式的区域
* @param spans
*/
private fun getOutSidePosition(spans: MutableList<Pair<Int, Int>>): MutableList<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
var lastEnd = selectionStart
for (span in spans) {
if (span.first > lastEnd) {
result.add(Pair(lastEnd, span.first))
}
lastEnd = span.second
}
if (lastEnd < selectionEnd) {
result.add(Pair(lastEnd, selectionEnd))
}
return result
}
/**
* Set bold
* 设置加粗
*/
private fun setBold(
boldStyleSpan: StyleSpan?,
start: Int = selectionStart,
end: Int = selectionEnd
) {
val spansStart = spannableStringBuilder.getSpanStart(boldStyleSpan)
val spanEnd = spannableStringBuilder.getSpanEnd(boldStyleSpan)
if (boldStyleSpan != null) {
when (boldStyleSpan.style) {
Typeface.BOLD_ITALIC -> {
spannableStringBuilder.removeSpan(boldStyleSpan)
spannableStringBuilder.setSpan(
StyleSpan(Typeface.ITALIC),
spansStart,
spanEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
Typeface.BOLD -> {
spannableStringBuilder.removeSpan(boldStyleSpan)
}
Typeface.ITALIC -> {
spannableStringBuilder.removeSpan(boldStyleSpan)
spannableStringBuilder.setSpan(
StyleSpan(Typeface.BOLD_ITALIC),
spansStart,
spanEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
} else {
spannableStringBuilder.setSpan(
StyleSpan(Typeface.BOLD),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
/**
* Set italic
* 设置斜体
*/
private fun setItalic(
italicStyleSpan: StyleSpan?,
start: Int = selectionStart,
end: Int = selectionEnd
) {
if (italicStyleSpan != null) {
val spanStart = spannableStringBuilder.getSpanStart(italicStyleSpan)
val spanEnd = spannableStringBuilder.getSpanEnd(italicStyleSpan)
when (italicStyleSpan.style) {
Typeface.BOLD_ITALIC -> {
spannableStringBuilder.removeSpan(italicStyleSpan)
spannableStringBuilder.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
spanEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
Typeface.BOLD -> {
spannableStringBuilder.removeSpan(italicStyleSpan)
spannableStringBuilder.setSpan(
StyleSpan(Typeface.BOLD_ITALIC),
spanStart,
spanEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
Typeface.ITALIC -> {
spannableStringBuilder.removeSpan(italicStyleSpan)
}
}
} else {
spannableStringBuilder.setSpan(
StyleSpan(Typeface.ITALIC),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
/**
* Set text alignment
* 0 左对齐 1 居中 2 右对齐
*/
private fun setTextAlignmentSpan(alignType: Int) {
val blockPosition = getBlockPosition()
val alignmentSpan =
getSpan(blockPosition.first, blockPosition.second, AlignmentSpan::class.java)
if (alignmentSpan != null) {
spannableStringBuilder.removeSpan(alignmentSpan)
}
when (alignType) {
0 -> {
if (alignmentSpan?.alignment != Layout.Alignment.ALIGN_NORMAL) {
spannableStringBuilder.setSpan(
AlignmentSpan.Standard(Layout.Alignment.ALIGN_NORMAL),
blockPosition.first,
blockPosition.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
1 -> {
if (alignmentSpan?.alignment != Layout.Alignment.ALIGN_CENTER) {
spannableStringBuilder.setSpan(
AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER),
blockPosition.first,
blockPosition.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
2 -> {
if (alignmentSpan?.alignment != Layout.Alignment.ALIGN_OPPOSITE) {
spannableStringBuilder.setSpan(
AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE),
blockPosition.first,
blockPosition.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
}
}
/**
* Set heading
* 设置标题
* @param headingValue
*/
private fun setHeading(headingValue: Float) {
val blockPosition = getBlockPosition()
if (hasFormat(
blockPosition.first, blockPosition.second, RelativeSizeSpan::class.java
)
) {
val spans: Array<RelativeSizeSpan> = spannableStringBuilder.getSpans(
blockPosition.first, blockPosition.second, RelativeSizeSpan::class.java
)
for (span in spans) {
if (span.sizeChange == headingValue) {
spannableStringBuilder.removeSpan(span)
removeSpan(
blockPosition.first, blockPosition.second, StyleSpan::class.java
)
break
} else if (span.sizeChange != headingValue) {
spannableStringBuilder.removeSpan(span)
spannableStringBuilder.setSpan(
RelativeSizeSpan(headingValue),
blockPosition.first,
blockPosition.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
break
}
}
} else {
spannableStringBuilder.setSpan(
RelativeSizeSpan(headingValue),
blockPosition.first,
blockPosition.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
spannableStringBuilder.setSpan(
StyleSpan(Typeface.BOLD),
blockPosition.first,
blockPosition.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
/**
* Has format
* 检查是否存在格式
* @param start
* @param end
* @param formatClazz
* @return
*/
private fun hasFormat(start: Int, end: Int, formatClazz: Class<*>): Boolean {
if (spannableStringBuilder.length < start) {
return false
}
var hasFormat = false
spannableStringBuilder.let {
val spans: Array<*> = it.getSpans(
start, end, formatClazz
)
for (span in spans) {
if (span != null) {
if (span.javaClass == formatClazz) {
hasFormat = true
break
}
}
}
}
return hasFormat
}
/**
* Get span
* 获取所有样式
* @param T
* @param start
* @param end
* @param spanClass
* @return
*/
private inline fun <reified T : Any> getSpans(
start: Int, end: Int, spanClass: Class<T>
): MutableList<T> {
if (spannableStringBuilder.length < start) {
return mutableListOf()
}
val spans = mutableListOf<T>()
spannableStringBuilder.let {
val allSpans: Array<*> = it.getSpans(
start, end, spanClass
)
for (span in allSpans) {
if (span != null) {
if (span is T) {
spans.add(span)
}
}
}
}
return spans
}
/**
* Get span
* 获取样式
* @param T
* @param start
* @param end
* @param spanClass
* @return
*/
private inline fun <reified T : Any> getSpan(
start: Int, end: Int, spanClass: Class<T>
): T? {
if (spannableStringBuilder.length < start) {
return null
}
val spans = mutableListOf<T>()
spannableStringBuilder.let {
val allSpans: Array<*> = it.getSpans(
start, end, spanClass
)
for (span in allSpans) {
if (span != null) {
if (span is T) {
return span
}
}
}
}
return null
}
/**
* Remove span
* 移除效果
* @param start
* @param end
* @param spanClass
*/
private fun removeSpan(start: Int, end: Int, spanClass: Class<*>) {
if (spannableStringBuilder.length < start) {
return
}
spannableStringBuilder.let {
val spans: Array<*> = it.getSpans(
start, end, spanClass
)
for (span in spans) {
if (span != null) {
if (span.javaClass == spanClass) {
it.removeSpan(span)
break
}
}
}
}
}
/**
* Get block position
* 获取文本块
* @return
*/
private fun getBlockPosition(): Pair<Int, Int> {
val nextNewLine = text?.indexOf('\n', selectionStart) ?: 0
val previousNewLine = text?.lastIndexOf('\n', selectionStart - 1) ?: 0
if (previousNewLine == -1) {
return 0 to nextNewLine
}
return previousNewLine to nextNewLine
}
}
| 0
|
Kotlin
|
0
| 0
|
21d0d71085769d3b5414dd54e8341258b5fd9ddc
| 23,770
|
RichText
|
MIT License
|
feature/mobile/provider-info/src/main/kotlin/com/flixclusive/feature/mobile/provider/info/ProviderInfoScreenViewModel.kt
|
rhenwinch
| 659,237,375
| false
|
{"Kotlin": 1933360, "Java": 18011}
|
package com.flixclusive.feature.mobile.provider.info
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.flixclusive.core.datastore.AppSettingsManager
import com.flixclusive.core.ui.common.navigation.ProviderInfoScreenNavArgs
import com.flixclusive.core.ui.mobile.component.provider.ProviderInstallationStatus
import com.flixclusive.core.util.common.dispatcher.di.ApplicationScope
import com.flixclusive.core.util.common.resource.Resource
import com.flixclusive.core.util.common.ui.UiText
import com.flixclusive.data.provider.ProviderManager
import com.flixclusive.domain.provider.GetRepositoryUseCase
import com.flixclusive.domain.provider.util.extractGithubInfoFromLink
import com.flixclusive.domain.updater.ProviderUpdaterUseCase
import com.flixclusive.gradle.entities.Repository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject
import com.flixclusive.core.util.R as UtilR
@HiltViewModel
class ProviderInfoScreenViewModel @Inject constructor(
@ApplicationScope private val scope: CoroutineScope,
private val appSettingsManager: AppSettingsManager,
private val getRepositoryUseCase: GetRepositoryUseCase,
private val providerManager: ProviderManager,
private val providerUpdaterUseCase: ProviderUpdaterUseCase,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val providerData = savedStateHandle.navArgs<ProviderInfoScreenNavArgs>().providerData
var providerInstallationStatus by mutableStateOf(ProviderInstallationStatus.NotInstalled)
private set
var snackbar by mutableStateOf<Resource.Failure?>(null)
private set
private var providerJob: Job? = null
var repository: Repository? by mutableStateOf(null)
private set
init {
viewModelScope.launch {
initialize()
}
}
private suspend fun initialize() {
providerInstallationStatus = ProviderInstallationStatus.NotInstalled
val isInstalledAlready =
providerManager.providerDataList.any { it.name.equals(providerData.name, true) }
if (isInstalledAlready && providerUpdaterUseCase.isProviderOutdated(providerData)) {
providerInstallationStatus = ProviderInstallationStatus.Outdated
} else if (isInstalledAlready) {
providerInstallationStatus = ProviderInstallationStatus.Installed
}
getRepository(providerData.repositoryUrl ?: return)
}
fun toggleInstallation() {
if (providerJob?.isActive == true)
return
providerJob = scope.launch {
when (providerInstallationStatus) {
ProviderInstallationStatus.NotInstalled -> installProvider()
ProviderInstallationStatus.Outdated -> updateProvider()
ProviderInstallationStatus.Installed -> uninstallProvider()
else -> Unit
}
}
}
private suspend fun installProvider() {
providerInstallationStatus = ProviderInstallationStatus.Installing
try {
providerManager.loadProvider(
providerData = providerData,
needsDownload = true
)
} catch (_: Exception) {
snackbar = Resource.Failure(
UiText.StringResource(
UtilR.string.failed_to_load_provider,
providerData.name
)
)
providerInstallationStatus = ProviderInstallationStatus.NotInstalled
return
}
providerInstallationStatus = ProviderInstallationStatus.Installed
}
private suspend fun uninstallProvider() {
providerManager.unloadProvider(providerData)
providerInstallationStatus = ProviderInstallationStatus.NotInstalled
}
private suspend fun updateProvider() {
val isSuccess = providerUpdaterUseCase.updateProvider(providerData.name)
if (isSuccess) {
providerInstallationStatus = ProviderInstallationStatus.Installed
} else {
snackbar =
Resource.Failure(UiText.StringResource(UtilR.string.failed_to_update_provider))
}
}
private suspend fun getRepository(url: String) {
val (username, repositoryName) = extractGithubInfoFromLink(url) ?: return
repository = appSettingsManager.localProviderSettings.repositories.find {
it.owner.equals(username, true) && it.name == repositoryName
}
if (repository != null)
return
when (val onlineRepository = getRepositoryUseCase(url)) {
is Resource.Failure -> snackbar = onlineRepository
Resource.Loading -> Unit
is Resource.Success -> {
repository = onlineRepository.data
appSettingsManager.updateProviderSettings {
it.copy(repositories = it.repositories + repository!!)
}
}
}
}
fun onConsumeSnackbar() {
snackbar = null
}
}
| 25
|
Kotlin
|
26
| 325
|
7b6ada69290e1afc0deb6fb3d4a9ab7f79ea3fb2
| 5,329
|
Flixclusive
|
MIT License
|
core/src/main/kotlin/snitch/request/TypedRequestWrapper.kt
|
memoizr
| 322,370,926
| false
| null |
package snitch.request
import snitch.response.CommonResponses
@JvmInline
value class TypedRequestWrapper<T : Any>(
val request: RequestWrapper,
): CommonResponses {
val body: T get() = request.body() as T
}
| 0
|
Kotlin
|
2
| 34
|
501b43074653207279fe3646a8f8519520967c3b
| 217
|
snitch
|
Apache License 2.0
|
cliente/app/src/main/java/gmarques/remotewincontrol/domain/funcoes/mouse/mousepad_gestos/EntradaCliqueDoisDedos.kt
|
GilianMarques
| 583,554,045
| false
|
{"Kotlin": 114978, "Java": 103, "Batchfile": 60}
|
package gmarques.remotewincontrol.domain.funcoes.mouse.mousepad_gestos
import android.view.MotionEvent
import gmarques.remotewincontrol.domain.dtos.cliente.TIPO_EVENTO_CLIENTE
import gmarques.remotewincontrol.domain.funcoes.mouse.EntradaCallback
import gmarques.remotewincontrol.domain.dtos.cliente.DtoCliente
import kotlin.math.abs
class EntradaCliqueDoisDedos(override var callback: EntradaCallback) : EntradaAbs() {
private var actionDown: Pair<Float, Float>? = null
override fun actionDown(event: MotionEvent) {
if (actionDown == null) {
actionDown = event.x to event.y
}
super.actionDown(event)
}
override fun actionPointerUp(event: MotionEvent) {
if (actionDown != null && event.pointerCount == 2) {
val movX = abs(actionDown!!.first - event.x)
val movY = abs(actionDown!!.second - event.y)
val duracao = event.eventTime - event.downTime
if (duracao <= CLICK_INTERVAL_TWO_FINGERS && movX <= MAX_MOV_PERM_TWO_FINGERS && movY <= MAX_MOV_PERM_TWO_FINGERS)
callback.entradaValidada(DtoCliente(TIPO_EVENTO_CLIENTE.PAD_CLICK_TWO_FINGERS))
}
actionDown = null
}
}
| 0
|
Kotlin
|
0
| 1
|
91c3464d2d845f9b09512d669450be68456f62e9
| 1,218
|
RemoteWinControl
|
MIT License
|
core/network/src/main/kotlin/com/example/network/service/SmsService.kt
|
zhouquancheng-dev
| 678,103,314
| false
|
{"Kotlin": 205122, "HTML": 3900}
|
package com.example.network.service
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.Headers
import retrofit2.http.POST
import com.example.model.UserResponse
import com.example.model.SmsResponse
interface SmsService {
/**
* 存储验证码信息
* @param phoneNumber 手机号码
* @param smsCode 验证码
* @param bizId 发送回执id
* @param sendTime 发送时间
* @return BaseResponse<Any?>
*/
@POST("/sms/save")
@Headers("Content-Type: application/x-www-form-urlencoded")
@FormUrlEncoded
suspend fun saveSmsData(
@Field("phone_number") phoneNumber: String,
@Field("sms_code") smsCode: String,
@Field("biz_id") bizId: String,
@Field("send_time") sendTime: String
): UserResponse<Any?>
/**
* 校验短信验证码
* @param phoneNumber 手机号码
* @param smsCode 验证码
* @param bizId 发送回执id
* @return BaseResponse<SmsResponse>
*/
@POST("/sms/check")
@Headers("Content-Type: application/x-www-form-urlencoded")
@FormUrlEncoded
suspend fun checkSms(
@Field("phone_number") phoneNumber: String,
@Field("sms_code") smsCode: String,
@Field("biz_id") bizId: String,
): UserResponse<SmsResponse?>
}
| 0
|
Kotlin
|
0
| 0
|
af4fd5feaa106297f1ce6fccc643fee28f9b2b80
| 1,242
|
Itinerary-android
|
Apache License 2.0
|
packages/graalvm/src/main/kotlin/elide/runtime/gvm/internals/intrinsics/js/JsSymbol.kt
|
elide-dev
| 506,113,888
| false
| null |
package elide.runtime.gvm.internals.intrinsics.js
import elide.runtime.intrinsics.js.Symbol
import kotlinx.serialization.Serializable
/**
* TBD.
*/
@Serializable
@JvmInline internal value class JsSymbol (override val symbol: String) :
Symbol,
Comparable<Symbol>,
java.io.Serializable {
/** Well-known JavaScript symbols. */
internal companion object JsSymbols {
/** @return JS symbol wrapping the receiving string. */
@JvmStatic fun String.asJsSymbol(): JsSymbol = JsSymbol(this)
}
/** @inheritDoc */
override fun toString(): String = "Symbol{$symbol}"
/** @inheritDoc */
override fun compareTo(other: Symbol): Int = this.symbol.compareTo(other.symbol)
}
| 36
|
Kotlin
|
4
| 33
|
91800dbbf291e65a91d451ed50c9673d82efd174
| 689
|
elide
|
MIT License
|
shop/app/src/main/java/id/kotlin/shop/login/LoginActivity.kt
|
budioktaviyan
| 130,386,248
| false
| null |
package id.kotlin.shop.login
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import id.kotlin.shop.R
import id.kotlin.shop.data.user.User
import id.kotlin.shop.deps.ShopDepsProvider
import id.kotlin.shop.router.ShopRouter
import kotlinx.android.synthetic.main.activity_login.*
import javax.inject.Inject
class LoginActivity : AppCompatActivity(), LoginView {
@Inject lateinit var router: ShopRouter
private lateinit var presenter: LoginPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
(application as? ShopDepsProvider)?.providesShopDeps?.inject(this)
(application as? ShopDepsProvider)?.providesDatabaseDeps?.let {
presenter = LoginPresenter(this, it)
}
btn_login.setOnClickListener {
val username = et_username.text.toString()
val password = <PASSWORD>
val user = User(username = username, password = <PASSWORD>)
presenter.login(user)
}
}
override fun onDestroy() {
super.onDestroy()
presenter.onDestroy()
}
override fun onUserCreated(user: User) {
Toast.makeText(this, "Created default user...", Toast.LENGTH_SHORT).show()
presenter.create(user)
}
override fun onLoginSuccess() {
router.launchHome(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
61f59ea0e8a5c3bcf239dfc18dee12dd3cf8441d
| 1,457
|
android-test-cases
|
MIT License
|
app/src/main/java/com/heyanle/easybangumi4/plugin/js/extension/JSExtensionCryLoader.kt
|
easybangumiorg
| 413,723,669
| false
|
{"Kotlin": 1490799, "Java": 761739, "Shell": 450}
|
package com.heyanle.easybangumi4.plugin.js.extension
import com.heyanle.easybangumi4.APP
import com.heyanle.easybangumi4.plugin.extension.ExtensionInfo
import com.heyanle.easybangumi4.plugin.extension.loader.ExtensionLoader
import com.heyanle.easybangumi4.plugin.extension.provider.FileJsExtensionProvider
import com.heyanle.easybangumi4.plugin.js.runtime.JSRuntimeProvider
import com.heyanle.easybangumi4.utils.PackageHelper
import com.heyanle.easybangumi4.utils.aesEncryptTo
import com.heyanle.easybangumi4.utils.getInnerCachePath
import com.heyanle.easybangumi4.utils.getMD5
import java.io.File
/**
* 加密 js 加载,解密后委托给 JsExtensionLoader
* Created by heyanle on 2024/10/13
* https://github.com/heyanLE
*/
class JSExtensionCryLoader(
private val file: File,
private val jsRuntime: JSRuntimeProvider,
): ExtensionLoader {
companion object {
val CHUNK_SIZE = 1024
}
private val plaintextCacheFolder = APP.getInnerCachePath("js_plaintext")
override val key: String
get() = "js:${file.path}"
override fun load(): ExtensionInfo? {
val plaintextFileName = file.absolutePath.getMD5()
val plaintextFile = File(plaintextCacheFolder, plaintextFileName)
plaintextFile.delete()
// 解密
file.aesEncryptTo(plaintextFile, PackageHelper.appSignature, CHUNK_SIZE)
plaintextFile.deleteOnExit()
return JSExtensionLoader(plaintextFile, jsRuntime).load()
}
override fun canLoad(): Boolean {
return file.isFile && file.exists() && file.canRead() && file.name.endsWith(
FileJsExtensionProvider.EXTENSION_CRY_SUFFIX)
}
}
| 30
|
Kotlin
|
82
| 2,892
|
e1f67cc997884e4f6e0e7074c2bae599d3996c9a
| 1,638
|
EasyBangumi
|
Apache License 2.0
|
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsLeftArrowCircle.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.boxicons.boxicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup
public val SolidGroup.BxsLeftArrowCircle: ImageVector
get() {
if (_bxsLeftArrowCircle != null) {
return _bxsLeftArrowCircle!!
}
_bxsLeftArrowCircle = Builder(name = "BxsLeftArrowCircle", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 2.0f)
curveTo(6.486f, 2.0f, 2.0f, 6.486f, 2.0f, 12.0f)
reflectiveCurveToRelative(4.486f, 10.0f, 10.0f, 10.0f)
reflectiveCurveToRelative(10.0f, -4.486f, 10.0f, -10.0f)
reflectiveCurveTo(17.514f, 2.0f, 12.0f, 2.0f)
close()
moveTo(17.0f, 13.0f)
horizontalLineToRelative(-5.0f)
verticalLineToRelative(4.0f)
lineToRelative(-5.0f, -5.0f)
lineToRelative(5.0f, -5.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(2.0f)
close()
}
}
.build()
return _bxsLeftArrowCircle!!
}
private var _bxsLeftArrowCircle: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,049
|
compose-icon-collections
|
MIT License
|
app/src/main/java/net/pters/learnopengl/android/scenes/lighting/Scene1Colors.kt
|
mpters
| 340,861,805
| false
| null |
package net.pters.learnopengl.android.scenes.lighting
import android.content.Context
import android.opengl.GLES30.*
import com.curiouscreature.kotlin.math.Float3
import com.curiouscreature.kotlin.math.perspective
import com.curiouscreature.kotlin.math.scale
import com.curiouscreature.kotlin.math.translation
import net.pters.learnopengl.android.R
import net.pters.learnopengl.android.tools.*
class Scene1Colors private constructor(
private val vertexShaderCode: String,
private val cubeFragmentShaderCode: String,
private val lightSourceFragmentShaderCode: String
) : Scene() {
private val vertices = floatArrayOf(
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f, -0.5f
)
private val camera = Camera(
eye = Float3(1.0f, 2.0f, 5.0f),
pitch = -20.0f,
yaw = -95.0f
)
private lateinit var cubeProgram: Program
private lateinit var cubeVertexData: VertexData
private lateinit var lightSourceProgram: Program
private lateinit var lightSourceVertexData: VertexData
override fun draw() {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
val view = camera.getViewMatrix().toFloatArray()
cubeProgram.use()
glUniformMatrix4fv(
cubeProgram.getUniformLocation("view"),
1,
true,
view,
0
)
glBindVertexArray(cubeVertexData.getVaoId())
glDrawArrays(GL_TRIANGLES, 0, 36)
lightSourceProgram.use()
glUniformMatrix4fv(
lightSourceProgram.getUniformLocation("view"),
1,
true,
view,
0
)
glBindVertexArray(lightSourceVertexData.getVaoId())
glDrawArrays(GL_TRIANGLES, 0, 36)
}
override fun getCamera() = camera
override fun init(width: Int, height: Int) {
glEnable(GL_DEPTH_TEST)
glViewport(0, 0, width, height)
val projection = perspective(45.0f, width.toFloat() / height.toFloat(), 0.1f, 100.0f)
cubeProgram = Program.create(vertexShaderCode, cubeFragmentShaderCode)
cubeVertexData = VertexData(vertices, null, 3)
cubeVertexData.addAttribute(cubeProgram.getAttributeLocation("aPos"), 3, 0)
cubeVertexData.bind()
cubeProgram.use()
glUniform3f(cubeProgram.getUniformLocation("objectColor"), 1.0f, 0.5f, 0.31f)
glUniform3f(cubeProgram.getUniformLocation("lightColor"), 1.0f, 1.0f, 1.0f)
glUniformMatrix4fv(
cubeProgram.getUniformLocation("model"),
1,
true,
translation(Float3(0.0f)).toFloatArray(),
0
)
glUniformMatrix4fv(
cubeProgram.getUniformLocation("projection"),
1,
true,
projection.toFloatArray(),
0
)
lightSourceProgram = Program.create(vertexShaderCode, lightSourceFragmentShaderCode)
lightSourceVertexData = VertexData(vertices, null, 3)
lightSourceVertexData.addAttribute(lightSourceProgram.getAttributeLocation("aPos"), 3, 0)
lightSourceVertexData.bind()
lightSourceProgram.use()
val lightSourceModel = translation(Float3(1.2f, 1.0f, 2.0f)) * scale(Float3(0.2f))
glUniformMatrix4fv(
lightSourceProgram.getUniformLocation("model"),
1,
true,
lightSourceModel.toFloatArray(),
0
)
glUniformMatrix4fv(
lightSourceProgram.getUniformLocation("projection"),
1,
true,
projection.toFloatArray(),
0
)
}
companion object {
fun create(context: Context): Scene {
val resources = context.resources
return Scene1Colors(
vertexShaderCode = resources.readRawTextFile(R.raw.lighting_scene1_colors_vert),
cubeFragmentShaderCode = resources.readRawTextFile(R.raw.lighting_scene1_colors_cube_frag),
lightSourceFragmentShaderCode = resources.readRawTextFile(R.raw.lighting_scene1_colors_light_source_frag)
)
}
}
}
| 0
|
Kotlin
|
2
| 6
|
e12e776acbb9fe41e97d100c8cf05971400b33e5
| 5,131
|
learnopengl-android
|
MIT License
|
feature/settings/src/main/java/com/flexcode/wedate/settings/SettingsScreen.kt
|
Felix-Kariuki
| 588,745,399
| false
| null |
/*
* Copyright 2023 <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.flexcode.wedate.settings
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIos
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.flexcode.wedate.common.R.string as AppText
import com.flexcode.wedate.common.composables.*
import com.flexcode.wedate.common.extestions.basicButton
import com.flexcode.wedate.common.theme.deepBrown
import com.flexcode.wedate.common.theme.deepLightPurple
import com.flexcode.wedate.common.theme.purpleGrey
import com.flexcode.wedate.common.utils.contact_utils.sendMail
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun SettingsScreen(
openAndPopUp: () -> Unit,
modifier: Modifier = Modifier,
viewModel: SettingsViewModel = hiltViewModel()
) {
val scrollState = rememberScrollState()
val state by viewModel.state
Column(
modifier = modifier
) {
Row(
horizontalArrangement = Arrangement.Start
) {
SwipeRightLeftIcon(
onClick = { openAndPopUp() },
icon = Icons.Default.ArrowBackIos,
contentDesc = "Back",
height = 20.dp,
width = 20.dp,
paddingValues = PaddingValues(start = 10.dp, 0.dp),
tint = Color.Black
)
Row(horizontalArrangement = Arrangement.Center, modifier = modifier.fillMaxWidth()) {
ResultText(text = "Settings", fontSize = 22.sp, fontWeight = FontWeight.SemiBold)
}
}
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(scrollState),
horizontalAlignment = Alignment.CenterHorizontally
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val showDialog = remember {
mutableStateOf(false)
}
if (showDialog.value) {
DeleteAccountDialog(
viewModel = viewModel,
scope = scope,
context = context,
showDialog = showDialog.value,
onDismiss = { showDialog.value = false }
)
}
BasicText(
text = AppText.account,
color = deepBrown,
modifier = modifier
.fillMaxWidth()
.background(color = deepLightPurple),
fontWeight = FontWeight.Bold
)
InfoColumn(AppText.name, "${state.userDetails?.firstName}")
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(AppText.birthday, "${state.userDetails?.dateOfBirth}")
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(AppText.phone_number, "${state.userDetails?.phoneNumber}")
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(AppText.email, "${state.userDetails?.email}")
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(AppText.location, "${state.userDetails?.locationName}")
BasicText(
text = AppText.support,
color = deepBrown,
modifier = modifier
.fillMaxWidth()
.background(color = deepLightPurple),
fontWeight = FontWeight.Bold
)
InfoColumn(
AppText.help,
"",
modifier = Modifier.clickable {
context.sendMail(
"<EMAIL>",
"Help "
)
}
)
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(
AppText.ask_a_quiz,
"",
modifier = Modifier.clickable {
context.sendMail(
"<EMAIL>",
"Question From ${state.userDetails?.firstName}"
)
}
)
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(
AppText.raise_a_concern,
"",
modifier = Modifier.clickable {
context.sendMail(
"<EMAIL>",
"Concern From ${state.userDetails?.firstName}"
)
}
)
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(
AppText.contact_us,
"",
modifier = Modifier.clickable {
context.sendMail(
"<EMAIL>",
"Message From ${state.userDetails?.firstName}"
)
}
)
BasicText(
text = AppText.more,
color = deepBrown,
modifier = modifier
.fillMaxWidth()
.background(color = deepLightPurple),
fontWeight = FontWeight.Bold
)
InfoColumn(
AppText.request_a_feature,
"",
modifier = Modifier.clickable {
context.sendMail("<EMAIL>", "Feature Request")
}
)
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(
AppText.privacy_policy,
"",
modifier = Modifier.clickable {
}
)
Divider(modifier = Modifier.padding(horizontal = 16.dp))
InfoColumn(
AppText.term_of_service,
"",
modifier = Modifier.clickable {
}
)
Button(
onClick = {
viewModel.signOut()
scope.launch {
delay(1000)
restartApp(context)
}
},
modifier = modifier
.basicButton()
.height(50.dp)
.clip(RoundedCornerShape(10.dp)),
colors = ButtonDefaults.buttonColors(
backgroundColor = purpleGrey,
contentColor = MaterialTheme.colors.onPrimary
)
) {
Text(text = stringResource(AppText.log_out), fontSize = 16.sp)
}
BasicTextButton(
text = AppText.delete_account,
modifier = modifier.height(50.dp),
color = MaterialTheme.colors.onBackground
) {
showDialog.value = true
}
Spacer(modifier = Modifier.height(10.dp))
LogoComposableImage()
AppTitleText(
modifier = modifier,
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
color = purpleGrey,
textColor = purpleGrey
)
ResultText(
text = "Version 1.0.2",
color = purpleGrey,
fontSize = 13.sp,
textAlign = TextAlign.Center,
modifier = modifier
.offset(y = (-8).dp)
.padding(start = 8.dp)
)
Spacer(modifier = Modifier.height(80.dp))
}
}
}
@Composable
fun InfoColumn(
@StringRes text1: Int,
text2: String,
modifier: Modifier = Modifier
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = modifier
.fillMaxWidth()
.padding(end = 10.dp, top = 10.dp)
) {
Text(
text = stringResource(id = text1),
fontSize = 16.sp,
textAlign = TextAlign.Start,
modifier = modifier.padding(16.dp, 8.dp)
)
Text(
text = text2,
fontSize = 16.sp,
textAlign = TextAlign.End,
modifier = modifier.padding(16.dp, 8.dp),
fontWeight = FontWeight.SemiBold
)
}
}
@Composable
fun DeleteAccountDialog(
viewModel: SettingsViewModel,
scope: CoroutineScope,
context: Context,
showDialog: Boolean,
onDismiss: () -> Unit
) {
if (showDialog) {
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(
text = "Are you sure you want to delete your account",
style = TextStyle(
fontSize = 25.sp,
fontWeight = FontWeight.Bold
)
)
},
text = {
Text(
text = "By deleting your account you will loose all your data which " +
"is not recoverable by any means. To delete Click on the Confirm Button" +
"We will be sad if you leave 💔",
fontSize = 17.sp
)
},
confirmButton = {
BasicButton(text = AppText.delete_account, modifier = Modifier) {
Toast.makeText(
context,
"Account will be deleted after 72 hours",
Toast.LENGTH_SHORT
).show()
viewModel.signOut()
scope.launch {
delay(1000)
restartApp(context)
}
/*viewModel.deleteUser()
viewModel.deleteUserAccount("DELETED")
scope.launch {
delay(1000)
restartApp(context)
}*/
}
},
dismissButton = {
BasicButton(text = AppText.cancel, modifier = Modifier) {
onDismiss()
}
}
)
}
}
fun restartApp(context: Context) {
val packageManager: PackageManager = context.packageManager
val intent: Intent = packageManager.getLaunchIntentForPackage(context.packageName)!!
val componentName: ComponentName = intent.component!!
val restartIntent: Intent = Intent.makeRestartActivityTask(componentName)
context.startActivity(restartIntent)
Runtime.getRuntime().exit(0)
}
| 14
|
Kotlin
|
1
| 9
|
20a9b38cb4ae45572a248f819eca775e2d2f2678
| 12,511
|
Mingle
|
Apache License 2.0
|
kotlin/src/commonMain/kotlin/dev/brella/amber/kotlin/string/parser/modifiers/KotlinTypeParameterModifierAppendable.kt
|
UnderMybrella
| 630,935,125
| false
| null |
package dev.brella.amber.kotlin.string.parser.modifiers
import dev.brella.amber.kotlin.KotlinAppendable
import dev.brella.amber.kotlin.string.parser.KotlinAnnotationAppendable
public interface KotlinTypeParameterModifierAppendable<SELF : KotlinTypeParameterModifierAppendable<SELF>> :
KotlinAppendable<SELF>, KotlinReificationModifierAppendable<SELF>, KotlinVarianceModifierAppendable<SELF>,
KotlinAnnotationAppendable<SELF>
| 0
|
Kotlin
|
0
| 0
|
719160cd27bcddf1ea6db15c5ac4eba57fc6f070
| 434
|
amber
|
MIT License
|
src/main/kotlin/no/nav/syfo/behandler/domain/BehandlerKontor.kt
|
navikt
| 378,118,189
| false
| null |
package no.nav.syfo.behandler.domain
import no.nav.syfo.domain.PartnerId
import no.nav.syfo.domain.Virksomhetsnummer
import java.time.OffsetDateTime
data class BehandlerKontor(
val partnerId: PartnerId,
val herId: Int?,
val navn: String?,
val adresse: String?,
val postnummer: String?,
val poststed: String?,
val orgnummer: Virksomhetsnummer?,
val dialogmeldingEnabled: Boolean,
val system: String?,
val mottatt: OffsetDateTime,
)
fun BehandlerKontor.harKomplettAdresse() = !adresse.isNullOrBlank() && !postnummer.isNullOrBlank() && !poststed.isNullOrBlank()
| 1
|
Kotlin
|
1
| 0
|
2855721889ccadcfa335a073a5a5d04574b628da
| 602
|
isdialogmelding
|
MIT License
|
libs/security/example/app/src/main/kotlin/com/softwareplace/springsecurity/example/handler/AuthorizationHandlerImpl.kt
|
softwareplace
| 749,152,259
| false
|
{"Kotlin": 201707, "Mustache": 12022, "Java": 4578, "Shell": 1291, "Makefile": 762}
|
package com.softwareplace.springsecurity.example.handler
import com.github.softwareplace.springboot.security.authorization.AuthorizationHandler
import org.springframework.stereotype.Component
@Component
class AuthorizationHandlerImpl : AuthorizationHandler
| 0
|
Kotlin
|
0
| 1
|
9d4c43c97b41cf5d645f3540af43b20b208968fd
| 259
|
springboot
|
Apache License 2.0
|
android/src/main/kotlin/com/producement/yubikit_flutter/piv/PivSignAction.kt
|
Producement
| 482,778,301
| false
|
{"Kotlin": 65812, "Swift": 44223, "Dart": 28609, "Ruby": 2379, "Objective-C": 736}
|
package com.producement.yubikit_flutter.piv;
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.yubico.yubikit.android.ui.YubiKeyPromptActivity
import com.yubico.yubikit.core.application.CommandState
import com.yubico.yubikit.core.smartcard.SmartCardConnection
import com.yubico.yubikit.core.util.Pair
import com.yubico.yubikit.piv.KeyType
import com.yubico.yubikit.piv.PivSession
import com.yubico.yubikit.piv.Slot
import java.lang.Exception
import java.security.Signature
class PivSignAction : PivAction() {
companion object {
private const val TAG = "PivSignAction"
fun pivSignIntent(
context: Context,
pin: String, algorithm: String, slot: Int, keyType: Int, message: ByteArray,
): Intent {
Log.d(TAG, "Creating intent")
val intent = YubiKeyPromptActivity.createIntent(context, PivSignAction::class.java)
intent.putExtra("PIV_PIN", pin)
intent.putExtra("PIV_ALGORITHM", algorithm)
intent.putExtra("PIV_SLOT", slot)
intent.putExtra("PIV_KEY_TYPE", keyType)
intent.putExtra("PIV_MESSAGE", message)
return intent
}
}
override fun onYubiKeyConnection(
connection: SmartCardConnection,
extras: Bundle,
commandState: CommandState
): Pair<Int, Intent> {
return tryWithCommand(commandState) {
Log.d(TAG, "Yubikey connection created")
val pin = extras.getString("PIV_PIN")!!
val algorithm = extras.getString("PIV_ALGORITHM")!!
val slot = extras.getInt("PIV_SLOT")
val keyType = extras.getInt("PIV_KEY_TYPE")
val message = extras.getByteArray("PIV_MESSAGE")!!
val pivSession = PivSession(connection)
pivSession.verifyPin(pin.toCharArray())
val signatureAlgorithm = getSignatureAlgorithm(algorithm)
if (signatureAlgorithm == null) {
val result = Intent()
result.putExtra("PIV_ERROR", "unsupported.algorithm.error")
Pair(Activity.RESULT_OK, result)
} else {
val signature = pivSession.sign(
Slot.fromValue(slot),
KeyType.fromValue(keyType),
message,
signatureAlgorithm,
)
Log.d(TAG, "Signature generated")
val result = Intent()
result.putExtra("PIV_RESULT", signature)
Pair(Activity.RESULT_OK, result)
}
}
}
private fun getSignatureAlgorithm(algorithm: String): Signature? {
return when (algorithm) {
"rsaSignatureMessagePKCS1v15SHA512" -> Signature.getInstance("SHA512withRSA")
"ecdsaSignatureMessageX962SHA256" -> Signature.getInstance("SHA256withECDSA")
else -> null
}
}
}
| 0
|
Kotlin
|
0
| 2
|
facc0f4c53847c6522e0098d098b210b22032b43
| 3,014
|
yubikit_flutter
|
MIT License
|
window/window/src/androidTest/java/androidx/window/SidecarCompatTest.kt
|
lyxxman
| 361,157,996
| true
|
{"Java Properties": 50, "Shell": 64, "INI": 3, "Text": 4537, "Gradle": 548, "Markdown": 80, "Ignore List": 36, "Java": 5433, "XML": 14068, "HTML": 17, "Kotlin": 4779, "Python": 33, "JSON": 46, "Proguard": 43, "Protocol Buffer Text Format": 54, "Protocol Buffer": 36, "CMake": 3, "C++": 5, "SVG": 4, "Ant Build System": 5, "Batchfile": 13, "AIDL": 101, "ANTLR": 1, "YAML": 5, "JavaScript": 1, "CSS": 1, "JSON with Comments": 1, "desktop": 1, "Gradle Kotlin DSL": 2}
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Sidecar is deprecated but consuming code must be maintained for compatibility reasons
@file:Suppress("DEPRECATION")
package androidx.window
import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.os.IBinder
import android.view.View
import android.view.Window
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.window.ExtensionInterfaceCompat.ExtensionCallbackInterface
import androidx.window.TestFoldingFeatureUtil.invalidFoldBounds
import androidx.window.TestFoldingFeatureUtil.validFoldBound
import androidx.window.sidecar.SidecarDeviceState
import androidx.window.sidecar.SidecarDisplayFeature
import androidx.window.sidecar.SidecarInterface
import androidx.window.sidecar.SidecarInterface.SidecarCallback
import androidx.window.sidecar.SidecarWindowLayoutInfo
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.argThat
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mockito.`when`
import org.mockito.Mockito.atLeastOnce
import org.mockito.Mockito.doAnswer
import org.mockito.Mockito.mock
import org.mockito.Mockito.reset
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import org.mockito.invocation.InvocationOnMock
/**
* Tests for [SidecarCompat] implementation of [ExtensionInterfaceCompat]. This class
* uses a mocked Sidecar to verify the behavior of the implementation on any hardware.
*
* Because this class extends [SidecarCompatDeviceTest], it will also run the mocked
* versions of methods defined in [CompatDeviceTestInterface].
*/
@LargeTest
@RunWith(AndroidJUnit4::class)
public class SidecarCompatTest : WindowTestBase(), CompatTestInterface {
private lateinit var activity: Activity
private lateinit var sidecarCompat: SidecarCompat
@Before
public fun setUp() {
activity = mock(Activity::class.java)
sidecarCompat = SidecarCompat(mock(SidecarInterface::class.java), SidecarAdapter())
`when`(activity.getResources())
.thenReturn(ApplicationProvider.getApplicationContext<Context>().resources)
val window: Window = spy(TestWindow(activity))
window.attributes.token = mock(IBinder::class.java)
`when`(activity.getWindow()).thenReturn(window)
val mWindowBoundsHelper = TestWindowBoundsHelper()
mWindowBoundsHelper.setCurrentBounds(WINDOW_BOUNDS)
WindowBoundsHelper.setForTesting(mWindowBoundsHelper)
// Setup mocked sidecar responses
val defaultDeviceState = SidecarDeviceState()
SidecarAdapter.setSidecarDevicePosture(
defaultDeviceState,
SidecarDeviceState.POSTURE_HALF_OPENED
)
`when`(sidecarCompat.mSidecar.deviceState).thenReturn(defaultDeviceState)
val sidecarDisplayFeature = newDisplayFeature(
Rect(0, 1, WINDOW_BOUNDS.width(), 1), SidecarDisplayFeature.TYPE_HINGE
)
val sidecarWindowLayoutInfo = SidecarWindowLayoutInfo()
val displayFeatures = listOf(sidecarDisplayFeature)
SidecarAdapter.setSidecarDisplayFeatures(sidecarWindowLayoutInfo, displayFeatures)
`when`(sidecarCompat.mSidecar.getWindowLayoutInfo(any()))
.thenReturn(sidecarWindowLayoutInfo)
}
@After
public fun tearDown() {
WindowBoundsHelper.setForTesting(null)
}
@Test
override fun testGetWindowLayout() {
val fakeSidecarImp = FakeExtensionImp(
newDeviceState(SidecarDeviceState.POSTURE_OPENED),
newWindowLayoutInfo(emptyList())
)
val compat = SidecarCompat(fakeSidecarImp, SidecarAdapter())
val mockCallback = mock(
ExtensionCallbackInterface::class.java
)
compat.setExtensionCallback(mockCallback)
compat.onWindowLayoutChangeListenerAdded(activity)
fakeSidecarImp.triggerGoodSignal()
verify(mockCallback, atLeastOnce()).onWindowLayoutChanged(
eq(activity),
any(WindowLayoutInfo::class.java)
)
}
@Test
public fun testGetWindowLayout_featureWithEmptyBounds() {
// Add a feature with an empty bounds to the reported list
val originalWindowLayoutInfo = sidecarCompat.mSidecar.getWindowLayoutInfo(
getActivityWindowToken(
activity
)
)
val sidecarDisplayFeatures =
SidecarAdapter.getSidecarDisplayFeatures(originalWindowLayoutInfo) ?: emptyList()
val newFeature = SidecarDisplayFeature()
newFeature.rect = Rect()
SidecarAdapter.setSidecarDisplayFeatures(
originalWindowLayoutInfo,
sidecarDisplayFeatures + newFeature
)
// Verify that this feature is skipped.
val windowLayoutInfo = sidecarCompat.getWindowLayoutInfo(activity)
assertEquals(
(sidecarDisplayFeatures.size).toLong(),
windowLayoutInfo.displayFeatures.size.toLong()
)
}
@Test
public fun testGetWindowLayout_foldWithNonZeroArea() {
val originalWindowLayoutInfo = sidecarCompat.mSidecar.getWindowLayoutInfo(
mock(
IBinder::class.java
)
)
val sidecarDisplayFeatures =
SidecarAdapter.getSidecarDisplayFeatures(originalWindowLayoutInfo) ?: emptyList()
val additionalFeatures = listOf(
// Horizontal fold.
newDisplayFeature(
Rect(0, 1, WINDOW_BOUNDS.width(), 2),
SidecarDisplayFeature.TYPE_FOLD
),
// Vertical fold.
newDisplayFeature(
Rect(1, 0, 2, WINDOW_BOUNDS.height()),
SidecarDisplayFeature.TYPE_FOLD
)
)
val replacementFeatures = sidecarDisplayFeatures + additionalFeatures
SidecarAdapter.setSidecarDisplayFeatures(originalWindowLayoutInfo, replacementFeatures)
// Verify that these features are skipped.
val windowLayoutInfo = sidecarCompat.getWindowLayoutInfo(activity)
assertEquals(
(sidecarDisplayFeatures.size).toLong(),
windowLayoutInfo.displayFeatures.size.toLong()
)
}
@Test
public fun testGetWindowLayout_hingeNotSpanningEntireWindow() {
val originalWindowLayoutInfo = sidecarCompat.mSidecar.getWindowLayoutInfo(
mock(
IBinder::class.java
)
)
val sidecarDisplayFeatures =
SidecarAdapter.getSidecarDisplayFeatures(originalWindowLayoutInfo) ?: emptyList()
val additionalFeatures = listOf(
// Horizontal hinge.
newDisplayFeature(
Rect(0, 1, WINDOW_BOUNDS.width() - 1, 2),
SidecarDisplayFeature.TYPE_FOLD
),
// Vertical hinge.
newDisplayFeature(
Rect(1, 0, 2, WINDOW_BOUNDS.height() - 1),
SidecarDisplayFeature.TYPE_FOLD
)
)
val replacementFeatures = sidecarDisplayFeatures + additionalFeatures
SidecarAdapter.setSidecarDisplayFeatures(originalWindowLayoutInfo, replacementFeatures)
// Verify that these features are skipped.
val windowLayoutInfo = sidecarCompat.getWindowLayoutInfo(activity)
assertEquals(
(sidecarDisplayFeatures.size).toLong(),
windowLayoutInfo.displayFeatures.size.toLong()
)
}
@Test
public fun testGetWindowLayout_foldNotSpanningEntireWindow() {
val originalWindowLayoutInfo = sidecarCompat.mSidecar.getWindowLayoutInfo(
mock(
IBinder::class.java
)
)
val sidecarDisplayFeatures =
SidecarAdapter.getSidecarDisplayFeatures(originalWindowLayoutInfo) ?: emptyList()
val additionalFeatures = listOf(
// Horizontal fold.
newDisplayFeature(
Rect(0, 1, WINDOW_BOUNDS.width() - 1, 2),
SidecarDisplayFeature.TYPE_FOLD
),
// Vertical fold.
newDisplayFeature(
Rect(1, 0, 2, WINDOW_BOUNDS.height() - 1),
SidecarDisplayFeature.TYPE_FOLD
)
)
val replacementFeatures = sidecarDisplayFeatures + additionalFeatures
SidecarAdapter.setSidecarDisplayFeatures(originalWindowLayoutInfo, replacementFeatures)
// Verify that these features are skipped.
val windowLayoutInfo = sidecarCompat.getWindowLayoutInfo(activity)
assertEquals(
(sidecarDisplayFeatures.size).toLong(),
windowLayoutInfo.displayFeatures.size.toLong()
)
}
override fun testExtensionCallback_filterRemovesInvalidValues() {
val fakeSidecarImp = FakeExtensionImp(
newDeviceState(SidecarDeviceState.POSTURE_OPENED),
newWindowLayoutInfo(emptyList())
)
val compat = SidecarCompat(fakeSidecarImp, SidecarAdapter())
val mockCallback = mock(
ExtensionCallbackInterface::class.java
)
compat.setExtensionCallback(mockCallback)
compat.onWindowLayoutChangeListenerAdded(activity)
fakeSidecarImp.triggerMalformedSignal()
verify(mockCallback).onWindowLayoutChanged(
any(),
argThat { windowLayoutInfo -> windowLayoutInfo.displayFeatures.isEmpty() }
)
}
@Test
override fun testSetExtensionCallback() {
val sidecarCallbackCaptor = ArgumentCaptor.forClass(
SidecarCallback::class.java
)
// Verify that the sidecar got the callback set
val callback = mock(
ExtensionCallbackInterface::class.java
)
sidecarCompat.setExtensionCallback(callback)
verify(sidecarCompat.mSidecar)
.setSidecarCallback(sidecarCallbackCaptor.capture())
// Verify that the callback set for sidecar propagates the device state callback
val sidecarDeviceState = SidecarDeviceState()
SidecarAdapter.setSidecarDevicePosture(
sidecarDeviceState,
SidecarDeviceState.POSTURE_HALF_OPENED
)
sidecarCallbackCaptor.value.onDeviceStateChanged(sidecarDeviceState)
// Verify that the callback set for sidecar propagates the window layout callback when a
// window layout changed listener has been added.
sidecarCompat.onWindowLayoutChangeListenerAdded(activity)
val bounds = Rect(0, 1, WINDOW_BOUNDS.width(), 1)
val sidecarDisplayFeature = newDisplayFeature(
bounds,
SidecarDisplayFeature.TYPE_HINGE
)
val sidecarWindowLayoutInfo = SidecarWindowLayoutInfo()
val displayFeatures = listOf(sidecarDisplayFeature)
SidecarAdapter.setSidecarDisplayFeatures(sidecarWindowLayoutInfo, displayFeatures)
sidecarCallbackCaptor.value.onWindowLayoutChanged(
getActivityWindowToken(
activity
),
sidecarWindowLayoutInfo
)
val windowLayoutInfoCaptor = ArgumentCaptor.forClass(
WindowLayoutInfo::class.java
)
verify(callback).onWindowLayoutChanged(
eq(activity),
windowLayoutInfoCaptor.capture()
)
val capturedLayout = windowLayoutInfoCaptor.value
assertEquals(1, capturedLayout.displayFeatures.size.toLong())
val capturedDisplayFeature = capturedLayout.displayFeatures[0]
val foldingFeature = capturedDisplayFeature as FoldingFeature
assertNotNull(foldingFeature)
assertEquals(bounds, capturedDisplayFeature.bounds)
}
@Test
public fun testMissingCallToOnWindowLayoutChangedListenerAdded() {
val sidecarCallbackCaptor = ArgumentCaptor.forClass(
SidecarCallback::class.java
)
// Verify that the sidecar got the callback set
val callback = mock(
ExtensionCallbackInterface::class.java
)
sidecarCompat.setExtensionCallback(callback)
verify(sidecarCompat.mSidecar)
.setSidecarCallback(sidecarCallbackCaptor.capture())
// Verify that the callback set for sidecar propagates the window layout callback when a
// window layout changed listener has been added.
val sidecarDisplayFeature = SidecarDisplayFeature()
sidecarDisplayFeature.type = SidecarDisplayFeature.TYPE_HINGE
val bounds = Rect(1, 2, 3, 4)
sidecarDisplayFeature.rect = bounds
val sidecarWindowLayoutInfo = SidecarWindowLayoutInfo()
val displayFeatures = listOf(sidecarDisplayFeature)
SidecarAdapter.setSidecarDisplayFeatures(sidecarWindowLayoutInfo, displayFeatures)
val windowToken = mock(IBinder::class.java)
sidecarCallbackCaptor.value.onWindowLayoutChanged(
windowToken,
sidecarWindowLayoutInfo
)
verifyZeroInteractions(callback)
}
@Test
override fun testOnWindowLayoutChangeListenerAdded() {
val windowToken = getActivityWindowToken(
activity
)
sidecarCompat.onWindowLayoutChangeListenerAdded(activity)
verify(sidecarCompat.mSidecar).onWindowLayoutChangeListenerAdded(windowToken)
verify(sidecarCompat.mSidecar).onDeviceStateListenersChanged(false)
}
@Test
public fun testOnWindowLayoutChangeListenerAdded_emitInitialValue() {
val layoutInfo = SidecarWindowLayoutInfo()
val expectedLayoutInfo = WindowLayoutInfo(listOf())
val listener = mock(
ExtensionCallbackInterface::class.java
)
sidecarCompat.setExtensionCallback(listener)
`when`(sidecarCompat.mSidecar.getWindowLayoutInfo(any()))
.thenReturn(layoutInfo)
sidecarCompat.onWindowLayoutChangeListenerAdded(activity)
verify(listener).onWindowLayoutChanged(
activity, expectedLayoutInfo
)
}
@Test
public fun testOnWindowLayoutChangeListenerAdded_emitInitialValueDelayed() {
val layoutInfo = SidecarWindowLayoutInfo()
val expectedLayoutInfo = WindowLayoutInfo(listOf())
val listener = mock(
ExtensionCallbackInterface::class.java
)
sidecarCompat.setExtensionCallback(listener)
`when`(sidecarCompat.mSidecar.getWindowLayoutInfo(any()))
.thenReturn(layoutInfo)
val fakeView = mock(View::class.java)
val fakeWindow: Window = TestWindow(activity, fakeView)
doAnswer { invocation: InvocationOnMock ->
val stateChangeListener = invocation.getArgument<View.OnAttachStateChangeListener>(0)
fakeWindow.attributes.token = mock(IBinder::class.java)
stateChangeListener.onViewAttachedToWindow(fakeView)
null
}.`when`(fakeView).addOnAttachStateChangeListener(any())
`when`(activity.window).thenReturn(fakeWindow)
sidecarCompat.onWindowLayoutChangeListenerAdded(activity)
verify(listener).onWindowLayoutChanged(
activity, expectedLayoutInfo
)
}
@Test
override fun testOnWindowLayoutChangeListenerRemoved() {
val windowToken = getActivityWindowToken(
activity
)
sidecarCompat.onWindowLayoutChangeListenerRemoved(activity)
verify(sidecarCompat.mSidecar).onWindowLayoutChangeListenerRemoved(
eq(windowToken)
)
}
@Test
public fun testOnDeviceStateListenersChanged() {
sidecarCompat.onWindowLayoutChangeListenerAdded(activity)
sidecarCompat.onWindowLayoutChangeListenerRemoved(activity)
verify(sidecarCompat.mSidecar).onDeviceStateListenersChanged(true)
}
@Test
public fun testOnDeviceStateChangedUpdatesWindowLayout() {
val fakeSidecarImp = FakeExtensionImp(
newDeviceState(SidecarDeviceState.POSTURE_CLOSED),
validWindowLayoutInfo()
)
val compat = SidecarCompat(fakeSidecarImp, SidecarAdapter())
val mockCallback = mock(
ExtensionCallbackInterface::class.java
)
compat.setExtensionCallback(mockCallback)
compat.onWindowLayoutChangeListenerAdded(activity)
val windowLayoutCaptor = ArgumentCaptor.forClass(
WindowLayoutInfo::class.java
)
reset(mockCallback)
fakeSidecarImp.triggerDeviceState(newDeviceState(SidecarDeviceState.POSTURE_OPENED))
verify(mockCallback)
.onWindowLayoutChanged(eq(activity), windowLayoutCaptor.capture())
var capturedFoldingFeature = windowLayoutCaptor.value
.displayFeatures[0] as FoldingFeature
assertEquals(
FoldingFeature.STATE_FLAT.toLong(),
capturedFoldingFeature.state.toLong()
)
reset(mockCallback)
fakeSidecarImp.triggerDeviceState(newDeviceState(SidecarDeviceState.POSTURE_HALF_OPENED))
verify(mockCallback)
.onWindowLayoutChanged(eq(activity), windowLayoutCaptor.capture())
capturedFoldingFeature = windowLayoutCaptor.value.displayFeatures[0] as FoldingFeature
assertEquals(
FoldingFeature.STATE_HALF_OPENED.toLong(),
capturedFoldingFeature.state.toLong()
)
// No display features must be reported in closed state or flipped state.
reset(mockCallback)
fakeSidecarImp.triggerDeviceState(newDeviceState(SidecarDeviceState.POSTURE_CLOSED))
fakeSidecarImp.triggerDeviceState(newDeviceState(SidecarDeviceState.POSTURE_FLIPPED))
verify(mockCallback)
.onWindowLayoutChanged(eq(activity), windowLayoutCaptor.capture())
assertTrue(windowLayoutCaptor.value.displayFeatures.isEmpty())
}
private class FakeExtensionImp(
private var deviceState: SidecarDeviceState,
private var info: SidecarWindowLayoutInfo
) : SidecarInterface {
private var callback: SidecarCallback
private val tokens = mutableListOf<IBinder>()
override fun setSidecarCallback(callback: SidecarCallback) {
this.callback = callback
}
override fun getWindowLayoutInfo(windowToken: IBinder): SidecarWindowLayoutInfo {
return info
}
override fun onWindowLayoutChangeListenerAdded(windowToken: IBinder) {
tokens.add(windowToken)
}
override fun onWindowLayoutChangeListenerRemoved(windowToken: IBinder) {
tokens.remove(windowToken)
}
override fun getDeviceState(): SidecarDeviceState {
return deviceState
}
override fun onDeviceStateListenersChanged(isEmpty: Boolean) {}
fun triggerMalformedSignal() {
triggerSignal(malformedWindowLayoutInfo())
}
fun triggerGoodSignal() {
triggerSignal(validWindowLayoutInfo())
}
fun triggerSignal(info: SidecarWindowLayoutInfo) {
this.info = info
for (token in tokens) {
callback.onWindowLayoutChanged(token, info)
}
}
fun triggerDeviceState(state: SidecarDeviceState) {
deviceState = state
callback.onDeviceStateChanged(state)
}
private fun malformedWindowLayoutInfo(): SidecarWindowLayoutInfo {
val malformedFeatures = mutableListOf<SidecarDisplayFeature>()
for (malformedBound in invalidFoldBounds(WINDOW_BOUNDS)) {
malformedFeatures.add(
newDisplayFeature(
malformedBound,
SidecarDisplayFeature.TYPE_FOLD
)
)
}
for (malformedBound in invalidFoldBounds(WINDOW_BOUNDS)) {
malformedFeatures.add(
newDisplayFeature(
malformedBound,
SidecarDisplayFeature.TYPE_HINGE
)
)
}
return newWindowLayoutInfo(malformedFeatures)
}
init {
callback = object : SidecarCallback {
override fun onDeviceStateChanged(newDeviceState: SidecarDeviceState) {}
override fun onWindowLayoutChanged(
windowToken: IBinder,
newLayout: SidecarWindowLayoutInfo
) {
}
}
}
}
private companion object {
private val WINDOW_BOUNDS = Rect(1, 1, 50, 100)
private fun newDisplayFeature(rect: Rect, type: Int): SidecarDisplayFeature {
val feature = SidecarDisplayFeature()
feature.rect = rect
feature.type = type
return feature
}
private fun newWindowLayoutInfo(
features: List<SidecarDisplayFeature>
): SidecarWindowLayoutInfo {
val info = SidecarWindowLayoutInfo()
SidecarAdapter.setSidecarDisplayFeatures(info, features)
return info
}
private fun validWindowLayoutInfo(): SidecarWindowLayoutInfo {
val goodFeatures = listOf(
newDisplayFeature(
validFoldBound(WINDOW_BOUNDS),
SidecarDisplayFeature.TYPE_FOLD
)
)
return newWindowLayoutInfo(goodFeatures)
}
private fun newDeviceState(posture: Int): SidecarDeviceState {
val state = SidecarDeviceState()
SidecarAdapter.setSidecarDevicePosture(state, posture)
return state
}
}
}
| 0
| null |
0
| 0
|
7c1c1e4e879a602c7a4da894efed13e71b1cd124
| 22,628
|
androidx
|
Apache License 2.0
|
maps-wrapper/src/main/java/maps/map/TileOverlay.kt
|
sandorbogyo
| 491,430,310
| true
|
{"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Text": 2, "Ignore List": 3, "INI": 1, "Java": 79, "XML": 42, "Kotlin": 15, "Proguard": 1}
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package maps.map;
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposeNode
import androidx.compose.runtime.currentComposer
import maps.wrapper.TileOverlay
import maps.wrapper.TileOverlayOptions
import maps.wrapper.TileProvider
private class TileOverlayNode(
var tileOverlay: TileOverlay,
var onTileOverlayClick: (TileOverlay) -> Unit
) : MapNode {
override fun onRemoved() {
tileOverlay.remove()
}
}
/**
* A composable for a tile overlay on the map.
*
* @param tileProvider the tile provider to use for this tile overlay
* @param fadeIn boolean indicating whether the tiles should fade in
* @param transparency the transparency of the tile overlay
* @param visible the visibility of the tile overlay
* @param zIndex the z-index of the tile overlay
* @param onClick a lambda invoked when the tile overlay is clicked
*/
@Composable
fun TileOverlay(
tileProvider: TileProvider,
fadeIn: Boolean = true,
transparency: Float = 0f,
visible: Boolean = true,
zIndex: Float = 0f,
onClick: (TileOverlay) -> Unit = {},
) {
val mapApplier = currentComposer.applier as MapApplier?
ComposeNode<TileOverlayNode, MapApplier>(
factory = {
val tileOverlay = mapApplier?.map?.addTileOverlay(
TileOverlayOptions()
.tileProvider(tileProvider)
.fadeIn(fadeIn)
.transparency(transparency)
.visible(visible)
.zIndex(zIndex)
) ?: error("Error adding tile overlay")
TileOverlayNode(tileOverlay, onClick)
},
update = {
update(onClick) { this.onTileOverlayClick = it }
set(tileProvider) {
this.tileOverlay.remove()
this.tileOverlay = mapApplier?.map?.addTileOverlay(
TileOverlayOptions()
.tileProvider(tileProvider)
.fadeIn(fadeIn)
.transparency(transparency)
.visible(visible)
.zIndex(zIndex)
) ?: error("Error adding tile overlay")
}
set(fadeIn) { this.tileOverlay.setFadeIn(it) }
set(transparency) { this.tileOverlay.setTransparency(it) }
set(visible) { this.tileOverlay.setVisible(it) }
set(zIndex) { this.tileOverlay.zIndex = it }
}
)
}
| 0
|
Java
|
0
| 0
|
1b8f7b47d54c8296a6dc7a7b5c9a2acf7902c414
| 3,060
|
ComposeMapsWrapper
|
MIT License
|
src/main/kotlin/uk/gov/justice/probation/courtcaseservice/service/ProbationCaseEngagementService.kt
|
ministryofjustice
| 215,829,678
| false
|
{"Gradle": 2, "YAML": 32, "JSON": 162, "Dockerfile": 4, "Shell": 14, "Java Properties": 1, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Markdown": 19, "SVG": 1, "Nginx": 2, "INI": 1, "Java": 409, "Kotlin": 100, "XML": 3, "SQL": 48, "reStructuredText": 6, "HTTP": 1, "PLpgSQL": 84, "Mustache": 2}
|
package uk.gov.justice.probation.courtcaseservice.service
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import uk.gov.justice.probation.courtcaseservice.client.model.DeliusOffenderDetail
import uk.gov.justice.probation.courtcaseservice.client.model.ProbationStatus
import uk.gov.justice.probation.courtcaseservice.jpa.entity.OffenderEntity
import uk.gov.justice.probation.courtcaseservice.jpa.entity.OffenderProbationStatus
import uk.gov.justice.probation.courtcaseservice.jpa.repository.DefendantRepository
import uk.gov.justice.probation.courtcaseservice.jpa.repository.OffenderRepository
@Service
class ProbationCaseEngagementService(
val defendantRepository: DefendantRepository,
val offenderRepository: OffenderRepository,
val telemetryService: TelemetryService
) {
private companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
fun updateMatchingDefendantsWithOffender(deliusOffenderDetail: DeliusOffenderDetail?) {
val matchingDefendants = defendantRepository.findMatchingDefendants(
deliusOffenderDetail?.identifiers?.pnc,
deliusOffenderDetail?.dateOfBirth,
deliusOffenderDetail?.name?.forename,
deliusOffenderDetail?.name?.surname
)
if (matchingDefendants.isNotEmpty()) {
log.debug("Mapping new offender with details {}", deliusOffenderDetail)
val newOffender = createOffender(deliusOffenderDetail)
matchingDefendants.forEach { it ->
it.offender = newOffender
defendantRepository.save(it)
telemetryService.trackPiCNewEngagementDefendantLinkedEvent(it)
}
} else {
log.debug("No matching defendants found with {}", deliusOffenderDetail)
}
}
fun createOffender(deliusOffenderDetail: DeliusOffenderDetail?): OffenderEntity? {
log.debug("Creating new offender with details {}", deliusOffenderDetail)
val newOffender = OffenderEntity(
null,
deliusOffenderDetail?.identifiers?.crn,
deliusOffenderDetail?.identifiers?.pnc,
"",
emptyList(),
OffenderProbationStatus.NOT_SENTENCED,
true,
false,
false,
false,
null
)
return offenderRepository.save(newOffender)
}
}
| 18
|
Java
|
0
| 0
|
0efe7628b07f60119b93658b15b07f797b55f078
| 2,452
|
court-case-service
|
MIT License
|
app/src/main/java/com/handstandsam/shoppingapp/features/itemdetail/ItemDetailPresenter.kt
|
MaTriXy
| 121,965,877
| true
|
{"Kotlin": 82413}
|
package com.handstandsam.shoppingapp.features.itemdetail
import android.content.Intent
import com.handstandsam.shoppingapp.models.Item
import com.handstandsam.shoppingapp.repository.CheckoutCart
import com.handstandsam.shoppingapp.repository.SessionManager
import javax.inject.Inject
class ItemDetailPresenter(private val view: ItemDetailActivity.ItemDetailView) {
@Inject
lateinit internal var sessionManager: SessionManager
@Inject
lateinit internal var cart: CheckoutCart
lateinit internal var item: Item
init {
view.appComponent.inject(this)
}
fun onResume(intent: Intent) {
val extras = intent.extras
val item = extras!!.get(BUNDLE_PARAM_ITEM) as Item
this.item = item
view.setLabel(item.label!!)
view.setImageUrl(item.image!!)
view.setActionBarTitle(item.label!!)
}
fun addToCardClicked() {
cart.addItem(item)
view.showToast(item.label!! + " added to cart.")
}
companion object {
val BUNDLE_PARAM_ITEM = "item"
}
}
| 0
|
Kotlin
|
0
| 0
|
7d4e6fcf91ea557a91807c20c700d7b772b27f7e
| 1,065
|
ShoppingApp
|
Apache License 2.0
|
GinGer/app/src/main/java/com/example/ginger/MainActivity.kt
|
shikhargupta442003
| 785,548,989
| false
|
{"Kotlin": 11179}
|
package com.example.ginger
import android.os.Bundle
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private val drawerLayout: DrawerLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)
val toggle = ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.open_nav,
R.string.close_nav
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, HomeFragment()).commit()
navigationView.setCheckedItem(R.id.nav_home)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_home -> supportFragmentManager.beginTransaction().replace(R.id.fragment_container, HomeFragment()).commit()
R.id.nav_settings -> supportFragmentManager.beginTransaction().replace(R.id.fragment_container, SettingsFragment()).commit()
R.id.nav_share -> supportFragmentManager.beginTransaction().replace(R.id.fragment_container, ShareFragment()).commit()
R.id.nav_about -> supportFragmentManager.beginTransaction().replace(R.id.fragment_container, AboutFragment()).commit()
R.id.nav_logout -> Toast.makeText(this, "Logout!", Toast.LENGTH_SHORT).show()
}
drawerLayout!!.closeDrawer(GravityCompat.START)
return true
}
override fun onBackPressed() {
if (drawerLayout!!.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a68f202d774285605a0b715745d2b3c837bf5636
| 2,680
|
Vihaan007
|
MIT License
|
src/main/kotlin/com/solarexsoft/kotlinexercise/K5.7.kt
|
flyfire
| 113,817,538
| false
| null |
package com.solarexsoft.kotlinexercise
import java.io.OutputStream
import java.nio.charset.Charset
import kotlin.math.log
/**
* Created by houruhou on 2018/11/7.
* Desc:
*/
fun log1(tag: String, target: OutputStream, message: String) {
target.write("$tag $message\n".toByteArray())
}
fun log2(tag: String) = fun(target: OutputStream) = fun(message: Any?) = target.write("$tag,$message\n".toByteArray())
fun <P1, P2, P3, R> Function3<P1, P2, P3, R>.curried()
= fun(p1: P1) = fun(p2: P2) = fun(p3: P3) = this(p1, p2, p3)
val makeString = fun(byteArray: ByteArray, charset: Charset): String{
return String(byteArray, charset)
}
fun <P1,P2,R> Function2<P1,P2,R>.partial1(p1: P1) = fun(p2: P2) = this(p1,p2)
fun <P1,P2,R> Function2<P1,P2,R>.partial2(p2: P2) = fun(p1: P1) = this(p1,p2)
val makeStringFromGBK = makeString.partial2(charset("GBK"))
fun main(args: Array<String>) {
log1("Solarex", System.out, "Hello,world")
log2("flyfire")(System.out)("Hello,Kotlin")
::log1.curried()("SKR")(System.out)("skr,skr")
val consoleLogWithTag = ::log1.curried()("KrisWu")(System.out)
consoleLogWithTag("awesome")
val bytes = "眼镜蛇机动".toByteArray(charset("GBK"))
println(makeStringFromGBK(bytes))
}
| 0
|
Kotlin
|
0
| 0
|
0fa02e6096bf8089f205d4423473d79593bad094
| 1,231
|
JavaWithKotlin
|
Apache License 2.0
|
firestore/src/main/java/de/sipgate/federmappe/firestore/FirestoreTimestampDataNormalizer.kt
|
sipgate
| 729,069,301
| false
|
{"Kotlin": 104510}
|
package de.sipgate.federmappe.firestore
import de.sipgate.federmappe.common.decoder.DataNormalizer
class FirestoreTimestampDataNormalizer : DataNormalizer {
override fun normalize(data: Map<String, Any?>): Map<String, Any?> =
data.normalizeStringMapNullable()
}
| 1
|
Kotlin
|
0
| 1
|
d6cb7d137e82301bd59d70be8ec8b0ebae4b069d
| 276
|
federmappe
|
Apache License 2.0
|
app/src/main/java/bill/kanban/atomic/AtomicInterfaces.kt
|
emanuelmch
| 129,978,558
| false
| null |
package bill.kanban.atomic
abstract class AtomicPresenter<Atom : Any, in Action : Any?> {
lateinit var currentState: Atom
private set
var view: AtomicView<Atom> = EmptyAtomicView()
private set
abstract val initialState: Atom
fun attach(view: AtomicView<Atom>) {
this.currentState = initialState
this.view = view
view.render(currentState)
onViewAttached(view)
}
abstract fun onViewAttached(view: AtomicView<Atom>)
open fun beforeViewDetached() {}
fun detach() {
beforeViewDetached()
view = EmptyAtomicView()
}
fun emitAction(action: Action) {
if (view is EmptyAtomicView) return
currentState = reduce(currentState, action)
view.render(currentState)
}
abstract fun reduce(atom: Atom, action: Action): Atom
}
interface AtomicView<in Atom> {
fun render(atom: Atom)
}
class EmptyAtomicView<in Atom> : AtomicView<Atom> {
override fun render(atom: Atom) {}
}
| 0
|
Kotlin
|
0
| 0
|
1a41731f90fd38690c5651031068455d007eee51
| 1,011
|
KanbanLite
|
MIT License
|
app/src/main/java/org/cocos2dx/lib/Cocos2dxEditText.kt
|
geode-sdk
| 495,234,000
| false
|
{"Kotlin": 315657, "C++": 11054, "CMake": 1491}
|
package org.cocos2dx.lib
import android.content.Context
import android.view.KeyEvent
import androidx.appcompat.widget.AppCompatEditText
class Cocos2dxEditText(context: Context) : AppCompatEditText(context) {
var cocos2dxGLSurfaceView: Cocos2dxGLSurfaceView? = null
override fun onKeyDown(keyCode: Int, keyEvent: KeyEvent): Boolean {
super.onKeyDown(keyCode, keyEvent)
if (keyCode != KeyEvent.KEYCODE_BACK) {
return true
}
cocos2dxGLSurfaceView?.requestFocus()
return true
}
}
| 6
|
Kotlin
|
19
| 45
|
b60c564173161894599aec8db237cde1ffb8a3cc
| 542
|
android-launcher
|
Boost Software License 1.0
|
app/src/main/java/org/cocos2dx/lib/Cocos2dxEditText.kt
|
geode-sdk
| 495,234,000
| false
|
{"Kotlin": 315657, "C++": 11054, "CMake": 1491}
|
package org.cocos2dx.lib
import android.content.Context
import android.view.KeyEvent
import androidx.appcompat.widget.AppCompatEditText
class Cocos2dxEditText(context: Context) : AppCompatEditText(context) {
var cocos2dxGLSurfaceView: Cocos2dxGLSurfaceView? = null
override fun onKeyDown(keyCode: Int, keyEvent: KeyEvent): Boolean {
super.onKeyDown(keyCode, keyEvent)
if (keyCode != KeyEvent.KEYCODE_BACK) {
return true
}
cocos2dxGLSurfaceView?.requestFocus()
return true
}
}
| 6
|
Kotlin
|
19
| 45
|
b60c564173161894599aec8db237cde1ffb8a3cc
| 542
|
android-launcher
|
Boost Software License 1.0
|
app-common/src/commonMain/kotlin/dev/garage/rpm/app/common/ui/base/BackHandler.kt
|
vchernyshov
| 249,563,649
| false
| null |
package dev.garage.rpm.app.common.ui.base
interface BackHandler {
fun handleBack(): Boolean
}
| 7
|
Kotlin
|
2
| 12
|
902dcd41c1aae758200f427b2a95968a53f33bad
| 98
|
reaktive-pm
|
MIT License
|
BooksSearchApp/app/src/main/java/com/example/bookssearchapp/GetBook.kt
|
sad786
| 196,528,384
| false
| null |
package com.example.bookssearchapp
import android.net.Uri
import java.net.HttpURLConnection
import java.net.URL
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.IOException
import java.io.InputStream
class GetBook
{
companion object{
private const val WEB_URL = "https://www.googleapis.com/books/v1/volumes?"
const val QUERY = "q"
const val MAX = "maxResults"
const val PRINT_TYPE = "printType"
fun getBookInfo(query:String):String{
val uriBuilder:Uri = Uri.parse(WEB_URL).buildUpon().
appendQueryParameter(QUERY,query).
appendQueryParameter(MAX,"5").
appendQueryParameter(PRINT_TYPE,"books").
build()
val builder = StringBuilder()
var inputStream:InputStream? = null
var reader:BufferedReader?=null
try{
val url = URL(uriBuilder.toString())
println(url.toString())
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()
inputStream = connection.inputStream
reader = BufferedReader(InputStreamReader(inputStream))
var line = reader.readLine()
while(line!=null)
{
builder.append(line)
line = reader.readLine()
}
}catch(io:IOException){
reader?.close()
inputStream?.close()
println("=> ${io.message}")
}
return if(builder.isEmpty())"No Data Found" else builder.toString()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b87caf8ac3668f96629677ed5342b89ac151629a
| 1,752
|
AndroidProjects
|
MIT License
|
projects/make-recall-decisions-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/integrations/delius/document/entity/Document.kt
|
ministryofjustice
| 500,855,647
| false
|
{"Kotlin": 4250610, "HTML": 70066, "D2": 42781, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
|
package uk.gov.justice.digital.hmpps.integrations.delius.document.entity
import jakarta.persistence.*
import org.hibernate.annotations.Immutable
import org.hibernate.annotations.SQLRestriction
import java.time.Instant
import java.time.ZonedDateTime
@Entity
@Immutable
@Table(name = "document")
@SQLRestriction("soft_deleted = 0")
class DocumentEntity(
@ManyToOne
@JoinColumn(name = "offender_id")
val person: Person,
@Column(name = "alfresco_document_id")
val alfrescoId: String,
@Column(name = "primary_key_id")
val primaryKeyId: Long,
@Column(name = "document_name")
val name: String,
@Column(name = "document_type")
val type: String,
@Column(name = "table_name")
val tableName: String?,
@Column(name = "template_name")
val templateName: String?,
@Column(name = "created_datetime")
val createdAt: ZonedDateTime,
@Column(name = "last_saved")
val lastSaved: ZonedDateTime,
@Column(name = "created_by_user_id")
val createdByUserId: Long,
@Column(name = "last_updated_user_id")
val lastUpdatedUserId: Long,
@Column(name = "soft_deleted", columnDefinition = "number")
val softDeleted: Boolean = false,
@Id
@Column(name = "document_id")
val id: Long,
)
interface Document {
val alfrescoId: String
val name: String
val type: String
val tableName: String
val createdAt: Instant?
val lastUpdatedAt: Instant?
val author: String?
val description: String?
val eventId: Long?
}
@Immutable
@Table(name = "offender")
@Entity(name = "DocumentPerson")
@SQLRestriction("soft_deleted = 0")
class Person(
@Id
@Column(name = "offender_id")
val id: Long,
@Column(columnDefinition = "char(7)")
val crn: String,
@Column(columnDefinition = "number")
val softDeleted: Boolean = false
)
| 3
|
Kotlin
|
0
| 2
|
76197df3761bc90253cbf0ec8854a9324d807a7c
| 1,857
|
hmpps-probation-integration-services
|
MIT License
|
input/core/src/commonMain/kotlin/symphony/Visibility.kt
|
aSoft-Ltd
| 632,021,007
| false
| null |
@file:JsExport
package symphony
import kollections.JsExport
sealed class Visibility {
object Visible : Visibility()
object Hidden : Visibility()
val isVisible get() = this is Visible
val isHidden get() = this is Hidden
}
| 0
|
Kotlin
|
0
| 0
|
2cc87fa8e74c9602759117b4d854daaaf331be73
| 240
|
symphony
|
MIT License
|
cexup-data-storage/src/main/java/com/trian/data_storage/room/dao/NurseDao.kt
|
triandamai
| 388,050,344
| false
| null |
package com.trian.data_storage.room.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import com.trian.data_storage.room.entity.Nurse
@SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
@Dao
interface NurseDao {
@Query("SELECT * FROM tb_nurse")
fun allNurse(): LiveData<List<Nurse?>?>?
@Insert
fun insert(nurse:Nurse?)
@Update
fun update(nurse: Nurse?)
@Delete
fun delete(nurse: Nurse?)
}
| 0
| null |
0
| 0
|
dc904e6fcfae22774ef05a39cd3ead78d918fe3e
| 434
|
cexup-mobile-module
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.