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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/prime/media/impl/LibraryViewModel.kt | iZakirSheikh | 506,656,610 | false | null | package com.prime.media.impl
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ClearAll
import androidx.compose.material.icons.outlined.Error
import androidx.compose.material.icons.outlined.Message
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.media3.common.C
import com.prime.media.R
import com.prime.media.core.compose.Channel
import com.prime.media.core.db.toMediaItem
import com.prime.media.core.db.uri
import com.prime.media.core.playback.MediaItem
import com.prime.media.core.playback.Playback
import com.prime.media.core.playback.Remote
import com.prime.media.core.util.toMediaItem
import com.prime.media.library.Library
import com.primex.core.DahliaYellow
import com.primex.core.MetroGreen
import com.primex.core.Rose
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch
import javax.inject.Inject
private const val TAG = "LibraryViewModel"
private const val CAROUSAL_DELAY_MILLS = 10_000L // 10 seconds
/**
* Stop observing as soon as timeout.
*/
private val TimeOutPolicy = SharingStarted.Lazily
private const val SHOW_CASE_MAX_ITEMS = 20
@HiltViewModel
class LibraryViewModel @Inject constructor(
repository: Repository,
private val remote: Remote,
private val channel: Channel
) : ViewModel(), Library {
override val recent = repository.playlist(Playback.PLAYLIST_RECENT)
override val carousel = repository
.recent(SHOW_CASE_MAX_ITEMS)
.transform { list ->
if (list.isEmpty()) {
emit(null)
return@transform
}
var current = 0
while (true) {
if (current >= list.size)
current = 0
emit(list[current])
current++
kotlinx.coroutines.delay(CAROUSAL_DELAY_MILLS)
}
}
.stateIn(viewModelScope, TimeOutPolicy, null)
override val newlyAdded = repository
.observe(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI)
.map {
repository.getAudios(
order = MediaStore.Audio.Media.DATE_MODIFIED,
ascending = false,
offset = 0,
limit = SHOW_CASE_MAX_ITEMS
)
}
override fun onClickRecentFile(uri: String) {
viewModelScope.launch {
val isAlreadyInPlaylist = remote.seekTo(Uri.parse(uri))
// since it is already in the playlist seek to it and return; it will start playing
// maybe call play
if (isAlreadyInPlaylist)
return@launch
// Since the item is definitely not in the queue, present a message to the user to inquire
// about their preference. If the user agrees, the playlist will be reset, and the recent
// item will be added to the playlist, initiating playback from this item's index.
// If the user decides otherwise, the item will be added to the queue following the current queue order.
val res = channel.show(
R.string.msg_library_recent_click,
action = R.string.reset,
leading = Icons.Outlined.Message,
accent = Color.MetroGreen
)
val files = recent.firstOrNull()
val file = files?.find { it.uri == uri }
if (files == null || file == null) {
channel.show(
R.string.msg_unknown_error,
leading = Icons.Outlined.Error,
accent = Color.Rose
)
return@launch
}
if (res != Channel.Result.ActionPerformed) {
remote.add(file.toMediaItem, index = remote.nextIndex)
remote.seekTo(Uri.parse(uri))
return@launch
}
remote.clear()
val index = files.indexOf(file)
remote.set(files.map { it.toMediaItem })
remote.seekTo(index.coerceAtLeast(0), C.TIME_UNSET)
remote.play(true)
}
}
override fun onClickRecentAddedFile(id: Long) {
viewModelScope.launch {
// null case should not happen; bacese that measns some weired error.
val files = newlyAdded.firstOrNull()
val item = files?.find { it.id == id }
if (files == null || item == null) {
channel.show(
R.string.msg_unknown_error,
R.string.error,
leading = Icons.Outlined.Error,
accent = Color.Rose
)
return@launch
}
val isAlreadyInPlaylist = remote.seekTo(item.uri)
// since it is already in the playlist seek to it and return; it will start playing
// maybe call play
if (isAlreadyInPlaylist)
return@launch
val res = channel.show(
R.string.msg_library_recently_added_click,
action = R.string.reset,
leading = Icons.Outlined.ClearAll,
accent = Color.DahliaYellow
)
// just return
if (res != Channel.Result.ActionPerformed)
return@launch
val index = files.indexOf(item)
remote.set(files.map { it.toMediaItem })
remote.seekTo(index.coerceAtLeast(0), C.TIME_UNSET)
remote.play(true)
}
}
override fun onRequestPlayVideo(uri: Uri, context: Context) {
viewModelScope.launch {
context.contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
val item = MediaItem(context, uri)
remote.set(item)
remote.play(true)
}
}
} | 5 | null | 9 | 97 | a92a3d74451442b3dfb8d409c1177453c5d656a3 | 6,294 | Audiofy | Apache License 2.0 |
app/src/main/java/com/example/mvvm/data/remote/api/ItemApi.kt | bachhoan88 | 166,437,272 | false | {"Gradle": 1, "Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 48, "Java": 3, "JSON": 4, "XML": 16} | package com.example.mvvm.data.remote.api
import com.example.mvvm.data.remote.response.SearchRepoResponse
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query
interface ItemApi {
@GET("search/repositories")
fun searchRepos(@Query("q") query: String, @Query("page") page: Int): Single<SearchRepoResponse>
} | 0 | Kotlin | 0 | 4 | 24b6cfbbd9e5ab877dba5f754f86e20431eb76e2 | 343 | SmallArchitecture | Apache License 2.0 |
opendc-common/src/main/kotlin/org/opendc/common/units/DataRate.kt | atlarge-research | 79,902,234 | false | {"Kotlin": 1128256, "Java": 446828, "JavaScript": 339363, "Python": 46381, "MDX": 36554, "CSS": 18038, "Dockerfile": 3592, "Shell": 280} | /*
* Copyright (c) 2024 AtLarge Research
*
* 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.
*/
@file:OptIn(InternalUse::class)
package org.opendc.common.units
import kotlinx.serialization.Serializable
import org.opendc.common.annotations.InternalUse
import org.opendc.common.units.Time.Companion.toTime
import org.opendc.common.utils.ifNeg0thenPos0
import java.time.Duration
/**
* Represents data-rate values.
* @see[Unit]
*/
@JvmInline
@Serializable(with = DataRate.Companion.DataRateSerializer::class)
public value class DataRate private constructor(
// In bits/s.
override val value: Double,
) : Unit<DataRate> {
@InternalUse
override fun new(value: Double): DataRate = DataRate(value.ifNeg0thenPos0())
public fun tobps(): Double = value
public fun toKibps(): Double = value / 1024
public fun toKbps(): Double = value / 1e3
public fun toKiBps(): Double = toKibps() / 8
public fun toKBps(): Double = toKbps() / 8
public fun toMibps(): Double = toKibps() / 1024
public fun toMbps(): Double = toKbps() / 1e3
public fun toMiBps(): Double = toMibps() / 8
public fun toMBps(): Double = toMbps() / 8
public fun toGibps(): Double = toMibps() / 1024
public fun toGbps(): Double = toMbps() / 1e3
public fun toGiBps(): Double = toGibps() / 8
public fun toGBps(): Double = toGbps() / 8
override fun toString(): String = fmtValue()
public override fun fmtValue(fmt: String): String =
when (abs()) {
in ZERO..ofBps(100) -> "${String.format(fmt, tobps())} bps"
in ofbps(100)..ofKbps(100) -> "${String.format(fmt, toKbps())} Kbps"
in ofKbps(100)..ofMbps(100) -> "${String.format(fmt, toMbps())} Mbps"
else -> "${String.format(fmt, toGbps())} Gbps"
}
public operator fun times(time: Time): DataSize = DataSize.ofKiB(toKiBps() * time.toSec())
public operator fun times(duration: Duration): DataSize = this * duration.toTime()
public companion object {
@JvmStatic public val ZERO: DataRate = DataRate(.0)
@JvmStatic
@JvmName("ofbps")
public fun ofbps(bps: Number): DataRate = DataRate(bps.toDouble())
@JvmStatic
@JvmName("ofBps")
public fun ofBps(Bps: Number): DataRate = ofbps(Bps.toDouble() * 8)
@JvmStatic
@JvmName("ofKibps")
public fun ofKibps(kibps: Number): DataRate = ofbps(kibps.toDouble() * 1024)
@JvmStatic
@JvmName("ofKbps")
public fun ofKbps(kbps: Number): DataRate = ofbps(kbps.toDouble() * 1e3)
@JvmStatic
@JvmName("ofKiBps")
public fun ofKiBps(kiBps: Number): DataRate = ofKibps(kiBps.toDouble() * 8)
@JvmStatic
@JvmName("ofKBps")
public fun ofKBps(kBps: Number): DataRate = ofKbps(kBps.toDouble() * 8)
@JvmStatic
@JvmName("ofMibps")
public fun ofMibps(mibps: Number): DataRate = ofKibps(mibps.toDouble() * 1024)
@JvmStatic
@JvmName("ofMbps")
public fun ofMbps(mbps: Number): DataRate = ofKbps(mbps.toDouble() * 1e3)
@JvmStatic
@JvmName("ofMiBps")
public fun ofMiBps(miBps: Number): DataRate = ofMibps(miBps.toDouble() * 8)
@JvmStatic
@JvmName("ofMBps")
public fun ofMBps(mBps: Number): DataRate = ofMbps(mBps.toDouble() * 8)
@JvmStatic
@JvmName("ofGibps")
public fun ofGibps(gibps: Number): DataRate = ofMibps(gibps.toDouble() * 1024)
@JvmStatic
@JvmName("ofGbps")
public fun ofGbps(gbps: Number): DataRate = ofMbps(gbps.toDouble() * 1e3)
@JvmStatic
@JvmName("ofGiBps")
public fun ofGiBps(giBps: Number): DataRate = ofGibps(giBps.toDouble() * 8)
@JvmStatic
@JvmName("ofGBps")
public fun ofGBps(gBps: Number): DataRate = ofGbps(gBps.toDouble() * 8)
/**
* Serializer for [DataRate] value class. It needs to be a compile
* time constant in order to be used as serializer automatically,
* hence `object :` instead of class instantiation.
*
* ```json
* // e.g.
* "data-rate": "1 Gbps"
* "data-rate": "10KBps"
* "data-rate": " 0.3 GBps "
* // etc.
* ```
*/
internal object DataRateSerializer : UnitSerializer<DataRate>(
ifNumber = {
LOG.warn(
"deserialization of number with no unit of measure, assuming it is in Kibps." +
"Keep in mind that you can also specify the value as '$it Kibps'",
)
ofKibps(it.toDouble())
},
serializerFun = { this.encodeString(it.toString()) },
ifMatches("$NUM_GROUP$BITS$PER$SEC") { ofbps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$BYTES$PER$SEC") { ofBps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$KIBI$BITS$PER$SEC") { ofKibps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$KILO$BITS$PER$SEC") { ofKbps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$KIBI$BYTES$PER$SEC") { ofKiBps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$KILO$BYTES$PER$SEC") { ofKBps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$MEBI$BITS$PER$SEC") { ofMibps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$MEGA$BITS$PER$SEC") { ofMbps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$MEBI$BYTES$PER$SEC") { ofMiBps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$MEGA$BYTES$PER$SEC") { ofMBps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$GIBI$BITS$PER$SEC") { ofGibps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$GIGA$BITS$PER$SEC") { ofGbps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$GIBI$BYTES$PER$SEC") { ofGiBps(json.decNumFromStr(groupValues[1])) },
ifMatches("$NUM_GROUP$GIGA$BYTES$PER$SEC") { ofGBps(json.decNumFromStr(groupValues[1])) },
)
}
}
| 33 | Kotlin | 47 | 70 | 5a365dbc068f2a8cdfa9813c39cc84bb30e15637 | 7,233 | opendc | MIT License |
lib-data/src/main/kotlin/com/jonapoul/common/di/ProvidesMoshiModule.kt | jonapoul | 375,762,483 | false | null | package com.jonapoul.common.di
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@InstallIn(SingletonComponent::class)
@Module
class ProvidesMoshiModule {
@Provides
fun providesMoshi(): Moshi = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
}
| 0 | Kotlin | 0 | 0 | 3c4bb0116dfc1cc5240fc616dc3dc1559ad27e5b | 454 | android-extensions | Apache License 2.0 |
conductor-dagger-sample/src/main/java/com/jshvarts/mosbymvp/searchrepos/SearchViewState.kt | jshvarts | 111,547,727 | false | null | package com.jshvarts.mosbymvp.searchrepos
import com.hannesdorfmann.mosby3.mvp.viewstate.ViewState
import com.jshvarts.mosbymvp.domain.GithubRepo
class SearchViewState : ViewState<SearchContract.View> {
companion object {
private const val STATE_DO_NOTHING = 0
private const val STATE_SHOW_DATA = 1
private const val STATE_SHOW_LOADING = 2
private const val STATE_SHOW_ERROR = 3
}
private var state = STATE_DO_NOTHING
private var data: List<GithubRepo>? = null
fun setData(data: List<GithubRepo>) {
state = STATE_SHOW_DATA
this.data = data
}
fun setShowLoading() {
state = STATE_SHOW_LOADING
}
fun setShowError() {
state = STATE_SHOW_ERROR
}
override fun apply(view: SearchContract.View, retained: Boolean) {
when (state) {
STATE_SHOW_DATA -> view.onSearchSuccess(data!!)
STATE_SHOW_LOADING -> view.showLoading()
STATE_SHOW_ERROR -> data = null
}
}
} | 1 | Kotlin | 6 | 28 | b982ee2683d8585c35090a1b9acb5ffaa61c0dd9 | 1,022 | MosbyMVP | Apache License 2.0 |
feature/account/src/main/java/com/flexcode/wedate/account/AccountScreen.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.account
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
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 coil.compose.AsyncImage
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.flexcode.inapppurchasescompose.SubscriptionsHelper
import com.flexcode.wedate.common.ImageShimmer
import com.flexcode.wedate.common.R
import com.flexcode.wedate.common.R.drawable as AppIcon
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.lightPurple
import com.flexcode.wedate.common.theme.purple
import com.flexcode.wedate.common.utils.Constants
import kotlinx.coroutines.launch
@Composable
fun AccountScreen(
openScreen: () -> Unit,
navigateToSettings: () -> Unit,
navigateToProfileDetails: () -> Unit,
modifier: Modifier = Modifier,
viewModel: AccountScreenViewModel = hiltViewModel()
) {
val state by viewModel.state
val billingPurchaseHelper = SubscriptionsHelper(
LocalContext.current,
Constants.LOVE_CALCULATOR
)
billingPurchaseHelper.setUpBillingPurchases()
val purchaseDone by billingPurchaseHelper.purchaseDone.collectAsState(false)
val gradient = Brush.verticalGradient(
listOf(lightPurple, Color.White),
startY = 500.0f,
endY = 1300.0f
)
val scrollState = rememberScrollState()
Box(
modifier = modifier
.fillMaxSize()
.background(brush = gradient),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = CenterHorizontally,
modifier = modifier
.fillMaxSize()
.verticalScroll(scrollState)
) {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
modifier = modifier.offset(x = (16).dp, y = (-10).dp)
) {
AppTitleText(fontWeight = FontWeight.Normal, fontSize = 20.sp)
}
SwipeRightLeftIcon(
onClick = { navigateToSettings() },
icon = Icons.Default.Settings,
contentDesc = "Settings",
height = 30.dp,
width = 30.dp,
paddingValues = PaddingValues(0.dp, end = 10.dp)
)
}
ProfileImage(state, navigateToProfileDetails)
ResultText(
text = "${state.userDetails?.firstName},${state.userDetails?.years}",
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colors.background,
fontSize = 20.sp,
modifier = modifier.offset(y = (-8).dp)
)
Row(
modifier = modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
UserInfoItemComposable(
text = state.userDetails?.datingStatus.toString(),
icon = AppIcon.ic_favourite_border
)
UserInfoItemComposable(
text = state.userDetails?.gender.toString(),
icon = AppIcon.ic_male
)
}
Row(
modifier = modifier
.fillMaxWidth()
.padding(top = 30.dp),
horizontalArrangement = Arrangement.SpaceAround
) {
SubscriptionsCard(text = AppText.unlock_distance, icon = AppIcon.ic_location)
SubscriptionsCard(text = AppText.unlock_admirer, icon = AppIcon.ic_favourite_border)
SubscriptionsCard(text = AppText.subscriptions, icon = AppIcon.logo)
}
Column(
modifier = modifier
.weight(1f)
.padding(bottom = 60.dp),
verticalArrangement = Arrangement.Bottom
) {
BannerAdView()
BasicButton(
text = R.string.calculator,
modifier = modifier
.basicButton()
.height(50.dp)
.clip(RoundedCornerShape(10.dp))
) {
if (purchaseDone) {
billingPurchaseHelper.initializePurchase()
} else {
// save purchase if done
openScreen()
}
}
}
}
}
}
@Composable
fun SubscriptionsCard(
text: Int,
icon: Int
) {
Card(
shape = RoundedCornerShape(10.dp),
modifier = Modifier
.width(118.dp)
.height(135.dp)
) {
Column {
Image(
modifier = Modifier
.padding(10.dp)
.align(CenterHorizontally)
.size(30.dp),
painter = painterResource(id = icon),
contentDescription = stringResource(id = text)
)
Spacer(modifier = Modifier.weight(1f))
BasicText(
text = text,
fontSize = 14.sp,
textAlign = TextAlign.Center
)
}
}
}
@Composable
fun UserInfoItemComposable(
modifier: Modifier = Modifier,
text: String,
icon: Int
) {
Column(
modifier = modifier.size(150.dp)
) {
Card(
shape = CircleShape,
elevation = 10.dp,
modifier = modifier.align(CenterHorizontally)
) {
Image(
modifier = modifier.size(40.dp),
painter = painterResource(id = icon),
contentDescription = text
)
}
ResultText(text = text, textAlign = TextAlign.Center)
}
}
@Composable
fun ProfileImage(
state: AccountState,
navigateToProfileDetails: () -> Unit
) {
Box(
modifier = Modifier.size(115.dp)
) {
Card(
modifier = Modifier
.clip(CircleShape)
.align(Alignment.BottomEnd)
.clickable {
navigateToProfileDetails()
},
backgroundColor = purple
) {
Image(
modifier = Modifier
.size(40.dp)
.padding(8.dp),
imageVector = Icons.Default.Edit,
contentDescription = "edit profile"
)
}
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(state.userDetails?.profileImage?.profileImage1)
.crossfade(true)
.placeholder(ImageShimmer().shimmerDrawable)
.build(),
contentDescription = "profile image",
contentScale = ContentScale.Crop,
modifier = Modifier
.clickable {
navigateToProfileDetails()
}
.size(100.dp)
.clip(CircleShape)
)
}
}
| 13 | null | 1 | 9 | 20a9b38cb4ae45572a248f819eca775e2d2f2678 | 9,437 | Mingle | Apache License 2.0 |
app/src/main/java/com/globalfsm/features/photoReg/present/DsStatusListner.kt | DebashisINT | 614,841,798 | false | null | package com.globalfsm.features.photoReg.present
import com.globalfsm.app.domain.ProspectEntity
import com.globalfsm.features.photoReg.model.UserListResponseModel
interface DsStatusListner {
fun getDSInfoOnLick(obj: ProspectEntity)
} | 0 | Kotlin | 0 | 0 | f0435b0dd4b1ce20137b6a892ed58c2b7d7142f7 | 238 | GLOBAL | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/synthetics/CfnCanaryPropsDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.synthetics
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.synthetics.CfnCanaryProps
@Generated
public fun buildCfnCanaryProps(initializer: @AwsCdkDsl CfnCanaryProps.Builder.() -> Unit):
CfnCanaryProps = CfnCanaryProps.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | 451a1e42282de74a9a119a5716bd95b913662e7c | 394 | aws-cdk-kt | Apache License 2.0 |
vis-svg-portable/src/commonMain/kotlin/jetbrains/datalore/vis/svg/XmlNamespace.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.vis.svg
object XmlNamespace {
const val SVG_NAMESPACE_URI = "http://www.w3.org/2000/svg"
const val XLINK_NAMESPACE_URI = "http://www.w3.org/1999/xlink"
const val XLINK_PREFIX = "xlink"
} | 98 | Kotlin | 46 | 886 | 30f147b2ab81c2b4f6bb29ba7a5e41ad3245cdfd | 372 | lets-plot | MIT License |
vendor/vendor-android/src/main/kotlin/com/malinskiy/marathon/android/executor/listeners/video/ScreenRecorder.kt | fkorotkov | 215,035,477 | true | {"Kotlin": 394025, "JavaScript": 40471, "CSS": 29266, "HTML": 2960, "Shell": 1043} | package com.malinskiy.marathon.android.executor.listeners.video
import com.android.ddmlib.CollectingOutputReceiver
import com.android.ddmlib.IDevice
import com.android.ddmlib.ScreenRecorderOptions
import com.malinskiy.marathon.android.safeStartScreenRecorder
import com.malinskiy.marathon.log.MarathonLogging
import java.util.concurrent.TimeUnit.SECONDS
import kotlin.system.measureTimeMillis
internal class ScreenRecorder(
private val device: IDevice,
private val receiver: CollectingOutputReceiver,
private val remoteFilePath: String
) : Runnable {
override fun run() {
try {
startRecordingTestVideo()
} catch (e: Exception) {
logger.error("Something went wrong while screen recording", e)
}
}
private fun startRecordingTestVideo() {
val millis = measureTimeMillis {
device.safeStartScreenRecorder(remoteFilePath, options, receiver)
}
logger.trace { "Recording finished in ${millis}ms $remoteFilePath" }
}
companion object {
private val logger = MarathonLogging.logger("ScreenRecorder")
private const val DURATION = 180
private const val BITRATE_MB_PER_SECOND = 1
private val options = ScreenRecorderOptions.Builder()
.setTimeLimit(DURATION.toLong(), SECONDS)
.setBitRate(BITRATE_MB_PER_SECOND)
.build()
}
}
| 0 | Kotlin | 0 | 0 | 569c6df350f5c1734f2476347e27aec641ab8c36 | 1,403 | marathon | Apache License 2.0 |
data/src/main/kotlin/ru/bykov/footballteams/repository/InMemoryCachedFootballTeamRepository.kt | grine4ka | 419,372,892 | false | null | package ru.bykov.footballteams.repository
import android.util.SparseArray
import io.reactivex.Single
import ru.bykov.footballteams.extensions.switchToSingleIfEmpty
import ru.bykov.footballteams.extensions.toMaybe
import ru.bykov.footballteams.models.FootballTeam
import ru.bykov.footballteams.models.FootballTeamDetails
// TODO move all this code to UseCase
class InMemoryCachedFootballTeamRepository(
private val remote: FootballTeamRepository,
private val teams: MutableList<FootballTeam> = mutableListOf(),
private val teamDetails: SparseArray<FootballTeamDetails> = SparseArray(5)
) : FootballTeamRepository {
override fun teams(forceUpdate: Boolean): Single<List<FootballTeam>> {
if (forceUpdate) {
return cacheRemoteTeams()
}
return teams.toMaybe()
.switchToSingleIfEmpty {
cacheRemoteTeams()
}
}
override fun details(teamId: Int): Single<FootballTeamDetails> {
return teamDetails[teamId].toMaybe()
.switchToSingleIfEmpty {
remote.details(teamId).doOnSuccess { details ->
teamDetails.append(details.id, details)
}
}
}
private fun cacheRemoteTeams() = remote.teams().doOnSuccess {
teams.clear()
teams.addAll(it)
}
} | 5 | Kotlin | 0 | 0 | ea1894aecc34f875562f1c6dc5a51580b859c8c2 | 1,337 | footea | MIT License |
articapi-client/src/commonMain/kotlin/com/peteraraujo/articapi/services/mobile/tour/TourFieldParam.kt | peteraraujo | 834,670,209 | false | {"Kotlin": 305250} | package com.peteraraujo.articapi.services.mobile.tour
import com.peteraraujo.articapi.services.commons.Param
/**
* Param field options.
*/
enum class TourFieldParam(override val value: String) : Param {
/**
* Unique identifier of this resource. Taken from the source system.
*/
Id("id"),
/**
* The name of this resource.
*/
Title("title"),
/**
* REST API resource type or endpoint.
*/
ApiModel("api_model"),
/**
* REST API link for this resource.
*/
ApiLink("api_link"),
/** Search score. */
Score("_score"),
/**
* The main image for the tour.
*/
Image("image"),
/**
* Explanation of what the tour is.
*/
Description("description"),
/**
* Text introducing the tour.
*/
Intro("intro"),
/**
* Number representing this tour's sort order.
*/
Weight("weight"),
/**
* Link to the audio file of the introduction.
*/
IntroLink("intro_link"),
/**
* Transcript of the introduction audio to the tour.
*/
IntroTranscript("intro_transcript"),
/**
* Names of the artworks featured in this tour's tour stops.
*/
ArtworkTitles("artwork_titles"),
/**
* Names of the artists of the artworks featured in this tour's tour stops.
*/
ArtistTitles("artist_titles"),
/** Optional tour stop list. */
TourStops(value = "tour_stops"),
/**
* Internal field to power the /autocomplete endpoint. Do not use directly.
*/
SuggestAutocompleteBoosted("suggest_autocomplete_boosted"),
/**
* Internal field to power the /autosuggest endpoint. Do not use directly.
*/
SuggestAutocompleteAll("suggest_autocomplete_all"),
/**
* Date and time the resource was updated in the source system.
*/
SourceUpdatedAt("source_updated_at"),
/**
* Date and time the record was updated in the aggregator database.
*/
UpdatedAt("updated_at"),
/**
* Date and time the record was updated in the aggregator search index.
*/
Timestamp("timestamp");
}
| 0 | Kotlin | 0 | 1 | 1266af91767e083b9abdc2309b7f0eab9a6c919c | 2,139 | articapi-client | Apache License 2.0 |
src/main/kotlin/io/mverse/kslack/api/methods/request/conversations/ConversationsKickRequest.kt | mverse | 161,946,116 | true | {"Kotlin": 403852} | package io.mverse.kslack.api.methods.request.conversations
import io.mverse.kslack.api.methods.SlackApiRequest
data class ConversationsKickRequest(
/**
* Authentication token. Requires scope: `conversations:write`
*/
override var token: String? = null,
/**
* ID of conversation to remove user from.
*/
val channel: String? = null,
/**
* User ID to be removed.
*/
val user: String? = null): SlackApiRequest
| 0 | Kotlin | 0 | 0 | 9ebf1dc13f6a3d89a03af11a83074a4d636cb071 | 441 | jslack | MIT License |
exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Constraints.kt | JetBrains | 11,765,017 | false | null | package org.jetbrains.exposed.sql
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.vendors.*
import java.sql.DatabaseMetaData
/**
* Common interface for database objects that can be created, modified and dropped.
*/
interface DdlAware {
/** Returns the list of DDL statements that create this object. */
fun createStatement(): List<String>
/** Returns the list of DDL statements that modify this object. */
fun modifyStatement(): List<String>
/** Returns the list of DDL statements that drops this object. */
fun dropStatement(): List<String>
}
/**
* Represents reference constraint actions.
* Read [Referential actions](https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-referential-actions) from MySQL docs
* or on [StackOverflow](https://stackoverflow.com/a/6720458/813981)
*/
enum class ReferenceOption {
CASCADE,
SET_NULL,
RESTRICT,
NO_ACTION;
override fun toString(): String = name.replace("_", " ")
companion object {
/** Returns the corresponding [ReferenceOption] for the specified [refOption] from JDBC. */
fun resolveRefOptionFromJdbc(refOption: Int): ReferenceOption = when (refOption) {
DatabaseMetaData.importedKeyCascade -> CASCADE
DatabaseMetaData.importedKeySetNull -> SET_NULL
DatabaseMetaData.importedKeyRestrict -> RESTRICT
DatabaseMetaData.importedKeyNoAction -> NO_ACTION
else -> currentDialect.defaultReferenceOption
}
}
}
/**
* Represents a foreign key constraint.
*/
data class ForeignKeyConstraint(
val target: Column<*>,
val from: Column<*>,
private val onUpdate: ReferenceOption?,
private val onDelete: ReferenceOption?,
private val name: String?
) : DdlAware {
private val tx: Transaction
get() = TransactionManager.current()
/** Name of the child table. */
val targetTable: String
get() = tx.identity(target.table)
/** Name of the foreign key column. */
val targetColumn: String
get() = tx.identity(target)
/** Name of the parent table. */
val fromTable: String
get() = tx.identity(from.table)
/** Name of the key column from the parent table. */
val fromColumn
get() = tx.identity(from)
/** Reference option when performing update operations. */
val updateRule: ReferenceOption?
get() = onUpdate ?: currentDialectIfAvailable?.defaultReferenceOption
/** Reference option when performing delete operations. */
val deleteRule: ReferenceOption?
get() = onDelete ?: currentDialectIfAvailable?.defaultReferenceOption
/** Name of this constraint. */
val fkName: String
get() = tx.db.identifierManager.cutIfNecessaryAndQuote(
name ?: "fk_${from.table.tableNameWithoutScheme}_${from.name}_${target.name}"
).inProperCase()
internal val foreignKeyPart: String get() = buildString {
if (fkName.isNotBlank()) {
append("CONSTRAINT $fkName ")
}
append("FOREIGN KEY ($fromColumn) REFERENCES $targetTable($targetColumn)")
if (deleteRule != ReferenceOption.NO_ACTION) {
append(" ON DELETE $deleteRule")
}
if (updateRule != ReferenceOption.NO_ACTION) {
if (currentDialect is OracleDialect) {
exposedLogger.warn("Oracle doesn't support FOREIGN KEY with ON UPDATE clause. Please check your $fromTable table.")
} else {
append(" ON UPDATE $updateRule")
}
}
}
override fun createStatement(): List<String> = listOf("ALTER TABLE $fromTable ADD $foreignKeyPart")
override fun modifyStatement(): List<String> = dropStatement() + createStatement()
override fun dropStatement(): List<String> {
val constraintType = when (currentDialect) {
is MysqlDialect -> "FOREIGN KEY"
else -> "CONSTRAINT"
}
return listOf("ALTER TABLE $fromTable DROP $constraintType $fkName")
}
}
/**
* Represents a check constraint.
*/
data class CheckConstraint(
/** Name of the table where the constraint is defined. */
val tableName: String,
/** Name of the check constraint. */
val checkName: String,
/** Boolean expression used for the check constraint. */
val checkOp: String
) : DdlAware {
internal val checkPart = "CONSTRAINT $checkName CHECK ($checkOp)"
override fun createStatement(): List<String> {
return if (currentDialect is MysqlDialect) {
exposedLogger.warn("Creation of CHECK constraints is not currently supported by MySQL")
listOf()
} else {
listOf("ALTER TABLE $tableName ADD $checkPart")
}
}
override fun modifyStatement(): List<String> = dropStatement() + createStatement()
override fun dropStatement(): List<String> {
return if (currentDialect is MysqlDialect) {
exposedLogger.warn("Deletion of CHECK constraints is not currently supported by MySQL")
listOf()
} else {
listOf("ALTER TABLE $tableName DROP CONSTRAINT $checkName")
}
}
companion object {
internal fun from(table: Table, name: String, op: Op<Boolean>): CheckConstraint {
require(name.isNotBlank()) { "Check constraint name cannot be blank" }
val tr = TransactionManager.current()
val identifierManager = tr.db.identifierManager
val tableName = tr.identity(table)
val checkOpSQL = op.toString().replace("$tableName.", "")
return CheckConstraint(tableName, identifierManager.cutIfNecessaryAndQuote(name), checkOpSQL)
}
}
}
/**
* Represents an index.
*/
data class Index(
/** Columns that are part of the index. */
val columns: List<Column<*>>,
/** Whether the index in unique or not. */
val unique: Boolean,
/** Optional custom name for the index. */
val customName: String? = null
) : DdlAware {
/** Table where the index is defined. */
val table: Table
/** Name of the index. */
val indexName: String
get() = customName ?: buildString {
append(table.nameInDatabaseCase())
append('_')
append(columns.joinToString("_") { it.name }.inProperCase())
if (unique) {
append("_unique".inProperCase())
}
}
init {
require(columns.isNotEmpty()) { "At least one column is required to create an index" }
val table = columns.distinctBy { it.table }.singleOrNull()?.table
requireNotNull(table) { "Columns from different tables can't persist in one index" }
this.table = table
}
override fun createStatement(): List<String> = listOf(currentDialect.createIndex(this))
override fun modifyStatement(): List<String> = dropStatement() + createStatement()
override fun dropStatement(): List<String> = listOf(currentDialect.dropIndex(table.nameInDatabaseCase(), indexName))
/** Returns `true` if the [other] index has the same columns and uniqueness as this index, but a different name, `false` otherwise */
fun onlyNameDiffer(other: Index): Boolean = indexName != other.indexName && columns == other.columns && unique == other.unique
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Index) return false
if (indexName != other.indexName) return false
if (columns != other.columns) return false
if (unique != other.unique) return false
return true
}
override fun hashCode(): Int {
var result = indexName.hashCode()
result = 31 * result + columns.hashCode()
result = 31 * result + unique.hashCode()
return result
}
override fun toString(): String =
"${if (unique) "Unique " else ""}Index '$indexName' for '${table.nameInDatabaseCase()}' on columns ${columns.joinToString()}"
}
| 286 | Kotlin | 467 | 5,683 | 6b51837e222eeebeae544a679ab18bfd9d415e5e | 8,079 | Exposed | Apache License 2.0 |
compat/runner/src/main/kotlin/NumberFunctionsTestPackProducer.kt | wjsrobertson | 424,259,165 | false | {"Gradle": 13, "INI": 1, "Text": 7, "Ignore List": 1, "YAML": 67, "Markdown": 6, "Kotlin": 146, "XML": 1, "JSON": 5461, "Gherkin": 37, "Makefile": 1, "reStructuredText": 7, "Python": 1, "SVG": 1, "Shell": 1, "Java": 7, "Gerber Image": 7} | package org.kevem.compat.runner
import org.kevem.compat.generated.NumberFunctions
import org.web3j.crypto.Credentials
import org.web3j.protocol.Web3j
import org.web3j.protocol.core.RemoteCall
import org.web3j.protocol.core.methods.response.TransactionReceipt
import org.web3j.protocol.http.HttpService
import org.web3j.tx.ClientTransactionManager
import org.web3j.utils.Numeric
import java.math.BigInteger
fun main(args: Array<String>) {
val (web3j, contract) = init()
val single = listOf(
"0x0000000000000000000000000000000000000000000000000000000000000000",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"0x0000000000000000000000000000000000000000000000000000000000000002",
"0x0000000000000000000000000000000000000000000000000000000000000009",
"0xffffffffffffffffffffffffffffff0000000000000000000000000000000000",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
)
val pairs = single.flatMap { i1 ->
single.map { i2 ->
listOf(i1, i2)
}
}
val triples = pairs.flatMap {
val (i1, i2) = it
single.map { i3 -> listOf(i1, i2, i3) }
}
val oneArgMethods = listOf("not", "iszero")
val twoArgMethods = listOf(
"add",
"and",
"byte",
"div",
"eq",
"exp",
"gt",
"lt",
"mod",
"mul",
"or",
"sdiv",
"sgt",
"signextend",
"slt",
"smod",
"sub",
"xor",
"sar"
)
val threeArgMethods = listOf("mulmod", "addmod")
val out = (oneArgMethods + twoArgMethods + threeArgMethods).flatMap { function ->
val argTypes = when (function) {
in oneArgMethods -> arrayOf(ByteArray::class.java)
in twoArgMethods -> arrayOf(ByteArray::class.java, ByteArray::class.java)
else -> arrayOf(ByteArray::class.java, ByteArray::class.java, ByteArray::class.java)
}
val argsList: List<List<String>> = when (function) {
in oneArgMethods -> single.map { listOf(it) }
in twoArgMethods -> pairs
else -> triples
}
val method = contract.javaClass.getMethod(contractFunctionName(function), *argTypes)
argsList.map { args ->
val argsX = args.map { Numeric.hexStringToByteArray(it) }.toTypedArray()
val txHash = (method.invoke(contract, *argsX) as RemoteCall<TransactionReceipt>).send().transactionHash
val receipt = web3j.ethGetTransactionReceipt(txHash).send().transactionReceipt.get()
val result = receipt.logs[0].data
(listOf(function) + listOf(result) + args + listOf("", "", "", "")).take(6).joinToString("\t")
}
}.joinToString("\n")
println(out)
}
private fun init(): Pair<Web3j, NumberFunctions> {
val web3j = Web3j.build(HttpService("http://127.0.0.1:8545"))
val account = Credentials.create("<KEY>")
val txManager = ClientTransactionManager(web3j, "0x4E7D932c0f12Cfe14295B86824B37bB1062bc29E")
val gasProvider = ConstantGasProvider(BigInteger.valueOf(1000000), BigInteger.valueOf(400))
val contract = NumberFunctions.deploy(web3j, txManager, gasProvider).send()
return Pair(web3j, contract)
}
private fun contractFunctionName(name: String) = "call" + name[0].toUpperCase() + name.drop(1)
| 11 | Kotlin | 1 | 0 | a5652a063b5d168394af94b54fe5559dab712736 | 3,488 | kevem | Apache License 2.0 |
langsmith-java-core/src/main/kotlin/com/langsmith/api/models/DatasetRunCreateParams.kt | langchain-ai | 774,515,765 | false | {"Kotlin": 2288977, "Shell": 1314, "Dockerfile": 305} | // File generated from our OpenAPI spec by Stainless.
package com.langsmith.api.models
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.langsmith.api.core.ExcludeMissing
import com.langsmith.api.core.JsonValue
import com.langsmith.api.core.NoAutoDetect
import com.langsmith.api.core.toUnmodifiable
import com.langsmith.api.models.*
import java.util.Objects
import java.util.Optional
class DatasetRunCreateParams
constructor(
private val datasetId: String,
private val sessionIds: List<String>,
private val filters: Filters?,
private val limit: Long?,
private val offset: Long?,
private val additionalQueryParams: Map<String, List<String>>,
private val additionalHeaders: Map<String, List<String>>,
private val additionalBodyProperties: Map<String, JsonValue>,
) {
fun datasetId(): String = datasetId
fun sessionIds(): List<String> = sessionIds
fun filters(): Optional<Filters> = Optional.ofNullable(filters)
fun limit(): Optional<Long> = Optional.ofNullable(limit)
fun offset(): Optional<Long> = Optional.ofNullable(offset)
@JvmSynthetic
internal fun getBody(): DatasetRunCreateBody {
return DatasetRunCreateBody(
sessionIds,
filters,
limit,
offset,
additionalBodyProperties,
)
}
@JvmSynthetic internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams
@JvmSynthetic internal fun getHeaders(): Map<String, List<String>> = additionalHeaders
fun getPathParam(index: Int): String {
return when (index) {
0 -> datasetId
else -> ""
}
}
@JsonDeserialize(builder = DatasetRunCreateBody.Builder::class)
@NoAutoDetect
class DatasetRunCreateBody
internal constructor(
private val sessionIds: List<String>?,
private val filters: Filters?,
private val limit: Long?,
private val offset: Long?,
private val additionalProperties: Map<String, JsonValue>,
) {
private var hashCode: Int = 0
@JsonProperty("session_ids") fun sessionIds(): List<String>? = sessionIds
@JsonProperty("filters") fun filters(): Filters? = filters
@JsonProperty("limit") fun limit(): Long? = limit
@JsonProperty("offset") fun offset(): Long? = offset
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is DatasetRunCreateBody &&
this.sessionIds == other.sessionIds &&
this.filters == other.filters &&
this.limit == other.limit &&
this.offset == other.offset &&
this.additionalProperties == other.additionalProperties
}
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode =
Objects.hash(
sessionIds,
filters,
limit,
offset,
additionalProperties,
)
}
return hashCode
}
override fun toString() =
"DatasetRunCreateBody{sessionIds=$sessionIds, filters=$filters, limit=$limit, offset=$offset, additionalProperties=$additionalProperties}"
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var sessionIds: List<String>? = null
private var filters: Filters? = null
private var limit: Long? = null
private var offset: Long? = null
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(datasetRunCreateBody: DatasetRunCreateBody) = apply {
this.sessionIds = datasetRunCreateBody.sessionIds
this.filters = datasetRunCreateBody.filters
this.limit = datasetRunCreateBody.limit
this.offset = datasetRunCreateBody.offset
additionalProperties(datasetRunCreateBody.additionalProperties)
}
@JsonProperty("session_ids")
fun sessionIds(sessionIds: List<String>) = apply { this.sessionIds = sessionIds }
@JsonProperty("filters")
fun filters(filters: Filters) = apply { this.filters = filters }
@JsonProperty("limit") fun limit(limit: Long) = apply { this.limit = limit }
@JsonProperty("offset") fun offset(offset: Long) = apply { this.offset = offset }
fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.clear()
this.additionalProperties.putAll(additionalProperties)
}
@JsonAnySetter
fun putAdditionalProperty(key: String, value: JsonValue) = apply {
this.additionalProperties.put(key, value)
}
fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.putAll(additionalProperties)
}
fun build(): DatasetRunCreateBody =
DatasetRunCreateBody(
checkNotNull(sessionIds) { "`sessionIds` is required but was not set" }
.toUnmodifiable(),
filters,
limit,
offset,
additionalProperties.toUnmodifiable(),
)
}
}
fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams
fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders
fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is DatasetRunCreateParams &&
this.datasetId == other.datasetId &&
this.sessionIds == other.sessionIds &&
this.filters == other.filters &&
this.limit == other.limit &&
this.offset == other.offset &&
this.additionalQueryParams == other.additionalQueryParams &&
this.additionalHeaders == other.additionalHeaders &&
this.additionalBodyProperties == other.additionalBodyProperties
}
override fun hashCode(): Int {
return Objects.hash(
datasetId,
sessionIds,
filters,
limit,
offset,
additionalQueryParams,
additionalHeaders,
additionalBodyProperties,
)
}
override fun toString() =
"DatasetRunCreateParams{datasetId=$datasetId, sessionIds=$sessionIds, filters=$filters, limit=$limit, offset=$offset, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}"
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
@NoAutoDetect
class Builder {
private var datasetId: String? = null
private var sessionIds: MutableList<String> = mutableListOf()
private var filters: Filters? = null
private var limit: Long? = null
private var offset: Long? = null
private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(datasetRunCreateParams: DatasetRunCreateParams) = apply {
this.datasetId = datasetRunCreateParams.datasetId
this.sessionIds(datasetRunCreateParams.sessionIds)
this.filters = datasetRunCreateParams.filters
this.limit = datasetRunCreateParams.limit
this.offset = datasetRunCreateParams.offset
additionalQueryParams(datasetRunCreateParams.additionalQueryParams)
additionalHeaders(datasetRunCreateParams.additionalHeaders)
additionalBodyProperties(datasetRunCreateParams.additionalBodyProperties)
}
fun datasetId(datasetId: String) = apply { this.datasetId = datasetId }
fun sessionIds(sessionIds: List<String>) = apply {
this.sessionIds.clear()
this.sessionIds.addAll(sessionIds)
}
fun addSessionId(sessionId: String) = apply { this.sessionIds.add(sessionId) }
fun filters(filters: Filters) = apply { this.filters = filters }
fun limit(limit: Long) = apply { this.limit = limit }
fun offset(offset: Long) = apply { this.offset = offset }
fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply {
this.additionalQueryParams.clear()
putAllQueryParams(additionalQueryParams)
}
fun putQueryParam(name: String, value: String) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value)
}
fun putQueryParams(name: String, values: Iterable<String>) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply {
additionalQueryParams.forEach(this::putQueryParams)
}
fun removeQueryParam(name: String) = apply {
this.additionalQueryParams.put(name, mutableListOf())
}
fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
this.additionalHeaders.clear()
putAllHeaders(additionalHeaders)
}
fun putHeader(name: String, value: String) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value)
}
fun putHeaders(name: String, values: Iterable<String>) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
additionalHeaders.forEach(this::putHeaders)
}
fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) }
fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply {
this.additionalBodyProperties.clear()
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply {
this.additionalBodyProperties.put(key, value)
}
fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) =
apply {
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun build(): DatasetRunCreateParams =
DatasetRunCreateParams(
checkNotNull(datasetId) { "`datasetId` is required but was not set" },
checkNotNull(sessionIds) { "`sessionIds` is required but was not set" }
.toUnmodifiable(),
filters,
limit,
offset,
additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalBodyProperties.toUnmodifiable(),
)
}
@JsonDeserialize(builder = Filters.Builder::class)
@NoAutoDetect
class Filters
private constructor(
private val additionalProperties: Map<String, JsonValue>,
) {
private var hashCode: Int = 0
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is Filters && this.additionalProperties == other.additionalProperties
}
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode = Objects.hash(additionalProperties)
}
return hashCode
}
override fun toString() = "Filters{additionalProperties=$additionalProperties}"
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(filters: Filters) = apply {
additionalProperties(filters.additionalProperties)
}
fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.clear()
this.additionalProperties.putAll(additionalProperties)
}
@JsonAnySetter
fun putAdditionalProperty(key: String, value: JsonValue) = apply {
this.additionalProperties.put(key, value)
}
fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.putAll(additionalProperties)
}
fun build(): Filters = Filters(additionalProperties.toUnmodifiable())
}
}
}
| 1 | Kotlin | 0 | 2 | 922058acd6e168f6e1db8d9e67a24850ab7e93a0 | 14,154 | langsmith-java | Apache License 2.0 |
src/main/kotlin/vkk/vk10/structs/DescriptorPoolCreateInfo.kt | kotlin-graphics | 132,931,904 | false | null | package vkk.vk10.structs
import kool.Adr
import kool.Ptr
import org.lwjgl.system.MemoryStack
import org.lwjgl.system.MemoryUtil.NULL
import org.lwjgl.system.MemoryUtil.memPutAddress
import org.lwjgl.vulkan.VkDescriptorPoolCreateInfo.*
import vkk.VkDescriptorPoolCreateFlags
import vkk.VkStack
import vkk.VkStructureType
/**
* Structure specifying parameters of a newly created descriptor pool.
*
* <h5>Description</h5>
*
* <p>If multiple {@link VkDescriptorPoolSize} structures appear in the {@code pPoolSizes} array then the pool will be created with enough storage for the total number of descriptors of each type.</p>
*
* <p>Fragmentation of a descriptor pool is possible and <b>may</b> lead to descriptor set allocation failures. A failure due to fragmentation is defined as failing a descriptor set allocation despite the sum of all outstanding descriptor set allocations from the pool plus the requested allocation requiring no more than the total number of descriptors requested at pool creation. Implementations provide certain guarantees of when fragmentation <b>must</b> not cause allocation failure, as described below.</p>
*
* <p>If a descriptor pool has not had any descriptor sets freed since it was created or most recently reset then fragmentation <b>must</b> not cause an allocation failure (note that this is always the case for a pool created without the {@link VK10#VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT} bit set). Additionally, if all sets allocated from the pool since it was created or most recently reset use the same number of descriptors (of each type) and the requested allocation also uses that same number of descriptors (of each type), then fragmentation <b>must</b> not cause an allocation failure.</p>
*
* <p>If an allocation failure occurs due to fragmentation, an application <b>can</b> create an additional descriptor pool to perform further descriptor set allocations.</p>
*
* <p>If {@code flags} has the {@link EXTDescriptorIndexing#VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT} bit set, descriptor pool creation <b>may</b> fail with the error {@link EXTDescriptorIndexing#VK_ERROR_FRAGMENTATION_EXT ERROR_FRAGMENTATION_EXT} if the total number of descriptors across all pools (including this one) created with this bit set exceeds {@code maxUpdateAfterBindDescriptorsInAllPools}, or if fragmentation of the underlying hardware resources occurs.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code maxSets} <b>must</b> be greater than 0</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code sType} <b>must</b> be {@link VK10#VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}</li>
* <li>{@code pNext} <b>must</b> be {@code NULL} or a pointer to a valid instance of {@link VkDescriptorPoolInlineUniformBlockCreateInfoEXT}</li>
* <li>{@code flags} <b>must</b> be a valid combination of {@code VkDescriptorPoolCreateFlagBits} values</li>
* <li>{@code pPoolSizes} <b>must</b> be a valid pointer to an array of {@code poolSizeCount} valid {@link VkDescriptorPoolSize} structures</li>
* <li>{@code poolSizeCount} <b>must</b> be greater than 0</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkDescriptorPoolSize}, {@link VK10#vkCreateDescriptorPool CreateDescriptorPool}</p>
*
* <h3>Member documentation</h3>
*
* <ul>
* <li>{@code sType} – the type of this structure.</li>
* <li>{@code pNext} – {@code NULL} or a pointer to an extension-specific structure.</li>
* <li>{@code flags} – a bitmask of {@code VkDescriptorPoolCreateFlagBits} specifying certain supported operations on the pool.</li>
* <li>{@code maxSets} – the maximum number of descriptor sets that <b>can</b> be allocated from the pool.</li>
* <li>{@code poolSizeCount} – the number of elements in {@code pPoolSizes}.</li>
* <li>{@code pPoolSizes} – a pointer to an array of {@link VkDescriptorPoolSize} structures, each containing a descriptor type and number of descriptors of that type to be allocated in the pool.</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkDescriptorPoolCreateInfo {
* VkStructureType sType;
* void const * pNext;
* VkDescriptorPoolCreateFlags flags;
* uint32_t maxSets;
* uint32_t poolSizeCount;
* {@link VkDescriptorPoolSize VkDescriptorPoolSize} const * pPoolSizes;
* }</code></pre>
*/
class DescriptorPoolCreateInfo(
var flags: VkDescriptorPoolCreateFlags,
var maxSets: Int,
var poolSizes: Array<DescriptorPoolSize>,
var next: Ptr = NULL
) {
val type get() = VkStructureType.DESCRIPTOR_POOL_CREATE_INFO
infix fun write(stack: MemoryStack): Adr {
val adr = stack.ncalloc(ALIGNOF, 1, SIZEOF)
nsType(adr, type.i)
npNext(adr, next)
nflags(adr, flags)
nmaxSets(adr, maxSets)
npoolSizeCount(adr, poolSizes.size)
memPutAddress(adr + PPOOLSIZES, poolSizes write stack)
return adr
}
} | 2 | Kotlin | 7 | 96 | 3ae299c509d6c1fa75acd957083a827859cd7097 | 5,111 | vkk | Apache License 2.0 |
app/src/main/java/com/project/cocktailconnoisseur/Navigation.kt | Johnny-OShea | 800,336,435 | false | {"Kotlin": 68857} | package com.project.cocktailconnoisseur
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.project.cocktailconnoisseur.screens.CategoriesScreen
import com.project.cocktailconnoisseur.screens.CocktailsScreen
import com.project.cocktailconnoisseur.screens.HomeScreen
import com.project.cocktailconnoisseur.screens.InformationScreen
import com.project.cocktailconnoisseur.screens.Screen
@Composable
fun CocktailConnoisseurApp( navController: NavHostController,
categoryViewModel: CategoryViewModel = CategoryViewModel(),
cocktailViewModel: CocktailsViewModel = CocktailsViewModel() ) {
// Use navHost to start in the cocktailsScreen for now
NavHost( navController = navController, startDestination = Screen.HomeScreen.route ) {
composable( route = Screen.HomeScreen.route ) {
HomeScreen( navController = navController, cocktailsViewModel = cocktailViewModel )
}
// Create a composable for the cocktails screen. Right now this is just a 2 wide lazy column of all the drinks
composable( route = Screen.CocktailsScreen.route ) {
// Send over the viewState and get the primary screen
CocktailsScreen( viewModel = cocktailViewModel, navController = navController )
}
// Create a composable for the categories. This screen holds a ScrollableTabRow where each tab will contains content
// of all the drinks within that tab
composable( route = Screen.CategoriesScreen.route ) {
// Send over the categories to get the primary screen. Additionally if a category is selected switch to the DrinksByCategory Route
CategoriesScreen( categoryViewModel = categoryViewModel, cocktailsViewModel = cocktailViewModel, navController = navController )
}
composable(
route = Screen.InformationScreen.route + "/{cocktailId}",
arguments = listOf(
navArgument(
name = "cocktailId"
) {
type = NavType.StringType;
defaultValue = "17225";
nullable = false
}
)
) {
entry ->
val cocktailId = entry.arguments?.getString( "cocktailId" )
cocktailViewModel.getCocktailById( ( cocktailId ?: "17225" ) )
InformationScreen( cocktailsViewModel = cocktailViewModel, cocktail = cocktailViewModel.allCocktailsState.value.listOfCocktails.first() )
}
}
} | 0 | Kotlin | 0 | 0 | de71e85dd3a662c029404b93ea1a936f9d8f3c7f | 2,801 | CocktailConnoisseur | Apache License 2.0 |
app/src/main/java/com/notisaver/main/log/core/AppMetaCacheManager.kt | Viet200103 | 724,431,957 | false | {"Kotlin": 453537} | package com.notisaver.main.log.core
import com.notisaver.database.NotisaveRepository
import com.notisaver.database.entities.AppMetaData
import java.util.concurrent.ConcurrentHashMap
class AppMetaCacheManager private constructor(
private val repository: NotisaveRepository
) {
private val metaCache = ConcurrentHashMap<String, AppMetaData>();
private fun getAppMetaDataInCache(packageHashcode: String) = metaCache[packageHashcode]
internal suspend fun getAppMetaData(packageHashcode: String): AppMetaData? {
return getAppMetaDataInCache(packageHashcode) ?: repository.getAppMetaData(packageHashcode)
}
internal suspend fun logAppMetaData(app: AppMetaData) {
repository.logAppMetaData(app)
metaCache[app.packageHashcode] = app
}
companion object {
private var INSTANCE: AppMetaCacheManager? = null
internal fun getInstance(repository: NotisaveRepository): AppMetaCacheManager {
if (INSTANCE == null) {
synchronized(this) {
INSTANCE = AppMetaCacheManager(repository)
}
}
return INSTANCE!!
}
}
} | 0 | Kotlin | 0 | 2 | 6b479442f63a0ce9314d7c8dc08870afd1787555 | 1,176 | Notification-History-Android | MIT License |
app/src/main/java/com/ollieSoft/ballCorral/gameSimulation/gameEntities/MobileEntity.kt | trlaw | 330,250,448 | false | null | package com.ollieSoft.ballCorral.gameSimulation.gameEntities
import com.ollieSoft.ballCorral.gameSimulation.CollisionGrid
import com.ollieSoft.ballCorral.gameSimulation.GameBoundary
interface MobileEntity {
fun travel(dt: Double, gameBoundary: GameBoundary)
} | 0 | Kotlin | 0 | 0 | 7af42878d2760ae778e08aaa453ce802f0480180 | 267 | BallCorral | MIT License |
app/src/main/java/com/kusamaru/standroid/nicoapi/nicorepo/NicoRepoDataClass.kt | kusamaru | 442,642,043 | false | null | package io.github.takusan23.tatimidroid.nicoapi.nicorepo
/**
* ニコレポのデータクラス
* @param isVideo 動画ならtrue、生放送ならfalse
* @param message ニコレポで表示するメッセージ
* @param title 動画、生放送のタイトル
* @param userName アカウント名
* @param contentId 動画ID、生放送ID
* @param date じかん
* @param thumbUrl サムネURL
* */
data class NicoRepoDataClass(
val isVideo: Boolean,
val message: String,
val contentId: String,
val date: Long,
val thumbUrl: String,
val title: String,
val userName: String,
val userId: String,
val userIcon: String,
) | 0 | null | 0 | 3 | 5c58707eecc7a994fbd4bc900b22106697bf3806 | 538 | StanDroid | Apache License 2.0 |
idea/idea-frontend-fir/testData/symbols/symbolByPsi/typeAlias.kt | MikhniukR | 391,971,724 | false | null | class X<T>
typealias Y<Z> = X<Z>
// RESULT
/*
KtFirTypeParameterSymbol:
isReified: false
name: T
origin: SOURCE
upperBounds: [kotlin/Any?]
variance: INVARIANT
KtFirNamedClassOrObjectSymbol:
annotationClassIds: []
annotations: []
classIdIfNonLocal: X
classKind: CLASS
companionObject: null
isData: false
isExternal: false
isFun: false
isInline: false
isInner: false
modality: FINAL
name: X
origin: SOURCE
superTypes: [[] kotlin/Any]
symbolKind: TOP_LEVEL
typeParameters: [KtFirTypeParameterSymbol(T)]
visibility: Public
KtFirTypeParameterSymbol:
isReified: false
name: Z
origin: SOURCE
upperBounds: [kotlin/Any?]
variance: INVARIANT
KtFirTypeAliasSymbol:
classIdIfNonLocal: Y
expandedType: X<Z>
name: Y
origin: SOURCE
symbolKind: TOP_LEVEL
*/
| 1 | null | 1 | 2 | 947e97511b56dd19a7593ac02c20f28a55e9f9fb | 811 | kotlin | Apache License 2.0 |
src/main/kotlin/ch/sourcemotion/vertx/kinesis/consumer/orchestra/consumer/StartFetchPositionLookup.kt | wem | 253,237,315 | false | null | package ch.sourcemotion.vertx.kinesis.consumer.orchestra.consumer
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.ShardIteratorStrategy
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.*
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl.ext.isNotNull
import ch.sourcemotion.vertx.kinesis.consumer.orchestra.spi.ShardStatePersistenceServiceAsync
import io.vertx.core.Vertx
import io.vertx.kotlin.coroutines.await
import mu.KLogging
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient
import software.amazon.awssdk.services.kinesis.model.ShardIteratorType
internal class StartFetchPositionLookup(
private val vertx: Vertx,
private val consumerInfo: String,
private val shardId: ShardId,
private val options: KinesisConsumerVerticleOptions,
private val shardStatePersistenceService: ShardStatePersistenceServiceAsync,
private val kinesisClient: KinesisAsyncClient
) {
private companion object : KLogging()
suspend fun getStartFetchPosition(): FetchPosition {
return when (options.shardIteratorStrategy) {
ShardIteratorStrategy.FORCE_LATEST -> {
logger.debug { "Force ${ShardIteratorType.LATEST.name} shard iterator on $consumerInfo" }
FetchPosition(kinesisClient.getLatestShardIteratorAwait(options.clusterName.streamName, shardId), null)
}
ShardIteratorStrategy.EXISTING_OR_LATEST -> {
val existingSequenceNumber = shardStatePersistenceService.getConsumerShardSequenceNumber(shardId)
if (existingSequenceNumber.isNotNull()) {
logger.debug { "Use existing shard sequence number: \"$existingSequenceNumber\" for $consumerInfo" }
FetchPosition(getShardIteratorBySequenceNumber(existingSequenceNumber), existingSequenceNumber)
} else {
// If the import address is defined, we try to import the sequence number to start from DynamoDB (KCL V1)
val importedSequenceNbr = if (options.sequenceNbrImportAddress.isNotNull()) {
vertx.eventBus().request<String>(options.sequenceNbrImportAddress, "$shardId").await().body()
} else null
if (importedSequenceNbr.isNotNull()) {
logger.debug { "Use KCL V1 imported sequence number for $consumerInfo" }
FetchPosition(
getShardIteratorBySequenceNumber(
SequenceNumber(importedSequenceNbr, SequenceNumberIteratorPosition.AFTER)
), existingSequenceNumber
)
} else {
logger.debug { "Use ${ShardIteratorType.LATEST.name} shard iterator for $consumerInfo because no existing position found" }
FetchPosition(kinesisClient.getLatestShardIteratorAwait(options.clusterName.streamName, shardId), null)
}
}
}
}
}
private suspend fun getShardIteratorBySequenceNumber(existingSequenceNumber: SequenceNumber): ShardIterator {
return kinesisClient.getShardIteratorBySequenceNumberAwait(
options.clusterName.streamName,
shardId,
existingSequenceNumber
)
}
}
| 6 | Kotlin | 0 | 4 | 026f06f31457f0ba99b688864ea5d4cfde3c2f4d | 3,368 | vertx-kinesis-consumer-orchestra | MIT License |
app/src/main/java/com/william/easykt/ui/DataStoreActivity.kt | WeiLianYang | 255,907,870 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "Kotlin": 215, "XML": 118, "Java": 4, "Protocol Buffer": 1} | /*
* Copyright WeiLianYang
*
* 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.william.easykt.ui
import android.content.Context
import androidx.activity.viewModels
import androidx.datastore.core.DataStore
import androidx.datastore.dataStore
import com.william.base_component.activity.BaseActivity
import com.william.base_component.extension.APP_DATA_STORE_FILE_NAME
import com.william.base_component.extension.bindingView
import com.william.base_component.extension.dataStore
import com.william.easykt.R
import com.william.easykt.UserPreferences
import com.william.easykt.data.repo.PreferencesRepository
import com.william.easykt.data.repo.UserPreferencesRepository
import com.william.easykt.databinding.ActivityDatastoreBinding
import com.william.easykt.datastore.serializer.UserPreferencesSerializer
import com.william.easykt.viewmodel.DataStoreViewModel
import com.william.easykt.viewmodel.provideFactory
// Build the DataStore
private val Context.userPreferencesStore: DataStore<UserPreferences> by dataStore(
fileName = APP_DATA_STORE_FILE_NAME,
serializer = UserPreferencesSerializer()
)
/**
* @author William
* @date 2022/8/22 21:35
* Class Comment:Data Store demo
*/
class DataStoreActivity : BaseActivity() {
override val viewBinding: ActivityDatastoreBinding by bindingView()
private val viewModel: DataStoreViewModel by viewModels {
provideFactory<DataStoreViewModel>(
PreferencesRepository(dataStore),
UserPreferencesRepository(userPreferencesStore)
)
}
override fun initView() {
super.initView()
viewBinding.button1.setOnClickListener {
viewModel.savePreferencesData()
}
viewBinding.button2.setOnClickListener {
viewModel.saveUserPreferencesData()
}
}
override fun initData() {
setTitleText(R.string.test_datastore)
viewModel.preferencesData.observe(this) {
viewBinding.text1.text = it
}
viewModel.userPreferencesData.observe(this) {
viewBinding.text2.text = it.toString()
}
}
} | 0 | Kotlin | 6 | 21 | 6e33d7c32945a261117a7de8f2a388a5187637c5 | 2,635 | EasyKotlin | Apache License 2.0 |
core/src/commonTest/kotlin/json/src/RoutePlanners.kt | DRSchlaubi | 295,040,489 | false | null | package json.src
//language=JSON
const val ROTATING_NANO_IP_ROUTE_PLANNER: String = """
{
"class": "RotatingNanoIpRoutePlanner",
"details": {
"ipBlock": {
"type": "Inet6Address",
"size": "1213123321"
},
"failingAddresses": [
{
"address": "/1.0.0.0",
"failingTimestamp": 1573520707545,
"failingTime": "Mon Nov 11 20:05:07 EST 2019"
}
],
"blockIndex": "0",
"currentAddressIndex": "36792023813"
}
}
"""
//language=JSON
const val ROTATING_IP_ROUTE_PLANNER: String = """
{
"class": "RotatingIpRoutePlanner",
"details": {
"ipBlock": {
"type": "Inet6Address",
"size": "1213123321"
},
"failingAddresses": [
{
"address": "/1.0.0.0",
"failingTimestamp": 1573520707545,
"failingTime": "Mon Nov 11 20:05:07 EST 2019"
}
],
"rotateIndex": "1",
"ipIndex": "1",
"currentAddress": "1"
}
}
"""
//language=JSON
const val NANO_IP_ROUTE_PLANNER: String = """
{
"class": "NanoIpRoutePlanner",
"details": {
"ipBlock": {
"type": "Inet6Address",
"size": "1213123321"
},
"failingAddresses": [
{
"address": "/1.0.0.0",
"failingTimestamp": 1573520707545,
"failingTime": "Mon Nov 11 20:05:07 EST 2019"
}
],
"currentAddressIndex": 1
}
}
"""
| 1 | null | 8 | 32 | b0c7f64b358b11f825ea5defe4056ca0d294cec3 | 1,582 | Lavalink.kt | MIT License |
core/src/commonMain/kotlin/info/laht/threekt/renderers/shaders/chunk/defaultnormal_vertex.kt | op07n | 204,459,686 | false | null | package info.laht.threekt.renderers.shaders.chunk
internal val __defaultnormal_vertex = """
vec3 transformedNormal = normalMatrix * objectNormal;
#ifdef FLIP_SIDED
transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
vec3 transformedTangent = normalMatrix * objectTangent;
#ifdef FLIP_SIDED
transformedTangent = - transformedTangent;
#endif
#endif
"""
| 1 | null | 1 | 1 | 285ad220a5e20b82700d65b74e39da20effe7c2c | 386 | three.kt | MIT License |
app/src/main/kotlin/au/com/abhishek/android/rxkotlin/fragments/RotationPersist1WorkerFragment.kt | cheetahmail007 | 257,058,942 | false | null | package au.com.tilbrook.android.rxkotlin.fragments
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import java.util.concurrent.TimeUnit
import au.com.tilbrook.android.rxkotlin.MainActivity
import org.jetbrains.anko.support.v4.ctx
import rx.Observable
import rx.Subscription
import rx.functions.Func1
import rx.observables.ConnectableObservable
class RotationPersist1WorkerFragment : Fragment() {
private var _masterFrag: IAmYourMaster? = null
private var _storedIntsObservable: ConnectableObservable<Int>? = null
private var _storedIntsSubscription: Subscription? = null
/**
* Hold a reference to the activity -> caller fragment
* this way when the worker frag kicks off
* we can talk back to the master and send results
*/
override fun onAttach(activity: Context?) {
super.onAttach(ctx)
val frags = (activity as MainActivity?)!!.supportFragmentManager.fragments
for (f in frags) {
if (f is IAmYourMaster) {
_masterFrag = f
}
}
if (_masterFrag == null) {
throw ClassCastException("We did not find a master who can understand us :(")
}
}
/**
* This method will only be called once when the retained Fragment is first created.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Retain this fragment across configuration changes.
retainInstance = true
if (_storedIntsObservable != null) {
return
}
val intsObservable = //
Observable.interval(1, TimeUnit.SECONDS)//
.map(object : Func1<Long, Int> {
override fun call(aLong: Long?): Int? {
return aLong!!.toInt()
}
})//
.take(20)
// -----------------------------------------------------------------------------------
// Making our observable "HOT" for the purpose of the demo.
//_intsObservable = _intsObservable.share();
_storedIntsObservable = intsObservable.replay()
_storedIntsSubscription = _storedIntsObservable!!.connect()
// Do not do this in production!
// `.share` is "warm" not "hot"
// the below forceful subscription fakes the heat
//_intsObservable.subscribe();
}
/**
* The Worker fragment has started doing it's thing
*/
override fun onResume() {
super.onResume()
_masterFrag!!.observeResults(_storedIntsObservable!!)
}
/**
* Set the callback to null so we don't accidentally leak the
* Activity instance.
*/
override fun onDetach() {
super.onDetach()
_masterFrag = null
}
override fun onDestroy() {
super.onDestroy()
_storedIntsSubscription!!.unsubscribe()
}
interface IAmYourMaster {
fun observeResults(intsObservable: ConnectableObservable<Int>)
}
}
| 2 | null | 17 | 3 | d834b7550f8f0ecdd7a1eaa0bc6b3fb639276adf | 3,145 | PlaywithRxKotlin | Apache License 2.0 |
app/src/main/kotlin/com/absinthe/libchecker/features/snapshot/detail/ui/view/SnapshotTitleView.kt | LibChecker | 248,400,799 | false | {"Kotlin": 1162665, "Java": 57156, "AIDL": 1149} | package com.absinthe.libchecker.features.snapshot.detail.ui.view
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.core.view.marginEnd
import androidx.core.view.marginStart
import com.absinthe.libchecker.R
import com.absinthe.libchecker.features.snapshot.detail.bean.SnapshotDiffItem
import com.absinthe.libchecker.utils.LCAppUtils
import com.absinthe.libchecker.utils.extensions.getColor
import com.absinthe.libchecker.utils.extensions.getColorByAttr
import com.absinthe.libchecker.utils.extensions.getDimensionPixelSize
import com.absinthe.libchecker.utils.extensions.sizeToString
import com.absinthe.libchecker.view.AViewGroup
import com.absinthe.libchecker.view.app.AlwaysMarqueeTextView
class SnapshotTitleView(
context: Context,
attributeSet: AttributeSet? = null
) : AViewGroup(context, attributeSet) {
val iconView = AppCompatImageView(context).apply {
val iconSize = context.getDimensionPixelSize(R.dimen.lib_detail_icon_size)
layoutParams = LayoutParams(iconSize, iconSize)
setImageResource(R.drawable.ic_icon_blueprint)
addView(this)
}
val appNameView = AlwaysMarqueeTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifMedium
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
).also {
it.marginStart = context.getDimensionPixelSize(R.dimen.normal_padding)
}
setTextColor(context.getColorByAttr(com.google.android.material.R.attr.colorOnSurface))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
addView(this)
}
val packageNameView =
AppCompatTextView(ContextThemeWrapper(context, R.style.TextView_SansSerif)).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(context.getColorByAttr(com.google.android.material.R.attr.colorOnSurface))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
addView(this)
}
val versionInfoView = AppCompatTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifCondensed
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(android.R.color.darker_gray.getColor(context))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
addView(this)
}
val packageSizeView = AppCompatTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifCondensed
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(android.R.color.darker_gray.getColor(context))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
addView(this)
}
val apisView = AppCompatTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifCondensedMedium
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(android.R.color.darker_gray.getColor(context))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
addView(this)
}
fun setPackageSizeText(item: SnapshotDiffItem, isNewOrDeleted: Boolean) {
if (item.packageSizeDiff.old > 0L) {
packageSizeView.isVisible = true
val sizeDiff = SnapshotDiffItem.DiffNode(
item.packageSizeDiff.old.sizeToString(context),
item.packageSizeDiff.new?.sizeToString(context)
)
val sizeDiffAppend = StringBuilder(LCAppUtils.getDiffString(sizeDiff, isNewOrDeleted))
if (item.packageSizeDiff.new != null) {
val diffSize = item.packageSizeDiff.new - item.packageSizeDiff.old
val diffSizeText = buildString {
append(if (diffSize > 0) "+" else "")
append(diffSize.sizeToString(context))
}
if (diffSize != 0L) {
sizeDiffAppend.append(", $diffSizeText")
}
}
packageSizeView.text = sizeDiffAppend
} else {
packageSizeView.isVisible = false
}
}
fun setApisText(item: SnapshotDiffItem, isNewOrDeleted: Boolean) {
val targetDiff = LCAppUtils.getDiffString(item.targetApiDiff, isNewOrDeleted).takeIf { item.targetApiDiff.old > 0 }
val minDiff = LCAppUtils.getDiffString(item.minSdkDiff, isNewOrDeleted).takeIf { item.minSdkDiff.old > 0 }
val compileDiff = LCAppUtils.getDiffString(item.compileSdkDiff, isNewOrDeleted).takeIf { item.compileSdkDiff.old > 0 }
apisView.text = buildSpannedString {
targetDiff?.let {
scale(1f) {
append("Target: ")
}
append(it)
append(" ")
}
minDiff?.let {
scale(1f) {
append("Min: ")
}
append(it)
append(" ")
}
compileDiff?.let {
scale(1f) {
append("Compile: ")
}
append(it)
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
children.forEach {
it.autoMeasure()
}
val textWidth =
measuredWidth - paddingStart - paddingEnd - iconView.measuredWidth - appNameView.marginStart
if (appNameView.measuredWidth > textWidth) {
appNameView.measure(
(textWidth - apisView.measuredWidth - appNameView.marginEnd).toExactlyMeasureSpec(),
appNameView.defaultHeightMeasureSpec(this)
)
}
if (packageNameView.measuredWidth > textWidth) {
packageNameView.measure(
textWidth.toExactlyMeasureSpec(),
packageNameView.defaultHeightMeasureSpec(this)
)
}
if (versionInfoView.measuredWidth > textWidth) {
versionInfoView.measure(
textWidth.toExactlyMeasureSpec(),
versionInfoView.defaultHeightMeasureSpec(this)
)
}
if (packageSizeView.measuredWidth > textWidth) {
packageSizeView.measure(
textWidth.toExactlyMeasureSpec(),
packageSizeView.defaultHeightMeasureSpec(this)
)
}
if (apisView.measuredWidth > textWidth) {
apisView.measure(
textWidth.toExactlyMeasureSpec(),
apisView.defaultHeightMeasureSpec(this)
)
}
setMeasuredDimension(
measuredWidth,
paddingTop +
appNameView.measuredHeight +
packageNameView.measuredHeight +
versionInfoView.measuredHeight +
packageSizeView.measuredHeight +
apisView.measuredHeight +
paddingBottom
)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
iconView.layout(paddingStart, paddingTop)
val appNameXOffset = paddingStart + iconView.measuredWidth + appNameView.marginStart
appNameView.layout(appNameXOffset, paddingTop)
packageNameView.layout(appNameXOffset, appNameView.bottom)
versionInfoView.layout(appNameXOffset, packageNameView.bottom)
packageSizeView.layout(appNameXOffset, versionInfoView.bottom)
apisView.layout(appNameXOffset, packageSizeView.bottom)
}
}
| 36 | Kotlin | 307 | 4,430 | 6a05bb1cff75020fd2f9f2421dfdb25b4e2cc0a9 | 7,451 | LibChecker | Apache License 2.0 |
idea/tests/testData/checker/diagnosticsMessage/incompleteTypeArgumentList.fir.kt | JetBrains | 278,369,660 | false | null | // IGNORE_K2
interface ApplicationFeature<in P : Pipeline<*>, B : Any, V>
open class Pipeline<TSubject : Any>()
fun <A : Pipeline<*>, T : Any, V> A.feature(feature: <error descr="[WRONG_NUMBER_OF_TYPE_ARGUMENTS] 3 type arguments expected for ApplicationFeature">ApplicationFeature<A, T></error>) : Unit {}
| 284 | null | 5162 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 307 | intellij-kotlin | Apache License 2.0 |
sample/sample-android/src/main/java/com/example/sampleandroid/view/model/UserScreen.kt | dss99911 | 138,060,985 | false | null | package com.example.sampleandroid.view.model
import androidx.compose.foundation.ScrollableColumn
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import kim.jeonghyeon.androidlibrary.compose.Screen
import kim.jeonghyeon.androidlibrary.compose.asValue
import kim.jeonghyeon.androidlibrary.compose.widget.Button
import kim.jeonghyeon.sample.viewmodel.UserViewModel
import kim.jeonghyeon.util.log
@Composable
fun UserScreen(model: UserViewModel) {
Screen(model) {
ScrollableColumn {
val userDetail = model.user.asValue() ?: return@ScrollableColumn
Text("Id : ${userDetail.id}")
Text("Name : ${userDetail.name}")
Button("Log Out") { model.onClickLogOut() }
}
}
}
// TODO reactive way.
//@Composable
//fun UserScreen2(model: UserViewModel2) {
// Screen(model) {
// ScrollableColumn {
// val userDetail = model.user.asValue() ?: return@ScrollableColumn
// Text("Id : ${userDetail.id}")
// Text("Name : ${userDetail.name}")
// Button("Log Out", model.click)
// }
// }
//} | 1 | null | 2 | 38 | e9da57fdab9c9c1169fab422fac7432143e2c02c | 1,135 | kotlin-simple-architecture | Apache License 2.0 |
src/main/kotlin/exnihilofabrico/api/recipes/witchwater/WitchWaterEntityRecipe.kt | SirLyle | 220,114,285 | false | null | package exnihilofabrico.api.recipes.witchwater
import exnihilofabrico.api.crafting.EntityTypeIngredient
import net.minecraft.entity.Entity
import net.minecraft.entity.EntityType
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.passive.VillagerEntity
import net.minecraft.village.VillagerProfession
import java.util.function.Predicate
data class WitchWaterEntityRecipe(val target: EntityTypeIngredient,
val profession: VillagerProfession?,
val tospawn: EntityType<*>
): Predicate<Entity?> {
override fun test(entity: Entity?): Boolean {
if(entity == null || entity !is LivingEntity)
return false
if(target.test(entity.type)) {
return if(entity is VillagerEntity)
entity.villagerData.profession == profession
else
profession == null
}
return false
}
} | 5 | null | 4 | 3 | 5224a14b7b50ab5df34a9edbd5ea9e63d743ed62 | 948 | ExNihiloFabrico | MIT License |
151004/Bashlikov/rv_task02/src/main/kotlin/by/bashlikovvv/api/dto/request/UpdateEditorDto.kt | freezton | 787,608,094 | true | {"Markdown": 14, "Batchfile": 51, "Java": 5246, "INI": 154, "TypeScript": 114, "SQL": 18, "Dockerfile": 61, "C#": 4133, "Go": 33, "Java Properties": 36, "Shell": 13, "HTML": 9, "PHP": 177, "CSS": 20, "JavaScript": 5, "Gradle Kotlin DSL": 37, "Kotlin": 596, "Java Server Pages": 23, "HTML+Razor": 6} | package by.bashlikovvv.api.dto.request
import by.bashlikovvv.util.inRange
import kotlinx.serialization.Serializable
import kotlin.jvm.Throws
@Serializable
data class CreateEditorDto @Throws(IllegalArgumentException::class) constructor(
val login: String,
val password: String,
val firstname: String,
val lastname: String
) {
init {
require(login.inRange(2, 64))
require(password.inRange(8, 128))
require(firstname.inRange(2, 64))
require(lastname.inRange(2, 64))
}
} | 0 | Java | 0 | 0 | f858e2a964bbda47bac057cede8ced3287221573 | 526 | Distributed-Computing | MIT License |
solutions/src/MiniumSizeSubArraySum.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 324, "Java": 15} | import kotlin.math.min
/**
* https://leetcode.com/problems/minimum-size-subarray-sum/
*/
class MiniumSizeSubArraySum {
fun minSubArrayLen(s: Int, nums: IntArray) : Int {
if (nums.isEmpty()) {
return 0
}
var minLength : Int? = null
var lower = 0
var upper = 0
var sumAtLower = IntArray(nums.size)
var sumUpper = IntArray(nums.size)
val totalSum = nums.sum()
for(i in nums.indices) {
if (i == 0) {
sumAtLower[0] = nums[0]
}
else {
sumAtLower[i]=nums[i]+sumAtLower[i-1]
}
}
for (i in nums.lastIndex downTo 0) {
if (i == nums.lastIndex) {
sumUpper[i] = nums[i]
}
else {
sumUpper[i] = nums[i]+sumUpper[i+1]
}
}
while (lower in 0..upper && upper < nums.size) {
val sum = when {
lower == 0 -> {
sumAtLower[upper]
}
upper == nums.lastIndex -> {
sumUpper[lower]
}
else -> {
totalSum - (sumAtLower[lower-1]+sumUpper[upper+1])
}
}
if (sum >= s) {
minLength = minOf(1 + (upper- lower), minLength ?: Int.MAX_VALUE)
lower++
}
else {
upper++
}
}
return minLength ?: 0
}
} | 1 | null | 1 | 1 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,535 | leetcode-solutions | MIT License |
compiler/testData/objc/java/callbacks/returnType/short.kt | udalov | 10,645,710 | false | {"Java": 9931656, "Kotlin": 2142480, "JavaScript": 942412, "C++": 613791, "C": 193807, "Objective-C": 22634, "Shell": 12589, "Groovy": 1267} | package test
import objc.A
fun main(args: Array<String>) {
A.printOKIf42 { 42 }
}
| 1 | Java | 1 | 6 | 3958b4a71d8f9a366d8b516c4c698aae80ecfe57 | 88 | kotlin-objc-diploma | Apache License 2.0 |
src/main/java/org/tokend/sdk/api/identity/IdentitiesService.kt | tokend | 153,458,393 | false | {"Gradle": 2, "Markdown": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "INI": 1, "Kotlin": 247, "Java": 209} | package org.tokend.sdk.api.identity
import com.github.jasminb.jsonapi.JSONAPIDocument
import org.tokend.sdk.api.base.model.AttributesEntity
import org.tokend.sdk.api.base.model.DataEntity
import org.tokend.sdk.api.identity.model.*
import retrofit2.Call
import retrofit2.http.*
interface IdentitiesService {
@GET("identities")
@JvmSuppressWildcards
fun get(@QueryMap query: Map<String, Any>): Call<JSONAPIDocument<List<IdentityResource>>>
@POST("identities")
@JvmSuppressWildcards
fun create(@Body body: DataEntity<AttributesEntity<Any>>): Call<JSONAPIDocument<IdentityResource>>
@POST("identities/mass-emails")
@JvmSuppressWildcards
fun getByAccountIds(@Body body: DataEntity<List<MassEmailAccountKey>>):
Call<JSONAPIDocument<List<IdentityResource>>>
@PUT("identities/{accountId}/settings/phone")
@JvmSuppressWildcards
fun setPhone(
@Path("accountId") accountId: String,
@Body body: DataEntity<AttributesEntity<Any>>
): Call<Void>
@PUT("identities/{accountId}/settings/passport")
@JvmSuppressWildcards
fun setPassportId(
@Path("accountId") accountId: String,
@Body body: DataEntity<AttributesEntity<Any>>
): Call<Void>
@PUT("identities/{accountId}/settings/telegram")
@JvmSuppressWildcards
fun setTelegramUsername(
@Path("accountId") accountId: String,
@Body body: DataEntity<AttributesEntity<Any>>
): Call<Void>
@GET("identities/{accountId}/settings")
@JvmSuppressWildcards
fun getSettings(
@Path("accountId") accountId: String,
@QueryMap query: Map<String, Any>
): Call<JSONAPIDocument<List<IdentitySettingsResource>>>
@GET("identities/{accountId}/settings/{key}")
@JvmSuppressWildcards
fun getSettingsItemByKey(
@Path("accountId") accountId: String,
@Path("key") key: String
): Call<JSONAPIDocument<IdentitySettingsResource>>
@PUT("identities/{accountId}/settings")
@JvmSuppressWildcards
fun setSettingsItem(
@Path("accountId") accountId: String,
@Body data: DataEntity<AttributesEntity<Any>>
): Call<Void>
} | 0 | Kotlin | 1 | 14 | f29c3aa9e251a38f76a7dc26960f7a8796a79975 | 2,161 | kotlin-sdk | Apache License 2.0 |
app/src/main/java/ru/tohaman/rg2/activities/F2LPagerActivity.kt | Tohaman | 113,494,425 | false | null | package ru.tohaman.rg2.activities
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.app_bar_sliding.*
import ru.tohaman.rg2.*
import ru.tohaman.rg2.adapters.MyOnlyImageListAdapter
import ru.tohaman.rg2.data.ListPager
import ru.tohaman.rg2.data.ListPagerLab
import ru.tohaman.rg2.fragments.FragmentF2LPagerItem
import java.util.ArrayList
class F2LPagerActivity : MyDefaultActivity(),
View.OnClickListener,
SharedPreferences.OnSharedPreferenceChangeListener,
FragmentF2LPagerItem.OnViewPagerInteractionListener
{
private lateinit var mListPagers : ArrayList<ListPager>
private lateinit var mListMainItem : ArrayList<ListPager>
private lateinit var mListPagerLab : ListPagerLab
private var curPhase = "EXP_F2L"
private var curId = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.v (DebugTag.TAG, "F2LPagerActivity onCreate")
setContentView(R.layout.activity_oll_pager)
setSupportActionBar(toolbar)
//Инициируем фазу и номер этапа, должны быть переданы из другой активности, если нет, то используем значения по-умолчанию
if (intent.hasExtra(RUBIC_PHASE)) curPhase = intent.extras!!.getString(RUBIC_PHASE)!!
if (intent.hasExtra(EXTRA_ID)) curId = intent.extras!!.getInt(EXTRA_ID)
Log.v (DebugTag.TAG, "SlidingTabActivity onCreate Инициализируем ListPagers и передаем его адаптерам")
mListPagerLab = ListPagerLab.get(this)
mListPagers = mListPagerLab.getPhaseList(curPhase, "0").filter { it.url != "ollPager" } as ArrayList<ListPager>
setSlidingTabAdapter(convertDescription2ListPagers(mListPagers[curId]))
viewPagerSlidingTabs.currentItem = 0
tabs.setViewPager(viewPagerSlidingTabs)
val mRecyclerView = findViewById<RecyclerView>(R.id.leftRecycleView)
// Создаем вертикальный RecycleView (задаем Layout Manager)
mRecyclerView.layoutManager = LinearLayoutManager(this)
// Назначаем адаптер типа MyOnlyImage элемент которого только картинка
// назначем обработчик для слушателя onClick адаптера в активности
mListMainItem = mListPagers.filter { it.subID == "0" } as ArrayList<ListPager>
mRecyclerView.adapter = MyOnlyImageListAdapter(mListMainItem,this)
}
private fun convertDescription2ListPagers(lp:ListPager): ArrayList<ListPager> {
return mListPagerLab.getPhaseItemList(lp.id, lp.phase)
}
//при смене этапа, меняем (устанавливаем) адаптер для слайдингтаба
private fun setSlidingTabAdapter(mListPagers: ArrayList<ListPager>) {
// подключим адаптер для слайдингтаба (основного текста)
val adapter = object : FragmentStatePagerAdapter(supportFragmentManager) {
override fun getPageTitle(position: Int): CharSequence {
//Заголовки для ViewPager
return mListPagers[position].subTitle
}
override fun getCount(): Int {
//Количество элементов для ViewPager
return mListPagers.size
}
override fun getItem(position: Int): Fragment {
//возвращает фрагмент с элементом для ViewPager
return FragmentF2LPagerItem.newInstance(mListPagers[position])
}
}
viewPagerSlidingTabs.adapter = adapter
}
//обрабатываем onClick по элементам RecycleView, через перехват onClick адаптера
override fun onClick(view: View?) {
val position = view?.tag as Int
//Log.v (DebugTag.TAG, "F2LPagerActivity Click on item $position")
setSlidingTabAdapter(convertDescription2ListPagers(mListMainItem[position]))
tabs.setViewPager(viewPagerSlidingTabs)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| 4 | Kotlin | 2 | 2 | a1755567246a90bca00020b38d58f6a1482511d1 | 4,273 | RG2.kotlin | Apache License 2.0 |
app/src/main/java/cn/imppp/knowlege/constant/FileTagEnum.kt | immppp | 311,555,492 | false | null | package cn.imppp.knowlege.constant
enum class FileTagEnum(val tag: Int,
val message: String,
val titleMessage: String) {
PREPARE_TAG(1, "出发准备", "应急小分队出发前准备"),
THINGS_PREPARE(2, "物资准备", "物资准备"),
PRO_PREPARE(3, "专业准备与装备", "专业准备与装备"),
TRAN_PREPARE(4, "交通和后勤保障", "交通和后勤保障"),
THINGS_PREPARE_FLAG1(5, "生活用品", "生活用品"),
THINGS_PREPARE_FLAG2(6, "通讯设备", "通讯设备"),
THINGS_PREPARE_FLAG3(7, "个人防护设备", "个人防护设备"),
// 流行病调查
DISEASE_QUERY(8, "流调步骤", "现场流行病学调查步骤"),
DISEASE_PREPARE(9, "组织准备", "组织准备"),
DISEASE_CONFIRM(10, "核实病例诊断", "核实病例诊断"),
DISEASE_EXSIT(11, "确定暴发或流行的存在", "确定暴发或流行的存在"),
DISEASE_BUILD(12, "建立病例定义", "建立病例定义"),
DISEASE_COUNT(13, "核实病例并计算病例数", "核实病例并计算病例数"),
DISEASE_ANY(14, "描述性分析", "描述性分析"),
DISEASE_IDEA(15, "建立并验证假设", "建立并验证假设"),
DISEASE_ADVICE(16, "采取控制措施", "采取控制措施"),
DISEASE_FINISH(17, "完善现场调查", "完善现场调查"),
DISEASE_REPORT(18, "书面报告", "书面报告"),
// 群体性不明原因疾病现场调查处置要点
SOCIAL_DEAL(19, "群体性不明事件", "群体性不明原因疾病现场调查处置要点"),
SOCIAL_CONFIRM(20, "核实与判断", "核实与判断"),
SOCIAL_ANY(21, "病例调查及分析", "病例调查及分析"),
SOCIAL_CHECK(22, "样本采集和实验室检测", "样本采集和实验室检测"),
SOCIAL_CONTROL(23, "现场控制措施", "现场控制措施"),
SOCIAL_ANY1(24, "病例搜索", "病例搜索"),
SOCIAL_ANY2(25, "初步分析", "初步分析"),
SOCIAL_ANY3(26, "提出病因假设", "提出病因假设"),
SOCIAL_ANY4(27, "验证病因", "验证病因"),
SOCIAL_ANY5(28, "判断和预测", "判断和预测"),
SOCIAL_CHECK1(29, "感染性疾病标本", "感染性疾病标本"),
SOCIAL_CHECK2(30, "非感染性疾病标本", "非感染性疾病标本"),
// SOCIAL_CHECK3(31, "实验室检测", "实验室检测"),
SOCIAL_CONTROL1(32, "无传染性的不明原因疾病", "无传染性的不明原因疾病"),
SOCIAL_CONTROL2(33, "有传染性的不明原因疾病", "有传染性的不明原因疾病"),
// 病媒生物应急控制要点
CRITICAL_CONTROL(34, "病媒控制", "病媒生物应急控制要点"),
CRITICAL_BASE_REQUIRE(35, "基本要求", "现场病媒生物控制的基本要求"),
CRITICAL_MOUSE_DEAL(36, "现场鼠类防制", "现场鼠类防制"),
CRITICAL_WEN_DEAL(37, "现场蚊类防制", "现场蚊类防制"),
CRITICAL_YING_DEAL(38, "现场蝇类防制", "现场蝇类防制"),
CRITICAL_BASE_REQUIRE1(39, "准备工作要充足", "准备工作要充足"),
CRITICAL_BASE_REQUIRE2(40, "具体操作要规范", "具体操作要规范"),
CRITICAL_BASE_REQUIRE3(41, "结束工作要做细", "结束工作要做细"),
CRITICAL_MOUSE_DEAL1(42, "灭鼠原则", "灭鼠的原则"),
CRITICAL_MOUSE_DEAL2(43, "灭鼠方法", "鼠类控制方法"),
CRITICAL_MOUSE_DEAL3(44, "灭鼠药物", "常用灭鼠药物"),
CRITICAL_MOUSE_DEAL4(45, "投放毒饵的量和时间", "投放毒饵的量和时间"),
CRITICAL_MOUSE_DEAL5(46, "投放毒饵的要求", "投放毒饵的要求"),
CRITICAL_MOUSE_DEAL6(47, "注意事项", "注意事项"),
CRITICAL_MOUSE_DEAL7(48, "鼠情监测", "鼠情监测"),
CRITICAL_WEN_DEAL1(49, "环境治理", "环境治理"),
CRITICAL_WEN_DEAL2(50, "防蚊驱蚊", "防蚊驱蚊"),
CRITICAL_WEN_DEAL3(10086, "蚊类化学控制", "蚊类化学控制"),
CRITICAL_YING_DEAL1(51, "环境治理", "环境治理"),
CRITICAL_YING_DEAL2(52, "蝇类控制", "蝇类控制"),
// 调查总结报告的撰写
REPORT_WRITING(53, "总结报告", "调查总结报告的撰写"),
WORK_REPORT(54, "业务调查报告", "业务调查总结报告"),
GOVERMENT_REPORT(55, "行政调查报告", "行政调查报告"),
WORK_REPORT1(56, "标题", "标题"),
WORK_REPORT2(57, "前言", "前言"),
WORK_REPORT3(58, "基本情况", "基本情况"),
WORK_REPORT4(59, "流行特点", "流行特点(流行强度、三间分布、相关图表)"),
WORK_REPORT5(60, "临床特点及诊断标准", "临床特点及诊断标准"),
WORK_REPORT6(61, "流行因素分析", "流行因素分析(包括分析流行病学的应用、采样与检测)"),
WORK_REPORT7(62, "防制措施与效果评价", "防制措施与效果评价"),
WORK_REPORT8(63, "建议", "建议"),
WORK_REPORT9(64, "小结", "小结"),
WORK_REPORT10(65, "报告单位和报告日期", "报告单位和报告日期"),
GOVERMENT_REPORT1(66, "标题", "标题"),
GOVERMENT_REPORT2(67, "前言", "前言"),
GOVERMENT_REPORT3(68, "事件概况", "事件概况"),
GOVERMENT_REPORT4(69, "已采取的措施及效果评价", "已采取的措施及效果评价"),
GOVERMENT_REPORT5(70, "调查结论与趋势分析", "调查结论与趋势分析"),
GOVERMENT_REPORT6(71, "下一步建议", "下一步建议"),
GOVERMENT_REPORT7(72, "报告单位和报告日期", "报告单位和报告日期"),
// 应急相关工具包
TOOL_PACKAGE(73, "应急相关工具包", "应急相关工具包"),
// 突发公共安全事件相关信息报告范围与标准
EVENT_RULE(74, "事件报告", "突发公共安全事件相关信息报告范围与标准"),
RECURSION_EVENT(75, "传染病", "传染病"),
FOOD_EVENT(76, "食物中毒", "食物中毒"),
JOB_EVENT(77, "职业中毒", "职业中毒"),
OTHER_EVENT(78, "其他中毒", "其他中毒"),
NATURE_EVENT(79, "环境因素事件", "环境因素事件"),
X_EVENT(80, "意外辐射照射事件", "意外辐射照射事件"),
LOSS_EVENT(81, "传染病菌、毒种丢失", "传染病菌、毒种丢失"),
BAD_EVENT(82, "预防接种和预防服药群体性不良反应", "预防接种和预防服药群体性不良反应"),
HOSPITAL_EVENT(83, "医源性感染事件", "医源性感染事件"),
NO_REASON_EVENT(84, "群体性不明原因疾病", "群体性不明原因疾病"),
THINK_EVENT(85, "其它突发公共卫生事件", "各级人民政府卫生行政部门认定的其它突发公共卫生事件"),
RECURSION_EVENT1(86, "鼠疫", "鼠疫"),
RECURSION_EVENT2(87, "霍乱", "霍乱"),
RECURSION_EVENT3(88, "传染性非典型肺炎", "传染性非典型肺炎"),
RECURSION_EVENT4(89, "人感染高致病性禽流感", "人感染高致病性禽流感"),
RECURSION_EVENT5(90, "炭疽", "炭疽"),
RECURSION_EVENT6(91, "甲肝/戊肝", "甲肝/戊肝"),
RECURSION_EVENT7(92, "伤寒(副伤寒)", "伤寒(副伤寒)"),
RECURSION_EVENT8(93, "细菌性和阿米巴性痢疾", "细菌性和阿米巴性痢疾"),
RECURSION_EVENT9(94, "麻疹", "麻疹"),
RECURSION_EVENT10(95, "风疹", "风疹"),
RECURSION_EVENT11(96, "流行性脑脊髓膜炎", "流行性脑脊髓膜炎"),
RECURSION_EVENT12(97, "登革热", "登革热"),
RECURSION_EVENT13(98, "流行性出血热", "流行性出血热"),
RECURSION_EVENT14(99, "钩端螺旋体病", "钩端螺旋体病"),
RECURSION_EVENT15(100, "流行性乙型脑炎", "流行性乙型脑炎"),
RECURSION_EVENT16(101, "疟疾", "疟疾"),
RECURSION_EVENT17(102, "血吸虫病", "血吸虫病"),
RECURSION_EVENT18(103, "流感", "流感"),
RECURSION_EVENT19(104, "流行性腮腺炎", "流行性腮腺炎"),
RECURSION_EVENT20(105, "感染性腹泻(除霍乱、痢疾、伤寒和副伤寒以外)", "感染性腹泻(除霍乱、痢疾、伤寒和副伤寒以外)"),
RECURSION_EVENT21(106, "猩红热", "猩红热"),
RECURSION_EVENT22(107, "水痘", "水痘"),
RECURSION_EVENT23(108, "输血性乙肝、丙肝、HIV", "输血性乙肝、丙肝、HIV"),
RECURSION_EVENT24(109, "新发或再发传染病", "新发或再发传染病"),
RECURSION_EVENT25(110, "不明原因肺炎", "不明原因肺炎"),
// 几种急性传染病的潜伏期、隔离期与接触者观察期
STATE_TIME(111, "急性传染病观察期", "几种急性传染病的潜伏期、隔离期与接触者观察期"),
CANCER_DISEASE(112, "病毒性肝炎", "病毒性肝炎"),
HEAD_DISEASE(113, "流行性乙型脑炎", "流行性乙型脑炎"),
GREY_DISEASE(114, "脊髓灰质炎", "脊髓灰质炎"),
DOG_DISEASE(115, "狂犬病", "狂犬病"),
POP_HEAD_DISEASE(116, "流行性感冒", "流行性感冒"),
MA_ZHEN(117, "麻疹", "麻疹"),
SHUI_DOU(118, "水痘", "水痘"),
SAI_XIAN(119, "流行性腮腺炎", "流行性腮腺炎"),
DENG_GE_RE(120, "登革热", "登革热"),
ZENG_DUO_ZHENG(121, "传染性单核细胞增多症", "传染性单核细胞增多症"),
AIDS(122, "艾滋病", "艾滋病"),
HUANG_RE_BING(123, "黄热病", "黄热病"),
SHANG_HAN(124, "流行性斑疹伤寒", "流行性斑疹伤寒"),
FU_SHANG(125, "伤寒、副伤寒甲、乙", "伤寒、副伤寒甲、乙"), //
NUE_JI(126, "细菌性痢疾", "细菌性痢疾"),
HUO_LUAN(127, "霍乱", "霍乱"),
GAN_JUN(128, "布氏杆菌病", "布氏杆菌病"),
SHU_YI(129, "鼠疫", "鼠疫"), //
TAN_JU(130, "炭疽", "炭疽"),
BAI_HOU(131, "白喉", "白喉"),
BAI_RI_KE(132, "百日咳", "百日咳"),
XING_HONG_RE(133, "猩红热", "猩红热"),
NAO_JI_SUI(134, "流行性脑脊髓膜炎", "流行性脑脊髓膜炎"),
LUO_XUAN_BING(135, "钩端螺旋体病", "钩端螺旋体病"),
HUI_GUI_RE(136, "回归热(虱传)", "回归热(虱传)"),
CANCER_DISEASE1(137, "甲型", "甲型"),
CANCER_DISEASE2(138, "乙型", "乙型"),
CANCER_DISEASE3(139, "丙型肝炎", "丙型肝炎"),
CANCER_DISEASE4(140, "丁型", "丁型"),
CANCER_DISEASE5(141, "戊型", "戊型"),
FU_SHANG1(142, "伤寒", "伤寒"),
FU_SHANG2(143, "副伤寒", "副伤寒"),
SHU_YI1(144, "腺鼠疫", "腺鼠疫"),
SHU_YI2(145, "肺鼠疫", "肺鼠疫"),
// 临床综合征划分的疾病特征
STUDY_DISEASE(146, "疾病识别", "按临床综合征划分的疾病特征"),
STUDY_DISEASE1(147, "无特征性皮疹的发热",
"无特征性皮疹的发热"),
STUDY_DISEASE2(148, "有特征性皮疹的发热",
"有特征性皮疹的发热"),
STUDY_DISEASE3(149, "发热伴出血",
"发热伴出血"),
STUDY_DISEASE4(150, "发热伴淋巴结肿大",
"发热伴淋巴结肿大"),
STUDY_DISEASE5(151, "发热伴神经系统表现", "发热伴神经系统表现"),
STUDY_DISEASE6(152, "发热伴呼吸道症状", "发热伴呼吸道症状"),
STUDY_DISEASE7(153, "发热伴胃肠道症状",
"发热伴胃肠道症状"),
STUDY_DISEASE8(154, "发热伴黄疸", "发热伴黄疸"),
STUDY_DISEASE9(155, "非发热性疾病", "非发热性疾病"),
STUDY_DISEASE1_1(156, "所有气候", "所有气候"),
STUDY_DISEASE1_2(157, "温暖气候或季节", "温暖气候或季节"),
STUDY_DISEASE2_1(158, "一般性皮疹(斑疹或紫癜)", "一般性皮疹(斑疹或紫癜)"),
STUDY_DISEASE2_2(159, "一般性皮疹(疱疹或脓疱疹)", "一般性皮疹(疱疹或脓疱疹)"),
STUDY_DISEASE2_3(160, "局部性红斑(任何部位)", "局部性红斑(任何部位)"),
STUDY_DISEASE3_1(161, "蚊虫传播", "蚊虫传播"),
STUDY_DISEASE3_2(162, "蜱传播", "蜱传播"),
STUDY_DISEASE3_3(163, "啮齿动物传播", "啮齿动物传播"),
STUDY_DISEASE3_4(164, "病媒不明", "病媒不明"),
STUDY_DISEASE4_1(165, "全身性淋巴结肿大", "全身性淋巴结肿大"),
STUDY_DISEASE4_2(166, "局部性淋巴结肿大", "局部性淋巴结肿大"),
STUDY_DISEASE5_1(167, "瘫痪", "瘫痪"),
STUDY_DISEASE5_2(168, "脑膜炎", "脑膜炎"),
STUDY_DISEASE5_3(169, "脑炎", "脑炎"),
STUDY_DISEASE5_4(170, "有各种致病因子引起的脑膜脑炎", "有各种致病因子引起的脑膜脑炎"),
STUDY_DISEASE6_1(171, "上呼吸道", "上呼吸道(喉、气管、支气管)"),
STUDY_DISEASE6_2(172, "下呼吸道", "下呼吸道(细支气管、肺泡)"),
STUDY_DISEASE7_1(173, "腹泻", "腹泻"),
STUDY_DISEASE7_2(174, "痢疾", "痢疾"),
STUDY_DISEASE7_3(175, "其它", "其它"),
STUDY_DISEASE9_1(176, "皮疹", "皮疹"),
STUDY_DISEASE9_2(177, "神经系统疾病", "神经系统疾病"),
STUDY_DISEASE9_3(178, "呼吸系统疾病", "呼吸系统疾病"),
STUDY_DISEASE9_4(179, "胃肠道疾病", "胃肠道疾病"),
STUDY_DISEASE9_5(180, "食物中毒", "食物中毒"),
STUDY_DISEASE9_6(181, "黄疸", "黄疸"),
STUDY_DISEASE9_7(182, "结合膜炎", "结合膜炎"),
STUDY_DISEASE9_8(183, "泌尿道疾病", "泌尿道疾病"),
// 急性不明原因中毒相关体征的甄别
CHECK_DRUGS(184, "急性不明原因中毒甄别", "急性不明原因中毒相关体征的甄别"),
SMELL_WRONG(185, "气味异常", "气味异常"),
DUO_HAN(186, "多汗", "多汗"),
SKIN_COLOR(187, "皮肤色泽", "皮肤色泽"),
SMELL_WRONG1(188, "酒精味", "酒精味"),
SMELL_WRONG2(189, "芳香味", "芳香味"),
SMELL_WRONG3(190, "臭蛋味", "臭蛋味"),
SMELL_WRONG4(191, "刺鼻味", "刺鼻味"),
SMELL_WRONG5(192, "苦杏仁味", "苦杏仁味"),
SMELL_WRONG6(193, "蒜味", "蒜味"),
SMELL_WRONG7(194, "腐鱼味", "腐鱼味"),
SMELL_WRONG8(195, "水果味", "水果味"),
SMELL_WRONG9(196, "干草味", "干草味"),
SMELL_WRONG10(197, "醋味", "醋味"),
SMELL_WRONG11(198, "鞋油味", "鞋油味"),
SMELL_WRONG12(199, "梨味", "梨味"),
SMELL_WRONG13(200, "更多", "更多"),
DUO_HAN1(201, "全身性多汗", "全身性多汗"),
DUO_HAN2(202, "早期出现大汗淋漓", "早期出现大汗淋漓"),
DUO_HAN3(203, "局部性多汗", "局部性多汗"),
DUO_HAN4(204, "病程中出现多汗", "病程中出现多汗"),
SKIN_COLOR1(205, "高铁血红蛋白症所导致的青紫", "高铁血红蛋白症所导致的青紫"),
SKIN_COLOR2(206, "樱桃红色", "樱桃红色"),
SKIN_COLOR3(207, "黄疸", "黄疸"),
SKIN_COLOR4(208, "潮红色", "潮红色"),
SKIN_COLOR5(209, "双手黄染", "双手黄染"),
SKIN_COLOR6(210, "皮肤损害", "皮肤损害"),
// 不明原因疾病样本采集表
COLLECT_TABLE(211, "不明病因样本采集", "不明原因疾病样本采集表"),
DISEASE_COLLECT1(212, "发热伴呼吸道症状", "发热伴呼吸道症状"),
DISEASE_COLLECT2(213, "发热伴消化道症状", "发热伴消化道症状"),
DISEASE_COLLECT3(214, "发热伴皮疹", "发热伴皮疹"),
DISEASE_COLLECT4(215, "发热伴神经系统症状", "发热伴神经系统症状"),
DISEASE_COLLECT5(216, "发热伴肝和肾功能损伤", "发热伴肾和肝功能损伤"),
DISEASE_COLLECT6(217, "发热伴心脏损伤", "发热伴心脏损伤"),
DISEASE_COLLECT7(218, "发热伴其他症状", "发热伴其他症状"),
DISEASE_COLLECT8(219, "食物中毒", "食物中毒"),
DISEASE_COLLECT9(220, "职业中毒", "职业中毒"),
// 各类食物中毒特点及处理要点
FOOD_DRUGS_DEAL(221, "食物中毒处理", "各类食物中毒特点及处理要点"),
FOOD_DRUGS_DEAL1(222, "化学性食物中毒", "化学性食物中毒"),
FOOD_DRUGS_DEAL2(223, "细菌性食物中毒", "细菌性食物中毒"),
FOOD_DRUGS_DEAL3(224, "真菌毒素食物中毒", "真菌毒素食物中毒"),
FOOD_DRUGS_DEAL4(225, "有毒动物食物中毒", "有毒动物食物中毒"),
FOOD_DRUGS_DEAL5(226, "有毒植物食物中毒", "有毒植物食物中毒"),
// 灾区饮用水水源选择、保护及消毒方法
WATER_USE_FUNCTION(227, "饮用水", "灾区饮用水水源选择、保护及消毒方法"),
WATER_CHOOSE(228, "饮用水源的选择", "饮用水源的选择"),
KEEP_WATER(229, "饮用水水源的保护", "饮用水水源的保护"),
DEAL_WATER(230, "水质的处理与消毒", "水质的处理与消毒"),
CLEAR_WATER(231, "使用一体化净水设备", "使用一体化净水设备"),
TRAN_WATER(232, "运送安全卫生水", "运送安全卫生水"),
RECOVER_WATER(233, "自然灾害恢复期的供水设施消毒", "自然灾害恢复期的供水设施消毒"),
CHECK_WATER(234, "饮水水质检测", "饮用水质检测"),
KEEP_WATER1(235, "防止毒害污染", "灾前做好充分准备,防止有毒有害物的污染"),
KEEP_WATER2(236, "防止人为污染", "饮用水源要防止人为污染"),
DEAL_WATER1(237, "缸(桶)水", "缸(桶)水消毒处理"),
DEAL_WATER2(238, "手压井", "手压井的消毒"),
DEAL_WATER3(239, "大口井", "大口井的消毒"),
DEAL_WATER4(240, "被淹没的自来水厂", "被淹没的自来水厂的水质处理及消毒"),
// 传染病防控现场消毒方法
KILL_VIRUS(241, "现场消毒方法", "传染病防控现场消毒方法"),
DI_MIAN(242, "地面、墙壁", "地面、墙壁"),
PAI_XIE(243, "病人排泄物和呕吐物", "病人排泄物和呕吐物"),
RONG_QI(244, "盛排泄物和呕吐物的容器", "盛排泄物和呕吐物的容器"),
CE_SUO(245, "厕所", "厕所"),
ROOM_AIR(246, "室内空气", "室内空气"),
WU_SHUI(247, "污水处理", "污水处理"),
LA_JI(248, "垃圾", "垃圾"),
CLOTH(249, "衣物", "衣物"),
CAN_JU(250, "餐(饮)具", "餐(饮)具"),
FOOD(251, "食物", "食物"),
THING(252, "物品、家具、玩具", "物品、家具、玩具"),
BOOK(253, "纸张、书报", "纸张、书报"),
BING_REN(254, "病人尸体", "病人尸体"),
ANIMAL_SHI_TI(255, "动物尸体", "动物尸体"),
YUN_SHU_TOOL(256, "运输工具", "运输工具"),
HAND_SKIN(257, "手和皮肤", "手和皮肤"),
// 自然灾害后灾区病媒生物监测和测评
NATURE_MONITOR(258, "灾区管理", "灾后管理"),
MIE_MONITOR(259, "病媒生物监测", "病媒生物监测"),
WORK_USE(260, "病媒生物防治工作实施及效果评价", "病媒生物防治工作实施及效果评价"),
MIE_MONITOR1(261, "蚊虫密度监测", "蚊虫密度监测"),
MIE_MONITOR2(262, "蝇类密度监测", "蝇类密度监测"),
MIE_MONITOR3(263, "鼠类密度监测", "鼠类密度监测"),
WORK_USE1(264, "实施杀虫、灭鼠工作的参考指标", "实施杀虫、灭鼠工作的参考指标"),
WORK_USE2(265, "杀虫、灭鼠效果的评价", "杀虫、灭鼠效果的评价"),
// 化学中毒常用解毒剂
OPEN_VIRUS(266, "解毒剂", "化学物中毒常用特效解毒剂"),
QING_VIRUS(267, "氰化物中毒解毒药", "氰化物中毒解毒药"),
JIN_SHU_VITUS(268, "金属与类金属中毒解毒药", "金属与类金属中毒解毒药"),
LIN_VIRUS(269, "有机磷农药中毒解毒剂", "有机磷农药中毒解毒剂"),
BEN_VIRUS(270, "苯胺、硝基苯类中毒解毒药", "苯胺、硝基苯类中毒解毒药"),
MOUSE_VIRUS(271, "鼠类及其他解毒剂", "鼠类及其他解毒剂"),
QING_VIRUS1(272, "亚硝酸异戊酯", "亚硝酸异戊酯"),
QING_VIRUS2(273, "亚硝酸钠", "亚硝酸钠"),
QING_VIRUS3(274, "硫代硫酸钠", "硫代硫酸钠"),
QING_VIRUS4(275, "4-二甲基苯酚(4-DMAP)", "4-二甲基苯酚(4-DMAP)"),
QING_VIRUS5(276, "对氨基苯丙酮(PAPP)", "对氨基苯丙酮(PAPP)"),
JIN_SHU_VITUS1(277, "依地酸二钠钙", "依地酸二钠钙"),
JIN_SHU_VITUS2(278, "基丙磺酸钠,解砷灵", "基丙磺酸钠,解砷灵"),
JIN_SHU_VITUS3(279, "二巯基丁二酸钠", "二巯基丁二酸钠"),
JIN_SHU_VITUS4(280, "二巯基丙醇", "二巯基丙醇"),
JIN_SHU_VITUS5(281, "促排灵(DTPA)", "促排灵(DTPA)"),
JIN_SHU_VITUS6(282, "巯乙胺", "巯乙胺"),
JIN_SHU_VITUS7(283, "巯丙甘", "巯丙甘"),
JIN_SHU_VITUS8(284, "青霉胺", "青霉胺"),
JIN_SHU_VITUS9(285, "普鲁士蓝", "普鲁士蓝"),
JIN_SHU_VITUS10(286, "硫酸钠,芒硝", "硫酸钠,芒硝"),
JIN_SHU_VITUS11(287, "喷替酸钙钠", "喷替酸钙钠"),
LIN_VIRUS1(288, "双复磷", "双复磷"),
LIN_VIRUS2(289, "氯解磷定", "氯解磷定"),
LIN_VIRUS3(290, "碘解磷定", "碘解磷定"),
BEN_VIRUS1(291, "美蓝", "美蓝"),
MOUSE_VIRUS1(292, "乙酰胺", "乙酰胺"),
MOUSE_VIRUS2(293, "维生素K1", "维生素K1"),
MOUSE_VIRUS3(294, "纳络酮", "纳络酮"),
// 疫苗免疫程序
KEEP_FUNCTION(295, "疫苗流程", "疫苗免疫程序"),
KEEP_FUNCTION1(296, "乙肝疫苗", "乙肝疫苗"),
KEEP_FUNCTION2(297, "卡介苗", "卡介苗"),
KEEP_FUNCTION3(298, "脊灰疫苗", "脊灰疫苗"),
KEEP_FUNCTION4(299, "百白破疫苗", "百白破疫苗"),
KEEP_FUNCTION5(300, "白破疫苗", "白破疫苗"),
KEEP_FUNCTION6(301, "麻风疫苗(麻疹疫苗)", "麻风疫苗(麻疹疫苗)"),
KEEP_FUNCTION7(302, "麻腮风疫苗(麻腮疫苗、麻疹疫苗)", "麻腮风疫苗(麻腮疫苗、麻疹疫苗)"),
KEEP_FUNCTION8(303, "乙脑减毒活疫苗", "乙脑减毒活疫苗"),
KEEP_FUNCTION9(304, "A群流脑疫苗", "A群流脑疫苗"),
KEEP_FUNCTION10(305, "A+C流脑疫苗", "A+C流脑疫苗"),
KEEP_FUNCTION11(306, "甲肝减毒活疫苗", "甲肝减毒活疫苗"),
KEEP_FUNCTION12(307, "出血热疫苗(双价)", "出血热疫苗(双价)"),
KEEP_FUNCTION13(308, "炭疽疫苗", "炭疽疫苗"),
KEEP_FUNCTION14(309, "钩体疫苗", "钩体疫苗"),
KEEP_FUNCTION15(310, "乙脑灭活疫苗", "乙脑灭活疫苗"),
KEEP_FUNCTION16(311, "甲肝灭活疫苗", "甲肝灭活疫苗"),
// 突发事件防护用品装备及使用目录
HIDDEN_EVENT(312, "防护装备", "突发事件防护用品装备及使用目录"),
MEI_QI_EVENT(313, "气体中毒防护", "突发煤气中毒事件"),
HU_XI(314, "呼吸道防护", "呼吸道防护用品配备标准及使用目录"),
CANG_DAO(315, "肠道传染病防护", "肠道传染病防护用品标准及使用说明"),
XIAN_CHANG(316, "生活保障物资", "现场应急队伍生活保障用品一线储备清单"),
HU_XI1(317, "一级防护标准", "一级防护标准"),
HU_XI2(318, "二级防护标准", "二级防护标准"),
HU_XI3(319, "三级防护标准", "三级防护标准"),
CANG_DAO1(320, "防护装备", "防护装备"),
CANG_DAO2(321, "使用说明", "使用说明"),
// 蚊类处理
WEN_CONTROL(322, "蚊类化学控制", "蚊类化学控制"),
WEN_CONTROL1(323, "蚊幼的化学防制", "蚊幼的化学防制"),
WEN_CONTROL2(324, "成蚊的化学控制", "成蚊的化学控制"),
WEN_CONTROL1_1(325, "蚊幼的化学防制", "蚊幼的化学防制"),
WEN_CONTROL1_2(326, "适合杀灭蚊虫幼虫的化学杀虫剂(WHO)", "适合杀灭蚊虫幼虫的化学杀虫剂(WHO)"),
WEN_CONTROL2_1(327, "室内常量喷洒", "室内常量喷洒"),
WEN_CONTROL2_2(328, "室内超低容量喷洒", "室内超低容量喷洒"),
WEN_CONTROL2_3(329, "外环境超低容量喷洒", "外环境超低容量喷洒"),
WEN_CONTROL2_4(330, "滞留处理", "滞留处理"),
WEN_CONTROL2_5(331, "可以用于室内滞留喷洒的化学杀虫剂(WHO)", "可以用于室内滞留喷洒的化学杀虫剂(WHO)"),
WEN_CONTROL2_6(332, "蚊帐浸泡", "蚊帐浸泡"),
WEN_CONTROL2_7(333, "处理不同织物的蚊帐所需要的杀虫剂的剂量(WHO)", "处理不同织物的蚊帐所需要的杀虫剂的剂量(WHO)"),
// 试剂
WEN_CONTROL1_2_1(334, "汽油", "汽油"),
WEN_CONTROL1_2_2(335, "柴油", "柴油"),
WEN_CONTROL1_2_3(336, "杀幼油", "杀幼油"),
WEN_CONTROL1_2_4(337, "巴黎绿", "巴黎绿"),
WEN_CONTROL1_2_5(338, "有机磷", "有机磷"),
WEN_CONTROL1_2_6(339, "昆虫生长调剂", "昆虫生长调剂"),
WEN_CONTROL1_2_5_1(340, "毒死蜱", "毒死蜱"),
WEN_CONTROL1_2_5_2(341, "杀螟松", "杀螟松"),
WEN_CONTROL1_2_5_3(342, "倍硫磷", "倍硫磷"),
WEN_CONTROL1_2_5_4(343, "碘硫磷", "碘硫磷"),
WEN_CONTROL1_2_5_5(344, "马拉硫磷", "马拉硫磷"),
WEN_CONTROL1_2_5_6(345, "甲嘧硫磷", "甲嘧硫磷"),
WEN_CONTROL1_2_5_7(346, "双硫磷", "双硫磷"),
WEN_CONTROL1_2_6_1(347, "灭幼脲", "灭幼脲"),
WEN_CONTROL1_2_6_2(348, "甲氧保幼激素", "甲氧保幼激素"),
WEN_CONTROL1_2_6_3(349, "蚊蝇醚", "蚊蝇醚"),
WEN_CONTROL2_5_1(350, "有机磷", "有机磷"),
WEN_CONTROL2_5_2(351, "氨基甲酸酯", "氨基甲酸酯"),
WEN_CONTROL2_5_3(352, "拟除虫菊酯", "拟除虫菊酯"),
WEN_CONTROL2_5_1_1(353, "马拉硫磷", "马拉硫磷"),
WEN_CONTROL2_5_1_2(354, "杀螟松", "杀螟松"),
WEN_CONTROL2_5_1_3(355, "甲嘧硫磷", "甲嘧硫磷"),
WEN_CONTROL2_5_2_1(356, "恶虫威", "恶虫威"),
WEN_CONTROL2_5_2_2(357, "残杀威", "残杀威"),
WEN_CONTROL2_5_3_1(358, "顺式氯氰菊酯", "顺式氯氰菊酯"),
WEN_CONTROL2_5_3_2(359, "氟氯氰菊酯", "氟氯氰菊酯"),
WEN_CONTROL2_5_3_3(360, "氯氰菊酯", "氯氰菊酯"),
WEN_CONTROL2_5_3_4(361, "三氟氯氰菊酯", "三氟氯氰菊酯"),
WEN_CONTROL2_5_3_5(362, "溴氰菊酯", "溴氰菊酯"),
WEN_CONTROL2_5_3_6(363, "二氯苯醚菊酯", "二氯苯醚菊酯"),
WEN_CONTROL2_7_1(364, "大孔网(大于2mm)", "大孔网(大于2mm)"),
WEN_CONTROL2_7_2(365, "标准蚊帐(1.5mm)", "标准蚊帐(1.5mm)"),
// new add
SHA_CHILD_CONG(373, "杀灭幼虫", "杀灭幼虫"),
CHENG_YING_KONG_ZHI(374, "成蝇控制", "成蝇控制"),
SHA_CHILD_CONG1(375, "常用灭蝇幼虫的杀虫剂", "常用灭蝇幼虫的杀虫剂"),
CHENG_YING_KONG_ZHI1(376, "滞留喷洒", "滞留喷洒"),
CHENG_YING_KONG_ZHI2(377, "空间喷雾", "空间喷雾"),
CHENG_YING_KONG_ZHI3(378, "毒饵灭蝇", "毒饵灭蝇"),
LINC_CHUANG_ZHENG_ZHUANG1(379, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG2(380, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG3(381, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG4(382, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG5(383, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG6(384, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG7(385, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG8(386, "临床症状", "临床症状"),
LINC_CHUANG_ZHENG_ZHUANG9(387, "临床症状", "临床症状"),
FUNCTION1(388, "诱蚊灯法", "诱蚊灯法"),
FUNCTION2(389, "人工小时法", "人工小时法"),
FUNCTION3(390, "粘蝇条(纸)法", "粘蝇条(纸)法"),
FUNCTION4(391, "目测法", "目测法"),
FUNCTION5(392, "毒饵盗食法", "毒饵盗食法"),
FUNCTION6(393, "鼠迹法", "鼠迹法"),
FUNCTION7(394, "鼠夹法", "鼠夹法"),
// 从临床症状入手寻找病因线索的步骤
REASON_STEP(405, "从临床症状寻找病因", "从临床症状入手寻找病因线索的步骤"),
QUICK_DISEASE(406, "急性感染性疾病可能性大",
"急性感染性疾病可能性大"),
QUICK_NO_DISEASE(407, "急性非感染性疾病可能性大",
"急性非感染性疾病可能性大"),
LIN_CHUANG_TE_ZHENG(408, "临床特征", "临床特征"),
QUICK_NO_DISEASE1(409, "急性非感染性疾病特征", "急性非感染性疾病特征"),
QUICK_NO_DISEASE2(410, "急性中毒可能性大", " 急性中毒可能性大"),
QUICK_NO_DISEASE3(411, "群体性心因性反应可能性大", "群体性心因性反应可能性大"),
QUICK_DISEASE1(412, "急性感染性疾病特征", "急性感染性疾病特征"),
QUICK_DISEASE2(413, "血常规", "血常规"),
QUICK_DISEASE3(414, "可能感染途径", "可能感染途径"),
QUICK_NO_DISEASE21(415, "急性中毒可能性临床现象", " 急性中毒可能性临床现象"),
QUICK_NO_DISEASE22(416, "可疑的致病毒物", " 可疑的致病毒物"),
QUICK_NO_DISEASE31(417, "群体性心因性反应临床现象", " 群体性心因性反应临床现象"),
QUICK_NO_DISEASE32(418, "群体性心因性反应时间的确定", " 群体性心因性反应时间的确定"),
// 自然灾害界面
THINGS_PREPARE_FLAG31(430, "呼吸道传染病防护用品", "呼吸道传染病防护用品"),
THINGS_PREPARE_FLAG32(431, "自然疫源性传染病防护用品", "自然疫源性传染病防护用品"),
THINGS_PREPARE_FLAG33(432, "台风洪涝灾害防护用品", "台风洪涝灾害防护用品"),
PEOPLE_DUTY(12306, "队员职责", "应急队员职责"),
} | 1 | null | 1 | 1 | fae631a1288c2f048fd48c29e4a22f1a89296281 | 18,939 | KownLegeRes | Apache License 2.0 |
uikit/src/main/java/com/sendbird/uikit/internal/ui/widgets/SingleMenuItemView.kt | sendbird | 350,188,329 | false | null | package com.sendbird.uikit.internal.ui.widgets
import android.content.Context
import android.content.res.ColorStateList
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import com.sendbird.uikit.R
import com.sendbird.uikit.SendbirdUIKit
import com.sendbird.uikit.consts.SingleMenuType
import com.sendbird.uikit.databinding.SbViewSingleMenuItemBinding
import com.sendbird.uikit.internal.extensions.setAppearance
import com.sendbird.uikit.utils.DrawableUtils
internal class SingleMenuItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {
val binding: SbViewSingleMenuItemBinding
val layout: View
get() = this
override fun setOnClickListener(listener: OnClickListener?) = binding.vgMenuItem.setOnClickListener(listener)
override fun setOnLongClickListener(listener: OnLongClickListener?) =
binding.vgMenuItem.setOnLongClickListener(listener)
fun setNextActionDrawable(@DrawableRes drawableResId: Int) = binding.ivNext.setImageResource(drawableResId)
fun setOnActionMenuClickListener(listener: OnClickListener) {
binding.scSwitch.setOnClickListener(listener)
binding.ivNext.setOnClickListener(listener)
}
fun setIcon(@DrawableRes resId: Int) = binding.ivIcon.setImageResource(resId)
fun setIconTint(@ColorRes tintResId: Int) {
binding.ivIcon.imageTintList = AppCompatResources.getColorStateList(binding.ivIcon.context, tintResId)
}
fun setIconTint(tint: ColorStateList) {
binding.ivIcon.imageTintList = tint
}
fun setName(name: String) {
binding.tvName.text = name
}
fun setChecked(checked: Boolean) {
binding.scSwitch.isChecked = checked
}
fun setMenuType(type: SingleMenuType) {
when (type) {
SingleMenuType.NEXT -> {
binding.scSwitch.visibility = GONE
binding.ivNext.visibility = VISIBLE
binding.tvDescription.visibility = VISIBLE
}
SingleMenuType.SWITCH -> {
binding.scSwitch.visibility = VISIBLE
binding.ivNext.visibility = GONE
binding.tvDescription.visibility = GONE
}
else -> {
binding.scSwitch.visibility = GONE
binding.ivNext.visibility = GONE
binding.tvDescription.visibility = GONE
}
}
}
fun setDescription(description: String) {
binding.tvDescription.text = description
}
fun setIconVisibility(visibility: Int) {
binding.ivIcon.visibility = visibility
}
init {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.SingleMenuItemView, defStyle, 0)
try {
binding = SbViewSingleMenuItemBinding.inflate(LayoutInflater.from(getContext()))
addView(binding.root, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
val itemBackground = a.getResourceId(
R.styleable.SingleMenuItemView_sb_menu_item_background,
R.drawable.selector_rectangle_light
)
val nicknameAppearance = a.getResourceId(
R.styleable.SingleMenuItemView_sb_menu_item_name_appearance,
R.style.SendbirdSubtitle2OnLight01
)
val descriptionAppearance = a.getResourceId(
R.styleable.SingleMenuItemView_sb_menu_item_description_appearance,
R.style.SendbirdSubtitle2OnLight02
)
val iconTintRes = a.getColorStateList(R.styleable.SingleMenuItemView_sb_menu_item_icon_tint)
val type = a.getInteger(R.styleable.SingleMenuItemView_sb_menu_item_type, 0)
binding.tvName.setAppearance(context, nicknameAppearance)
binding.tvName.ellipsize = TextUtils.TruncateAt.END
binding.tvName.maxLines = 1
binding.tvDescription.setAppearance(context, descriptionAppearance)
binding.vgMenuItem.setBackgroundResource(itemBackground)
val useDarkTheme = SendbirdUIKit.isDarkMode()
val nextTint = if (useDarkTheme) R.color.ondark_text_high_emphasis else R.color.onlight_text_high_emphasis
val divider = if (useDarkTheme) R.drawable.sb_line_divider_dark else R.drawable.sb_line_divider_light
val switchTrackTint = if (useDarkTheme) R.color.sb_switch_track_dark else R.color.sb_switch_track_light
val switchThumbTint = if (useDarkTheme) R.color.sb_switch_thumb_dark else R.color.sb_switch_thumb_light
binding.divider.setBackgroundResource(divider)
iconTintRes?.let { setIconTint(it) }
val nextResId = a.getResourceId(
R.styleable.SingleMenuItemView_sb_menu_item_action_drawable,
R.drawable.icon_chevron_right
)
binding.ivNext.setImageResource(nextResId)
binding.ivNext.setImageDrawable(
DrawableUtils.setTintList(
binding.ivNext.drawable,
AppCompatResources.getColorStateList(context, nextTint)
)
)
binding.scSwitch.trackTintList = AppCompatResources.getColorStateList(context, switchTrackTint)
binding.scSwitch.thumbTintList = AppCompatResources.getColorStateList(context, switchThumbTint)
setMenuType(SingleMenuType.from(type))
layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
height = context.resources.getDimensionPixelSize(R.dimen.sb_size_56)
}
} finally {
a.recycle()
}
}
companion object {
@JvmStatic
fun createMenuView(
context: Context,
title: String,
description: String?,
type: SingleMenuType,
@DrawableRes iconResId: Int,
@ColorRes iconTintResId: Int
): View {
return SingleMenuItemView(context).apply {
setName(title)
setMenuType(type)
description?.let { setDescription(it) }
if (iconResId != 0) {
setIcon(iconResId)
setIconVisibility(VISIBLE)
} else {
setIconVisibility(GONE)
}
if (iconTintResId != 0) {
setIconTint(AppCompatResources.getColorStateList(context, iconTintResId))
}
}
}
}
}
| 1 | null | 43 | 39 | 93f1b979a862a260d0e58ae9024105c38d1e7e63 | 6,895 | sendbird-uikit-android | MIT License |
infobip-rtc-ui/src/main/java/com/infobip/webrtc/ui/InfobipRtcUi.kt | infobip | 56,227,769 | false | {"Java": 1840765, "Kotlin": 396033, "HTML": 8111, "Shell": 2447} | package com.infobip.webrtc.ui
import android.Manifest
import android.app.Activity
import android.content.Context
import android.util.Log
import com.infobip.webrtc.ui.internal.core.Injector
import com.infobip.webrtc.ui.internal.core.TAG
import com.infobip.webrtc.ui.internal.model.RtcUiMode
import com.infobip.webrtc.ui.model.InCallButton
import com.infobip.webrtc.ui.model.ListenType
import com.infobip.webrtc.ui.model.RtcUiError
import com.infobip.webrtc.ui.view.styles.InfobipRtcUiTheme
import org.infobip.mobile.messaging.util.ResourceLoader
import java.util.Locale
/**
* [InfobipRtcUi] is an easy to use library, that allows you to connect to [Infobip RTC](https://github.com/infobip/infobip-rtc-android) by just building library.
*
* This assumes, though, that the initial setups of [Mobile Push Notifications](https://github.com/infobip/mobile-messaging-sdk-android/blob/master/README.md) and the [Infobip RTC](https://www.infobip.com/docs/voice-and-video/webrtc#getstartedwith-rtc-sdk) are set in both, your account and your mobile app profile.
* [InfobipRtcUi] takes care of everything: the registration of your device (in order to receive and trigger calls), the handle of the calls themselves, and offers you a powerful user interface with all the features your customer may need: ability to capture video through both, front and back camera, option to mute and use the speaker, ability to capture and share the screen of your mobile device, option to minimise the call UI in a picture-on-picture mode, and more.
* [InfobipRtcUi] also allows you to take control in any step of the flow, if you wish or need so, you can become a delegate for the FirebaseMessagingService or use your own custom user interface to handle the calls, it is up to you.
*/
interface InfobipRtcUi {
class Builder(private val context: Context) {
/**
* Defines Infobip [WebRTC configuration ID](https://www.infobip.com/docs/api/channels/webrtc-calls/webrtc/save-push-configuration) to use.
*
* @param id configuration id
* It is mandatory parameter. Can be provided also as string resource, builder provided ID has precedent over ID provided in resources.
* ```
* <resources>
* <string name="infobip_webrtc_configuration_id">WEBRTC CONFIGURATION ID</string>
* ...
* </resources>
* ```
*/
fun withConfigurationId(id: String) = apply {
Injector.cache.configurationId = id
}
/**
* Defines custom activity class to handle call UI.
*
* @param clazz custom activity class handling call UI
* @return [InfobipRtcUi.Builder]
*/
fun withCustomActivity(clazz: Class<out Activity>) = apply {
Injector.cache.activityClass = clazz
}
/**
* Set whether incoming InfobipRtcUi call should be declined in case of missing [Manifest.permission.POST_NOTIFICATIONS] permission. Default value is true.
*
* @param decline true if call is automatically declined, false otherwise
* @return [InfobipRtcUi.Builder]
*/
fun withAutoDeclineOnMissingNotificationPermission(decline: Boolean) = apply {
Injector.cache.autoDeclineOnMissingNotificationPermission = decline
}
/**
* Set whether incoming InfobipRtcUi call should be declined in case of missing [Manifest.permission.READ_PHONE_STATE] permission. Default value is false.
*
* Default value ensures to not miss first call ever. [Manifest.permission.READ_PHONE_STATE] permission is required only on Android 12 (API 31)
* and higher and it is requested in runtime by InfobipRtcUi library once call UI appears. Your application can request the permission, ensures is granted and set the value to true.
*
* @param decline true if call is automatically declined, false otherwise
* @return [InfobipRtcUi.Builder]
*/
fun withAutoDeclineOnMissingReadPhoneStatePermission(decline: Boolean) = apply {
Injector.cache.autoDeclineOnMissingReadPhoneStatePermission = decline
}
/**
* Set whether incoming InfobipRtcUi call should be declined when there is ringing or ongoing cellular call. Default value is true.
*
* Default value ensures to not miss first call ever. [Manifest.permission.READ_PHONE_STATE] permission is required only on Android 12 (API 31)
* and higher and it is requested in runtime by InfobipRtcUi library once call UI appears. Your application can request the permission, ensures is granted and set the value to true.
*
* @param decline true if call is automatically declined, false otherwise
* @return [InfobipRtcUi.Builder]
*/
fun withAutoDeclineWhenOngoingCellularCall(decline: Boolean) = apply {
Injector.cache.autoDeclineWhenOngoingCellularCall = decline
}
/**
* Set whether ongoing InfobipRtcUi call should be finished when incoming cellular call is accepted. Default value is true.
*
* On Android 12 (API 31) and higher, the setting is ignored if [Manifest.permission.READ_PHONE_STATE] permission is not granted.
* [Manifest.permission.READ_PHONE_STATE] permission is requested in runtime by InfobipRtcUi library once call UI appears.
*
* @param finish true if call is automatically declined, false otherwise
* @return [InfobipRtcUi.Builder]
*/
fun withAutoFinishWhenIncomingCellularCallAccepted(finish: Boolean) = apply {
Injector.cache.autoFinishWhenIncomingCellularCallAccepted = finish
}
/**
* Enables incoming calls for InAppChat. Calls are not enabled immediately, it is waiting for InAppChat to provide livechatRegistrationId what is used as identity, listenType is PUSH.
* If successListener is not provided, default null is used.
* If errorListener is not provided, default null is used.
*
* @param successListener callback triggered when incoming calls are subscribed
* @param errorListener callback triggered when incoming calls subscribe action failed
* @return [InfobipRtcUi.Builder]
*/
@JvmOverloads
fun withInAppChatCalls(
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
): BuilderFinalStep = BuilderFinalStepImpl(
context,
RtcUiMode.IN_APP_CHAT.withListeners(successListener, errorListener)
)
/**
* Enables incoming calls where internally managed pushRegistrationId is used as identity, listenType is PUSH.
* If successListener is not provided, default null is used.
* If errorListener is not provided, default null is used.
*
* @param successListener callback triggered when incoming calls are subscribed
* @param errorListener callback triggered when incoming calls subscribe action failed
*/
@JvmOverloads
fun withCalls(
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
): BuilderFinalStep = BuilderFinalStepImpl(
context,
RtcUiMode.DEFAULT.withListeners(successListener, errorListener)
)
/**
* Enables incoming calls for provided identity and listenType.
* If listenType is not provided, default ListenType.PUSH is used.
* If successListener is not provided, default null is used.
* If errorListener is not provided, default null is used.
*
* @param identity WebRTC identity
* @param listenType WebRTC listenType
* @param successListener callback triggered when incoming calls are subscribed
* @param errorListener callback triggered when incoming calls subscribe action failed
*/
@JvmOverloads
fun withCalls(
identity: String,
listenType: ListenType = ListenType.PUSH,
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
): BuilderFinalStep = BuilderFinalStepImpl(
context,
RtcUiMode.CUSTOM.withListeners(successListener, errorListener),
identity,
listenType
)
/**
* Creates [InfobipRtcUi] SDK instance.
*
* @return [InfobipRtcUi] instance
*/
fun build(): InfobipRtcUi {
return BuilderFinalStepImpl(context).build()
}
}
interface BuilderFinalStep {
/**
* Creates [InfobipRtcUi] SDK instance.
*
* @return [InfobipRtcUi] instance
*/
fun build(): InfobipRtcUi
}
private class BuilderFinalStepImpl(
private val context: Context,
private val rtcUiMode: RtcUiMode? = null,
private val identity: String? = null,
private val listenType: ListenType? = null
) : BuilderFinalStep {
override fun build(): InfobipRtcUi {
return getInstance(context).also { sdk ->
this.rtcUiMode?.let { mode ->
val defaultSuccessListener = SuccessListener { Log.d(TAG, "$mode calls enabled.") }
val defaultErrorListener = ErrorListener { Log.d(TAG, "Failed to enabled $mode calls.", it) }
when (mode) {
RtcUiMode.CUSTOM -> {
this.identity?.let { identity ->
this.listenType?.let { listenType ->
sdk.enableCalls(
identity = identity,
listenType = listenType,
successListener = mode.successListener ?: defaultSuccessListener,
errorListener = mode.errorListener ?: defaultErrorListener
)
}
}
}
RtcUiMode.DEFAULT -> sdk.enableCalls(
successListener = mode.successListener ?: defaultSuccessListener,
errorListener = mode.errorListener ?: defaultErrorListener
)
RtcUiMode.IN_APP_CHAT -> sdk.enableInAppChatCalls(
successListener = mode.successListener ?: defaultSuccessListener,
errorListener = mode.errorListener ?: defaultErrorListener
)
}
}
}
}
}
companion object {
/**
* Provides [InfobipRtcUi] SDK instance.
*
* @return [InfobipRtcUi] instance
*/
@JvmStatic
fun getInstance(context: Context): InfobipRtcUi {
val sdk = Injector.getWebrtcUi(context)
if (Injector.cache.configurationId.isBlank()) {
getWebRtcPushConfigurationIdFromResources(context)?.let {
Injector.cache.configurationId = it
}
}
validateMobileMessagingApplicationCode()
validateWebRtcPushConfigurationId()
return sdk
}
private fun getWebRtcPushConfigurationIdFromResources(context: Context): String? {
val resource = ResourceLoader.loadResourceByName(
context,
"string",
"infobip_webrtc_configuration_id"
)
return if (resource > 0) {
context.resources.getString(resource)
} else null
}
private fun validateMobileMessagingApplicationCode() {
if (Injector.appCodeDelegate.getApplicationCode().isNullOrBlank())
throw IllegalArgumentException("Application code is not provided to MobileMessaging library, make sure it is available in resources or Mobile Messaging SDK builder.")
}
private fun validateWebRtcPushConfigurationId() {
if (Injector.cache.configurationId.isBlank())
throw IllegalArgumentException("Webrtc push configuration ID is not provided to InfobipRtcUi library, make sure it is available in resources or InfobipRtcUi SDK builder.")
}
}
/**
* Disables incoming calls.
*
* @param successListener callback triggered when incoming calls are unsubscribed
* @param errorListener callback triggered when incoming calls unsubscribe action failed
*/
fun disableCalls(
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
)
/**
* Enables incoming calls for InAppChat. Calls are not enabled immediately, it is waiting for InAppChat to provide livechatRegistrationId what is used as identity, listenType is PUSH.
* If successListener is not provided, default null is used.
* If errorListener is not provided, default null is used.
*
* @param successListener callback triggered when incoming calls are subscribed
* @param errorListener callback triggered when incoming calls subscribe action failed
* @return [InfobipRtcUi.Builder]
*/
fun enableInAppChatCalls(
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
)
/**
* Enables incoming calls where internally managed pushRegistrationId is used as identity, listenType is PUSH.
* If successListener is not provided, default null is used.
* If errorListener is not provided, default null is used.
*
* @param successListener callback triggered when incoming calls are subscribed
* @param errorListener callback triggered when incoming calls subscribe action failed
*/
fun enableCalls(
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
)
/**
* Enables incoming calls for provided identity and listenType.
* If listenType is not provided, default ListenType.PUSH is used.
* If successListener is not provided, default null is used.
* If errorListener is not provided, default null is used.
*
* @param identity WebRTC identity
* @param listenType WebRTC listenType
* @param successListener callback triggered when incoming calls are subscribed
* @param errorListener callback triggered when incoming calls subscribe action failed
*/
fun enableCalls(
identity: String,
listenType: ListenType = ListenType.PUSH,
successListener: SuccessListener? = null,
errorListener: ErrorListener? = null
)
/**
* Sets the UI language. Call's UI must be recreated to apply new language.
*
* @param locale new locale to be set
*/
fun setLanguage(locale: Locale)
/**
* Sets bottom sheet buttons in call screen. First three buttons are in visible area (+ hang-up button is fixed on first place.)
* All another buttons are place in draggable area.
*
* @param buttons sorted set of in call buttons
*/
fun setInCallButtons(buttons: List<InCallButton>)
/**
* Set theme, it is alternative to defining style in xml.
*
* Final value for every theme attribute is resolved from multiple source-by-source priority.
* The source with the highest priority defines a final attribute value.
* If source does not define an attribute value, there is fallback to the source with lower priority.
*
* Sources by priority:
* 1. [InfobipRtcUiTheme] theme provided in runtime using this function.
* 2. [InfobipRtcUi] style provided in xml.
* 3. Default [InfobipRtcUi] style defined by InfobipRtcUi library
*
* Final value for every theme attribute is evaluated separately.
* It means you can define [InfobipRtcUiTheme.incomingCallMessageStyle] in runtime, colors in xml and skip icons.
* Library will use [InfobipRtcUiTheme.incomingCallMessageStyle] you defined in runtime, colors you defined in xml and default icons provided by library itself.
*
* @param theme data object holding all theme attributes
*/
fun setTheme(theme: InfobipRtcUiTheme)
/**
* Set custom error mapper which allows you to control what message is displayed to the user when certain error appears.
* InfobipRtcUi library uses default localised messages when mapper is not set.
*
* You can find all possible error codes defined by InfobipRtcUi library in [RtcUiError] class plus there
* are general WebRTC errors defined in Infobip WebRTC [documentation](https://www.infobip.com/docs/essentials/response-status-and-error-codes#webrtc-error-codes).
*
* @param errorMapper mapper to be used by InfobipRtcUi library
*/
fun setErrorMapper(errorMapper: RtcUiCallErrorMapper)
} | 6 | Java | 17 | 51 | 3fd34f50d810fb21108a0aebc08fdd4b4d8ef99e | 17,134 | mobile-messaging-sdk-android | Apache License 2.0 |
detekt-generator/src/test/kotlin/io/gitlab/arturbosch/detekt/generator/printer/RuleSetPagePrinterSpec.kt | mlegy | 121,956,975 | true | {"Gradle": 12, "YAML": 37, "INI": 2, "Markdown": 111, "Shell": 8, "Text": 4, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "XML": 5, "Groovy": 1, "Kotlin": 494, "Gemfile.lock": 1, "HTML": 45, "Dockerfile": 1, "JSON": 2, "Ruby": 1, "SVG": 4, "CSS": 9, "JavaScript": 6, "Java": 3} | package io.gitlab.arturbosch.detekt.generator.printer
import io.gitlab.arturbosch.detekt.generator.printer.rulesetpage.RuleSetPagePrinter
import io.gitlab.arturbosch.detekt.generator.util.createRuleSetPage
import io.gitlab.arturbosch.detekt.test.resource
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import java.io.File
class RuleSetPagePrinterSpec : Spek({
given("a config to print") {
it("prints the correct markdown format") {
val markdownString = RuleSetPagePrinter.print(createRuleSetPage())
val expectedMarkdownString = File(resource("/RuleSet.md")).readText()
assertThat(markdownString).isEqualTo(expectedMarkdownString)
}
}
})
| 3 | Kotlin | 0 | 1 | c37812e0b8af0ec304fcefce5152dfc9845d52c8 | 771 | detekt | Apache License 2.0 |
app/src/main/java/com/yourssu/notissu/model/NoticeDetail.kt | islandparadise14 | 227,648,327 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 77, "XML": 42, "Java": 2, "JSON": 1} | package com.yourssu.notissu.model
class NoticeDetail(val htmlText: String, val fileList: ArrayList<File>) | 0 | Kotlin | 1 | 5 | c7891a2aa82af0281ba0f29675446b1be2bf0bcd | 106 | Notissu | Apache License 2.0 |
agp-7.1.0-alpha01/tools/base/build-system/integration-test/application/src/test/java/com/android/build/gradle/integration/attribution/BuildAttributionDataTest.kt | jomof | 502,039,754 | true | {"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 2} | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.integration.attribution
import com.android.build.gradle.integration.common.fixture.BaseGradleExecutor
import com.android.build.gradle.integration.common.fixture.GradleTestProject
import com.android.build.gradle.integration.common.fixture.app.HelloWorldApp
import com.android.build.gradle.integration.common.utils.TestFileUtils
import com.android.build.gradle.options.StringOption
import com.android.ide.common.attribution.AndroidGradlePluginAttributionData
import com.android.utils.FileUtils
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class BuildAttributionDataTest(private val configCachingMode: BaseGradleExecutor.ConfigurationCaching) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun configCachingModes(): List<BaseGradleExecutor.ConfigurationCaching> {
return listOf(BaseGradleExecutor.ConfigurationCaching.ON,
BaseGradleExecutor.ConfigurationCaching.OFF)
}
}
@get:Rule
val temporaryFolder = TemporaryFolder()
@get:Rule
var project = GradleTestProject.builder()
.fromTestApp(HelloWorldApp.forPlugin("com.android.application"))
.withConfigurationCaching(configCachingMode)
.create()
private fun setUpProject() {
TestFileUtils.appendToFile(project.buildFile, """
abstract class SampleTask extends DefaultTask {
@OutputDirectory
abstract DirectoryProperty getOutputDir()
@TaskAction
def run() {
// do nothing
}
}
task sample1(type: SampleTask) {
outputDir = file("${"$"}buildDir/outputs/shared_output")
}
task sample2(type: SampleTask) {
outputDir = file("${"$"}buildDir/outputs/shared_output")
}
afterEvaluate { project ->
android.applicationVariants.all { variant ->
def mergeResourcesTask = tasks.getByPath("merge${"$"}{variant.name.capitalize()}Resources")
mergeResourcesTask.dependsOn sample1
mergeResourcesTask.dependsOn sample2
}
sample2.dependsOn sample1
}
""".trimIndent())
}
@Test
fun testBuildAttributionReport() {
setUpProject()
val attributionFileLocation = temporaryFolder.newFolder()
project.executor()
.with(StringOption.IDE_ATTRIBUTION_FILE_LOCATION,
attributionFileLocation.absolutePath)
.run("mergeDebugResources")
val originalAttributionData =
AndroidGradlePluginAttributionData.load(attributionFileLocation)!!
assertThat(originalAttributionData.taskNameToClassNameMap).isNotEmpty()
assertThat(originalAttributionData.tasksSharingOutput).isNotEmpty()
// delete the report and re-run
FileUtils.deleteDirectoryContents(attributionFileLocation)
project.executor()
.with(StringOption.IDE_ATTRIBUTION_FILE_LOCATION,
attributionFileLocation.absolutePath)
.run("mergeDebugResources")
val newAttributionData =
AndroidGradlePluginAttributionData.load(attributionFileLocation)!!
assertThat(newAttributionData.taskNameToClassNameMap).containsExactlyEntriesIn(
originalAttributionData.taskNameToClassNameMap)
assertThat(newAttributionData.tasksSharingOutput).containsExactlyEntriesIn(
originalAttributionData.tasksSharingOutput)
}
}
| 1 | null | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 4,458 | CppBuildCacheWorkInProgress | Apache License 2.0 |
kotlin/src/test/kotlin/com/spoonacular/client/model/SearchCustomFoods200ResponseCustomFoodsInnerTest.kt | valpackett | 787,267,296 | true | {"Markdown": 1853, "PowerShell": 1, "Go": 164, "Shell": 20, "Perl": 310, "Haskell": 23, "C#": 321, "PHP": 310, "JavaScript": 306, "Ruby": 313, "TypeScript": 328, "Batchfile": 2, "Java": 486, "INI": 4, "Scala": 1, "Python": 315, "C++": 316, "CMake": 1, "Rust": 156, "Lua": 305, "Kotlin": 321} | /**
*
* 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.spoonacular.client.model
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import com.spoonacular.client.model.SearchCustomFoods200ResponseCustomFoodsInner
class SearchCustomFoods200ResponseCustomFoodsInnerTest : ShouldSpec() {
init {
// uncomment below to create an instance of SearchCustomFoods200ResponseCustomFoodsInner
//val modelInstance = SearchCustomFoods200ResponseCustomFoodsInner()
// to test the property `id`
should("test id") {
// uncomment below to test the property
//modelInstance.id shouldBe ("TODO")
}
// to test the property `title`
should("test title") {
// uncomment below to test the property
//modelInstance.title shouldBe ("TODO")
}
// to test the property `servings`
should("test servings") {
// uncomment below to test the property
//modelInstance.servings shouldBe ("TODO")
}
// to test the property `imageUrl`
should("test imageUrl") {
// uncomment below to test the property
//modelInstance.imageUrl shouldBe ("TODO")
}
// to test the property `price`
should("test price") {
// uncomment below to test the property
//modelInstance.price shouldBe ("TODO")
}
}
}
| 0 | Java | 0 | 0 | b961f48275936e1daa8a8197d09b870b73da44df | 1,666 | spoonacular-api-clients | MIT License |
src/main/kotlin/com/github/w0819/plugin/UHCPlugin.kt | w0819 | 418,112,809 | false | null | package com.github.w0819.plugin
import com.github.w0819.enchant.AddDamage
import com.github.w0819.enchant.ReviveToken
import com.github.w0819.event.ItemEvent
import com.github.w0819.event.ModifierEvent
import com.github.w0819.event.SystemEvent
import com.github.w0819.game.UHCGame
import com.github.w0819.game.timer.StartAction
import com.github.w0819.game.timer.StartActionType
import com.github.w0819.game.util.ConfigUtil
import com.github.w0819.game.util.PlayerData
import com.github.w0819.game.util.Util
import com.github.w0819.game.util.uhc.UHC
import com.github.w0819.game.util.uhc.UHCKit
import com.github.w0819.game.util.uhc.UHCModifier
import com.github.w0819.game.util.uhc.UHCRecipe
import io.github.monun.kommand.getValue
import io.github.monun.kommand.kommand
import org.bukkit.Bukkit
import org.bukkit.World.Environment
import org.bukkit.entity.Player
import org.bukkit.plugin.java.JavaPlugin
import java.util.*
class UHCPlugin : JavaPlugin() {
companion object {
@JvmStatic
val games = mutableListOf<UHCGame>()
@JvmStatic
lateinit var game: UHCGame
private set
@JvmStatic
private val isGameInitialized: Boolean
get() = ::game.isInitialized
@JvmStatic
lateinit var instance: UHCPlugin
private set
@JvmStatic
val UHCList = ArrayList<UHC>()
@JvmStatic
val recipeList = { UHCList.filterIsInstance<UHCRecipe>() }
@JvmStatic
val modifierList = { UHCList.filterIsInstance<UHCModifier>() }
@JvmStatic
val kitList = { UHCList.filterIsInstance<UHCKit>() }
@JvmStatic
val PlayersUHC = HashMap<UUID, PlayerData>()
@JvmStatic
val itemList = { UHCList.filterIsInstance<UHCRecipe.Item>() }
}
override fun onEnable() {
// config 셋업
saveDefaultConfig()
ConfigUtil.config = config
// UHCList 에 모든 UHC 클래스를 불러온다
UHCList.addAll(UHC.load("com.github.w0819.game.uhc"))
println("load end")
// UHCRecipe 를 모두 등록
recipeList().forEach { it.register() }
// static 객체 설정
instance = this
server.logger.info("UHC_System is enabled")
// 이벤트 리스너 등록
server.pluginManager.apply {
registerEvents(SystemEvent(), this@UHCPlugin)
registerEvents(ItemEvent(),this@UHCPlugin)
registerEvents(ModifierEvent(),this@UHCPlugin)
}
// 게임 객체 생성
game = UHCGame.create(listOf())
// 기존에 접속해 있던 모든 플레이어들을 게임에 참가 시킴
Bukkit.getOnlinePlayers().forEach { player ->
game.addPlayer(player)
}
// 명령어
kommand {
register("uhc") {
then("start") {
executes {
startAll()
}
then("teamGame" to bool()) {
executes {
val teamGame : Boolean by it
startAll(teamGame)
}
}
}
then("kick" to player()) {
executes {
// 플레이어를 내보낸다
val kick: Player by it
game.removePlayer(kick)
}
}
requires { isOp }
then("stop") {
executes {
stopAll()
}
}
then("exit") {
executes {
player.sendMessage("wait 3 second for exit the game")
player.sendMessage("""or you won't,chat "/exit" """)
val runnable = Runnable {
Thread.sleep(3_000)
Util.playerGame(player)?.players?.minus(player)
val world = server.getWorld("world")
player.teleport((world?.spawnLocation ?: return@Runnable))
}
val thread = Thread(runnable,"$player exit")
if (thread in Thread.getAllStackTraces()) thread.interrupt() else thread.start()
}
}
}
}
// 인챈트 등록
AddDamage.register()
ReviveToken.register()
println(UHCList)
}
override fun onDisable() {
// UHC Data 저장
ConfigUtil.savePlayers(Bukkit.getOnlinePlayers().toList())
}
/**
* 게임을 시작한다
* @param teamGame 팀전일 경우 true, 개인전일 경우 false. 기본값은 false이다
*/
private fun startAll(teamGame: Boolean = false) {
// game 객체가 초기화되지 않았을때 오류 발생을 알림
if (!isGameInitialized) {
server.logger.severe("***The game hasn't been initialized. Please restart the server***")
server.logger.severe("This is most likely to be a bug, please add an issue here - https://github.com/w0819/UHC_System")
return
}
// UHCList 를 다시 불러온다
UHCList.apply {
removeAll(this.toSet())
addAll(UHC.load("com.github.w0819.game.uhc"))
}
// 플레이어 정보를 불러온다
ConfigUtil.loadPlayers(config, game.players)
// 시드 정보 로깅
game.uhcWorld.returnSeed().forEach {
println("UHC's ${it.first.environment.resolve()} seed is ${it.second}")
}
// 게임 시작 함수 호출
game.startGame(teamGame, StartAction(StartActionType.COUNTDOWN, 5))
}
// 게임을 멈춘다
private fun stopAll() {
ConfigUtil.savePlayers(Bukkit.getOnlinePlayers().toList())
game.stopGame()
}
/**
* Environment to vanilla world type
* @return Vanilla world type
*/
private fun Environment.resolve(): String {
return when (this) {
Environment.NORMAL -> "overworld"
Environment.NETHER -> "nether"
Environment.THE_END -> "end"
Environment.CUSTOM -> "custom"
}
}
}
| 0 | null | 2 | 3 | d3aa47c6be6330a10e6689ff89f161eccee25563 | 6,072 | UHC_System | MIT License |
ui/components/widgets/android/src/main/kotlin/com/github/wykopmobilny/ui/components/LinkVoteButton.kt | otwarty-wykop-mobilny | 374,160,630 | true | {"Kotlin": 1326147, "HTML": 66896, "Java": 38599} | package com.github.wykopmobilny.ui.components
import android.content.Context
import android.graphics.drawable.RippleDrawable
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import com.github.wykopmobilny.ui.components.utils.readColorAttr
import io.github.wykopmobilny.ui.components.widgets.TwoActionsCounterUi
import io.github.wykopmobilny.ui.components.widgets.android.R
import io.github.wykopmobilny.ui.components.widgets.android.databinding.ViewLinkVoteButtonBinding
import io.github.wykopmobilny.utils.bindings.setOnClick
import io.github.wykopmobilny.utils.bindings.toColorInt
class LinkVoteButton(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
init {
inflate(context, R.layout.view_link_vote_button, this)
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setBackgroundResource(R.drawable.ripple_outline)
}
}
fun LinkVoteButton.bind(value: TwoActionsCounterUi) {
val binding = ViewLinkVoteButtonBinding.bind(this)
val stroke = value.color?.toColorInt(context) ?: context.readColorAttr(R.attr.colorOutline)
val color = value.color?.toColorInt(context) ?: context.readColorAttr(R.attr.colorControlNormal)
(background.mutate() as RippleDrawable).getDrawable(1).mutate().setTintList(stroke)
binding.txtCount.text = value.count.toString()
binding.txtCount.setTextColor(color)
binding.imgVoteUp.imageTintList = color
binding.imgVoteUp.isEnabled = value.upvoteAction != null
binding.imgVoteUp.setOnClick(value.upvoteAction)
binding.imgVoteDown.imageTintList = color
binding.imgVoteDown.isEnabled = value.downvoteAction != null
binding.imgVoteDown.setOnClick(value.downvoteAction)
}
| 7 | Kotlin | 4 | 47 | 85b54b736f5fbcd6f62305779ed7ae2085c3b136 | 1,757 | wykop-android | MIT License |
app/src/main/java/org/covidwatch/android/ui/onboarding/OnboardingFragment.kt | covidwatchorg | 261,834,815 | false | null | package org.covidwatch.android.ui.onboarding
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import org.covidwatch.android.R
import org.covidwatch.android.databinding.FragmentOnboardingBinding
import org.covidwatch.android.ui.BaseFragment
class OnboardingFragment : BaseFragment<FragmentOnboardingBinding>() {
private lateinit var pagerAdapter: OnboardingPagerAdapter
private var isFirstPage = true
private var isLastPage = false
private val args: OnboardingFragmentArgs by navArgs()
private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
isLastPage = position == pagerAdapter.itemCount - 1
isFirstPage = position == 0
updateActionLayout()
}
}
private fun updateActionLayout() {
binding.btnPreviousOnboardingScreen.visibility =
if (isFirstPage) View.INVISIBLE else View.VISIBLE
binding.onboardingPageIndicator.isVisible = !isLastPage
binding.continueSetupButton.isVisible = isLastPage
}
override fun bind(
inflater: LayoutInflater,
container: ViewGroup?
): FragmentOnboardingBinding = FragmentOnboardingBinding.inflate(inflater, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pagerAdapter = OnboardingPagerAdapter(this)
updateActionLayout()
with(binding) {
viewPager.adapter = pagerAdapter
viewPager.registerOnPageChangeCallback(onPageChangeCallback)
TabLayoutMediator(tabLayout, viewPager) { _, _ -> }.attach()
btnPreviousOnboardingScreen.setOnClickListener {
viewPager.currentItem = tabLayout.selectedTabPosition - 1
}
btnNextOnboardingScreen.setOnClickListener {
viewPager.currentItem = tabLayout.selectedTabPosition + 1
}
if (args.onboarding) {
continueSetupButton.setText(R.string.continue_setup_button)
continueSetupButton.setOnClickListener {
// Remove previous onboarding fragments from the stack so we can't go back.
findNavController().popBackStack(R.id.homeFragment, false)
findNavController().navigate(R.id.enableExposureNotificationsFragment)
}
} else {
continueSetupButton.setText(R.string.button_finish)
continueSetupButton.setOnClickListener {
findNavController().popBackStack(R.id.homeFragment, false)
}
}
}
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (isFirstPage) {
findNavController().popBackStack()
} else {
binding.viewPager.currentItem = binding.tabLayout.selectedTabPosition - 1
}
}
})
}
override fun onDestroyView() {
binding.viewPager.unregisterOnPageChangeCallback(onPageChangeCallback)
super.onDestroyView()
}
} | 11 | Kotlin | 7 | 11 | a9d6fe16427f131fb8e5a5044db34cedb760c56e | 3,744 | covidwatch-android-en | Apache License 2.0 |
web/src/main/kotlin/top/bettercode/summer/web/support/packagescan/AssignableToPackageScanFilter.kt | top-bettercode | 387,652,015 | false | {"Kotlin": 2855099, "Java": 23656, "JavaScript": 22541, "CSS": 22336, "HTML": 16703} | package top.bettercode.summer.web.support.packagescan
/**
* Package scan filter for testing if a given class is assignable to another class.
*/
class AssignableToPackageScanFilter : PackageScanFilter {
private val parents: MutableSet<Class<*>> = HashSet()
constructor()
constructor(parentType: Class<*>) {
parents.add(parentType)
}
constructor(parents: Set<Class<*>>?) {
this.parents.addAll(parents!!)
}
fun addParentType(parentType: Class<*>) {
parents.add(parentType)
}
override fun matches(type: Class<*>): Boolean {
if (parents.size > 0) {
for (parent in parents) {
if (parent.isAssignableFrom(type) && parent != type) {
return true
}
}
}
return false
}
override fun toString(): String {
val sb = StringBuilder()
for (parent in parents) {
sb.append(parent.simpleName).append(", ")
}
sb.setLength(if (sb.isNotEmpty()) sb.length - 2 else 0)
return "is assignable to $sb"
}
}
| 0 | Kotlin | 0 | 1 | 04051941ce35156c6e571b74c89bd55b2b3132a7 | 1,109 | summer | Apache License 2.0 |
mobile/src/main/java/hanson/xyz/vpnhotspotmod/MyBroadcastReceiver.kt | hansonxyz | 657,293,222 | false | null | package hanson.xyz.vpnhotspotmod
import android.bluetooth.BluetoothManager
import android.content.*
import android.graphics.drawable.Icon
import android.os.Build
import android.os.IBinder
import android.service.quicksettings.Tile
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import hanson.xyz.vpnhotspotmod.R
import hanson.xyz.vpnhotspotmod.TetheringService
import hanson.xyz.vpnhotspotmod.manage.BluetoothTethering
import hanson.xyz.vpnhotspotmod.net.TetherType
import hanson.xyz.vpnhotspotmod.net.TetheringManager
import hanson.xyz.vpnhotspotmod.net.TetheringManager.tetheredIfaces
import hanson.xyz.vpnhotspotmod.net.wifi.WifiApManager
import hanson.xyz.vpnhotspotmod.util.broadcastReceiver
import hanson.xyz.vpnhotspotmod.util.readableMessage
import hanson.xyz.vpnhotspotmod.util.stopAndUnbind
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
// added by hansonxyz
class MyBroadcastReceiver : BroadcastReceiver(), TetheringManager.StartTetheringCallback {
private val handler = Handler(Looper.getMainLooper())
override fun onReceive(context: Context, intent: Intent) {
if (intent.action.toString().contains("BT_TETHER_START")) {
TetheringManager.startTethering(TetheringManager.TETHERING_BLUETOOTH, false, this)
}
if (intent.action.toString().contains("BT_TETHER_STOP")) {
TetheringManager.stopTethering(TetheringManager.TETHERING_BLUETOOTH)
}
if (intent.action.toString().contains("WIFI_TETHER_START")) {
TetheringManager.startTethering(TetheringManager.TETHERING_WIFI, false, this)
}
if (intent.action.toString().contains("WIFI_TETHER_STOP")) {
TetheringManager.stopTethering(TetheringManager.TETHERING_WIFI)
}
}
}
| 0 | Kotlin | 0 | 0 | 9c9f2cf51fd47b8f1ecf2a8ded7c765fc5034521 | 2,059 | vpnhotspotmod | Apache License 2.0 |
src/test/kotlin/hw3/task3/TestGeneratorConfigTest.kt | Degiv | 346,809,895 | false | null | package hw3.task3
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
internal class TestGeneratorConfigTest {
companion object {
@JvmStatic
fun inputData(): List<Arguments> = listOf(
Arguments.of(
"testConfig1.yaml",
TestGeneratorConfig(
"hw1.task3",
"InsertForward",
listOf(
FunctionName("perform"),
FunctionName("undo")
)
)
),
Arguments.of(
"testConfig2.yaml",
TestGeneratorConfig(
"hw1.task3",
"InsertBack",
listOf(
FunctionName("perform"),
FunctionName("undo")
)
)
)
)
}
@MethodSource("inputData")
@ParameterizedTest(name = "{index} {0}")
fun getFromYamlTest(inputName: String, expectedConfig: TestGeneratorConfig) {
assertEquals(expectedConfig, TestGeneratorConfig.getFromYaml(javaClass.getResource(inputName).readText()))
}
}
| 0 | Kotlin | 0 | 0 | 78304b37445a11cbd182c3044d72905f0703cd70 | 1,348 | spbu_kotlin_homework | Apache License 2.0 |
deprecated/network/sample/src/main/java/ru/surfstudio/android/network/sample/interactor/common/network/calladapter/CallAdapterFactory.kt | surfstudio | 139,034,657 | false | null | package ru.surfstudio.android.network.sample.interactor.common.network.calladapter
import ru.surfstudio.android.dagger.scope.PerApplication
import ru.surfstudio.android.network.calladapter.BaseCallAdapterFactory
import javax.inject.Inject
@PerApplication
class CallAdapterFactory @Inject constructor() : BaseCallAdapterFactory() | 5 | null | 30 | 249 | 6d73ebcaac4b4bd7186e84964cac2396a55ce2cc | 330 | SurfAndroidStandard | Apache License 2.0 |
src/main/kotlin/com/github/mckernant1/lol/blitzcrank/commands/lol/RosterCommand.kt | mckernant1 | 274,566,972 | false | null | package com.github.mckernant1.lol.blitzcrank.commands.lol
import com.github.mckernant1.extensions.strings.capitalize
import com.github.mckernant1.lol.blitzcrank.commands.DiscordCommand
import com.github.mckernant1.lol.blitzcrank.utils.apiClient
import com.github.mckernant1.lol.esports.api.models.Team
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
class RosterCommand(event: MessageReceivedEvent) : DiscordCommand(event) {
override fun validate() {
validateWordCount(2..2)
validateTeam(1)
}
override suspend fun execute() {
val teamToGet = words[1]
val team = apiClient.getTeamByCode(teamToGet.uppercase())
val message = formatMessage(team)
event.channel.sendMessage(message).complete()
}
private fun formatMessage(team: Team): String {
return "${team.name.capitalize()} Current Roster:\n" +
apiClient.getPlayersOnTeam(team.teamId.uppercase())
.asSequence()
.filter { player -> RoleSort.values().any { it.name.equals(player.role, true) } }
.sortedBy { RoleSort.valueOf(it.role!!.uppercase()).sorter }
.groupBy { it.role }
.map { role ->
"${role.key!!.capitalize()}:\n" +
role.value.joinToString("\n") { " -${it.id}" }
}.joinToString("\n") { it }
}
private enum class RoleSort(val sorter: Int) {
TOP(1),
JUNGLE(2),
MID(3),
BOT(4),
SUPPORT(5),
COACH(6),
NONE(7);
}
}
| 0 | Kotlin | 1 | 1 | ec284b1f7965b36c420f3d851cffea0683064bf2 | 1,628 | lol-predictions-bot | MIT License |
app/src/main/java/io/github/gmathi/novellibrary/fragment/DownloadFragment.kt | DonielMoins | 288,104,783 | true | {"Kotlin": 679756, "Java": 35788} | package io.github.gmathi.novellibrary.fragment
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.gmathi.novellibrary.R
import io.github.gmathi.novellibrary.activity.NavDrawerActivity
import io.github.gmathi.novellibrary.activity.startDownloadService
import io.github.gmathi.novellibrary.adapter.GenericAdapter
import io.github.gmathi.novellibrary.database.deleteDownload
import io.github.gmathi.novellibrary.database.getAllDownloads
import io.github.gmathi.novellibrary.database.updateDownloadStatus
import io.github.gmathi.novellibrary.dbHelper
import io.github.gmathi.novellibrary.model.Download
import io.github.gmathi.novellibrary.model.DownloadWebPageEvent
import io.github.gmathi.novellibrary.model.EventType
import io.github.gmathi.novellibrary.service.download.DownloadService
import io.github.gmathi.novellibrary.util.Utils
import io.github.gmathi.novellibrary.util.setDefaultsNoAnimation
import kotlinx.android.synthetic.main.activity_download_queue.*
import kotlinx.android.synthetic.main.content_download_queue.*
import kotlinx.android.synthetic.main.listitem_download_queue.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class DownloadFragment : BaseFragment(), GenericAdapter.Listener<Download> {
lateinit var adapter: GenericAdapter<Download>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.activity_download_queue, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
toolbar.title = getString(R.string.title_downloads)
setRecyclerView()
activity?.let {
(it as NavDrawerActivity).setToolbar(toolbar)
if (Utils.isServiceRunning(it, DownloadService.QUALIFIED_NAME)) {
fab.setImageResource(R.drawable.ic_pause_white_vector)
fab.tag = "playing"
} else {
fab.setImageResource(R.drawable.ic_play_arrow_white_vector)
fab.tag = "paused"
}
fab.setOnClickListener { _ ->
if (!adapter.items.isEmpty()) {
if (fab.tag == "playing") {
//pause all
it.stopService(Intent(it, DownloadService::class.java))
fab.setImageResource(R.drawable.ic_play_arrow_white_vector)
fab.tag = "paused"
} else if (fab.tag == "paused") {
//play all
it.startService(Intent(it, DownloadService::class.java))
fab.setImageResource(R.drawable.ic_pause_white_vector)
fab.tag = "playing"
}
}
}
}
}
private fun setRecyclerView() {
val items = dbHelper.getAllDownloads()
adapter = GenericAdapter(ArrayList(items), R.layout.listitem_download_queue, this)
recyclerView.setDefaultsNoAnimation(adapter)
recyclerView.addItemDecoration(object : DividerItemDecoration(context, DividerItemDecoration.VERTICAL) {
override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
val position = parent?.getChildAdapterPosition(view)
if (position == parent?.adapter?.itemCount?.minus(1)) {
outRect?.setEmpty()
} else {
super.getItemOffsets(outRect, view, parent, state)
}
}
})
}
//region Adapter Listener Methods - onItemClick(), viewBinder()
@SuppressLint("SetTextI18n")
override fun bind(item: Download, itemView: View, position: Int) {
itemView.title.text = item.novelName
when {
item.status == Download.STATUS_IN_QUEUE -> itemView.downloadPauseButton.setImageResource(R.drawable.ic_pause_white_vector)
item.status == Download.STATUS_PAUSED -> itemView.downloadPauseButton.setImageResource(R.drawable.ic_play_arrow_white_vector)
item.status == Download.STATUS_RUNNING -> itemView.downloadPauseButton.setImageResource(R.drawable.ic_cloud_download_white_vector)
}
itemView.subtitle.text = item.chapter
itemView.downloadPauseButton.setOnClickListener {
when {
item.status == Download.STATUS_IN_QUEUE -> {
itemView.downloadPauseButton.setImageResource(R.drawable.ic_play_arrow_white_vector)
item.status = Download.STATUS_PAUSED
dbHelper.updateDownloadStatus(Download.STATUS_PAUSED, item.webPageId)
}
item.status == Download.STATUS_PAUSED -> {
itemView.downloadPauseButton.setImageResource(R.drawable.ic_pause_white_vector)
item.status = Download.STATUS_IN_QUEUE
if (!Utils.isServiceRunning(activity!!, DownloadService.QUALIFIED_NAME))
activity?.startDownloadService()
}
//item.status == Download.STATUS_RUNNING ->
//Do Nothing
//itemView.downloadPauseButton.setImageResource(R.drawable.ic_cloud_download_white_vector)
}
}
itemView.downloadDeleteButton.setOnClickListener {
dbHelper.deleteDownload(item.webPageId)
adapter.removeItem(item)
//confirmDeleteAlert(item)
}
}
override fun onItemClick(item: Download) {
}
//endregion
// private fun confirmDeleteAlert(novel: Novel) {
// activity?.let {
// MaterialDialog.Builder(it)
// .content(getString(R.string.remove_from_downloads))
// .positiveText(getString(R.string.remove))
// .negativeText(getString(R.string.cancel))
// .icon(ContextCompat.getDrawable(it, R.drawable.ic_delete_white_vector)!!)
// .typeface("source_sans_pro_regular.ttf", "source_sans_pro_regular.ttf")
// .theme(Theme.DARK)
// .onPositive { _, _ -> deleteNovel(novel) }
// .show()
// }
// }
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onDownloadEvent(webPageEvent: DownloadWebPageEvent) {
if (webPageEvent.type == EventType.RUNNING) {
adapter.items.firstOrNull { it.webPageId == webPageEvent.webPageId }?.status = Download.STATUS_RUNNING
adapter.items.firstOrNull { it.webPageId == webPageEvent.webPageId }?.let {
it.status = Download.STATUS_RUNNING
adapter.updateItem(it)
}
}
if (webPageEvent.type == EventType.COMPLETE) {
adapter.removeItem(webPageEvent.download)
}
}
}
| 0 | Kotlin | 0 | 0 | dfbd1af4e3c82624fa637b0b90e3be8fc555a270 | 7,565 | NovelLibrary | Apache License 2.0 |
domain/src/main/java/com/andhiratobing/domain/mapper/MovieMapper.kt | andhiratobing | 420,155,298 | false | {"Kotlin": 52488} | package com.andhiratobing.domain.mapper
import com.andhiratobing.domain.models.MovieDomain
import com.andhiratobing.remote.dto.movie.MovieDto
class MovieMapper : Mapper<List<MovieDto>, List<MovieDomain>> {
override fun mapFromEntityToDomain(type: List<MovieDto>): List<MovieDomain> {
return type.map { movieDto ->
MovieDomain(
backdropPath = movieDto.backdropPath,
genreIds = movieDto.genreIds,
id = movieDto.id,
originalTitle = movieDto.originalTitle,
overview = movieDto.originalTitle,
posterPath = movieDto.posterPath,
releaseDate = movieDto.releaseDate,
voteAverage = movieDto.voteAverage,
)
}
}
override fun mapFromDomainToEntity(type: List<MovieDomain>): List<MovieDto> {
return type.map { movieDomain ->
MovieDto(
backdropPath = movieDomain.backdropPath,
genreIds = movieDomain.genreIds,
id = movieDomain.id,
originalTitle = movieDomain.originalTitle,
overview = movieDomain.originalTitle,
posterPath = movieDomain.posterPath,
releaseDate = movieDomain.releaseDate,
voteAverage = movieDomain.voteAverage,
)
}
}
} | 0 | Kotlin | 1 | 1 | c801591ffd13a65f9f442f6566f44c64b614f9c2 | 1,377 | movie | Apache License 2.0 |
movies/src/commonMain/kotlin/movies/MovieRepositoryImpl.kt | 4face-studi0 | 280,630,732 | false | null | package movies
import entities.movies.MovieRepository
internal class MovieRepositoryImpl(
private val remoteSource: RemoteMovieSource
) : MovieRepository by remoteSource
| 24 | Kotlin | 1 | 3 | 572514b24063815fba93809a9169a470f89fd445 | 176 | CineScout | Apache License 2.0 |
felles/src/main/kotlin/no/nav/helsearbeidsgiver/felles/rapidsrivers/Løser.kt | navikt | 495,713,363 | false | null | package no.nav.helsearbeidsgiver.felles.rapidsrivers
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import no.nav.helsearbeidsgiver.felles.EventName
import no.nav.helsearbeidsgiver.felles.Fail
import no.nav.helsearbeidsgiver.felles.Key
abstract class Løser(val rapidsConnection: RapidsConnection) : River.PacketListener {
lateinit var eventName: EventName
lateinit var forespoerselId: String
init {
configure(
River(rapidsConnection).apply {
validate(accept())
}
).register(this)
}
abstract fun accept(): River.PacketValidation
private fun configure(river: River): River {
return river.validate {
it.demandKey(Key.EVENT_NAME.str)
it.demandKey(Key.BEHOV.str)
it.rejectKey(Key.LØSNING.str)
it.interestedIn(Key.UUID.str)
it.interestedIn(Key.FORESPOERSEL_ID.str)
}
}
// Ungå å bruke det, hvis du kan.
// Alle løser som publiserer Behov vil få kunskap om nedstrøms løserne.
// i tilleg gjenbruktbarhet av løseren vil vare betydelig redusert
fun publishBehov(message: JsonMessage) {
message[Key.EVENT_NAME.str] = eventName.name
if (forespoerselId.isNotEmpty()) {
message[Key.FORESPOERSEL_ID.str] = forespoerselId
}
rapidsConnection.publish(message.toJson())
}
fun publishEvent(message: JsonMessage) {
if (forespoerselId.isNotEmpty()) {
message[Key.FORESPOERSEL_ID.str] = forespoerselId
}
rapidsConnection.publish(message.toJson())
}
fun publishData(message: JsonMessage) {
message[Key.EVENT_NAME.str] = eventName.name
rapidsConnection.publish(message.toJson())
}
fun publishFail(fail: Fail) {
rapidsConnection.publish(fail.toJsonMessage().toJson())
}
fun publishFail(message: JsonMessage) {
message[Key.EVENT_NAME.str] = eventName.name
rapidsConnection.publish(message.toJson())
}
override fun onPacket(packet: JsonMessage, context: MessageContext) {
eventName = EventName.valueOf(packet[Key.EVENT_NAME.str].asText())
forespoerselId = packet[Key.FORESPOERSEL_ID.str].asText()
onBehov(packet)
}
abstract fun onBehov(packet: JsonMessage)
}
| 14 | Kotlin | 0 | 2 | 347a1c30c2ab0ceb57e560de6936e3394831c9fd | 2,451 | helsearbeidsgiver-inntektsmelding | MIT License |
tmp/arrays/youTrackTests/611.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-41238
typealias ResponseCallback<T> = (T) -> Unit
typealias ResponseWrapperCallback<T> = (Wrapper<T>) -> Unit
class Wrapper<T>(val data: T)
object Testing {
fun callbackTest(callback: ResponseCallback<List<Int>>) {
var intList: List<Int> = listOf(1,2,3,4)
callback(intList)
}
fun callbackWrapperTest(callback: ResponseWrapperCallback<List<Int>>) {
var intList: List<Int> = listOf(1,2,3,4)
callback(Wrapper(intList))
}
}
| 1 | null | 1 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 492 | bbfgradle | Apache License 2.0 |
PreviewablePic/composeApp/src/desktopMain/kotlin/test/aussie/previewablepic/main.kt | AndyDentFree | 864,764,349 | false | {"Kotlin": 17560, "Swift": 1242, "HTML": 340, "CSS": 102} | package test.aussie.previewablepic
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "PreviewablePic",
) {
App()
}
} | 0 | Kotlin | 0 | 0 | 10ea151fde71f08acf39ac8ac9af5ebee83c7e43 | 270 | kotlyrical | MIT License |
tmp/arrays/youTrackTests/8903.kt | DaniilStepanov | 228,623,440 | false | {"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4} | // Original bug: KT-15871
inline fun <T> getAndCheck(getFirst: () -> T, getSecond: () -> T) =
getFirst() == getSecond()
fun getAndCheckInt(a: Int, b: Int) =
getAndCheck({ a }, { b })
| 1 | null | 1 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 193 | bbfgradle | Apache License 2.0 |
app/src/main/java/com/minaev/apod/presentation/feature/apod_list/ApodListContract.kt | EvgeniyEO | 596,599,800 | false | null | package com.minaev.apod.presentation.feature.apod_list
import com.minaev.apod.presentation.feature.SnackBarEvent
import com.minaev.apod.presentation.feature.ViewEvent
import com.minaev.apod.presentation.feature.ViewSideEffect
import com.minaev.apod.presentation.feature.ViewState
class ApodListContract {
data class State(
val isRefresh: Boolean,
val apodData: ApodListDataModel
) : ViewState
sealed class Event : ViewEvent {
object OnRefreshData: Event()
}
sealed class Effect: ViewSideEffect {
data class SnackBar(val snackBarEvent: SnackBarEvent): Effect()
}
} | 0 | Kotlin | 0 | 0 | 7f498f912a6ee8c45313f6898f55268a144d0e4a | 625 | NAPOD | MIT License |
app/src/main/java/com/umair/archiTemplate2/data/repositories/accessPoint/AccessPointDataSource.kt | umair13adil | 244,596,063 | false | null | package com.umair.archiTemplate2.data.repositories.accessPoint
import com.umair.archiTemplate2.model.accessPoint.AccessPoint
import com.umair.archiTemplate2.model.room.Room
interface AccessPointDataSource {
fun addRoom(room: Room)
fun addAccessPoint(accessPoint: AccessPoint)
fun addAccessPoints(accessPoints: List<AccessPoint>)
}
| 0 | Kotlin | 0 | 5 | beadd5db3284a48a7f2622a0bb1b585203232775 | 348 | SmartIndoor-PositioningAndroid | The Unlicense |
src/main/kotlin/phonon/puppet/math/interpolation/Interpolation.kt | phonon | 278,514,975 | false | null | /**
* Interface for interpolation functions
*/
package phonon.puppet.math
interface Interpolation {
public fun interpolate(v1: Double, v2: Double, t: Double): Double
companion object {
// references to interpolation functions
val CONSTANT: Interpolation = ConstantInterpolation
val LINEAR: Interpolation = LinearInterpolation
// return interpolation function from string name
public fun get(name: String): Interpolation {
return when ( name.toLowerCase() ) {
"const",
"constant" -> ConstantInterpolation
"linear" -> LinearInterpolation
else -> LinearInterpolation
}
}
}
} | 0 | Kotlin | 0 | 9 | 55b6d7055fd6bed9377bebfa39b7084dd24d9341 | 744 | minecraft-puppet | MIT License |
src/main/kotlin/mathlingua/lib/frontend/textalk/TexTalkParser.kt | DominicKramer | 203,428,613 | false | null | /*
* Copyright 2022 Dominic Kramer
*
* 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 mathlingua.lib.frontend.textalk
import mathlingua.lib.frontend.Diagnostic
import mathlingua.lib.frontend.ast.EmptyTexTalkNode
import mathlingua.lib.frontend.ast.TexTalkNode
internal interface TexTalkParser {
fun parse(): TexTalkNode
fun diagnostics(): List<Diagnostic>
}
internal fun newTexTalkParser(lexer: TexTalkLexer): TexTalkParser = TexTalkParserImpl(lexer)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private class TexTalkParserImpl(private val lexer: TexTalkLexer) : TexTalkParser {
private val diagnostic = mutableListOf<Diagnostic>()
override fun diagnostics() = diagnostic
override fun parse() = lexer.toTree()?.toTexTalkNode(diagnostics()) ?: EmptyTexTalkNode
}
| 1 | Kotlin | 0 | 68 | a1f5730e7ca48b12f2be157e8118a067634afebb | 1,386 | mathlingua | Apache License 2.0 |
api-public/src/main/kotlin/gropius/schema/query/UserQueries.kt | ccims | 487,996,394 | false | {"Kotlin": 958426, "TypeScript": 437791, "MDX": 55477, "JavaScript": 25165, "HTML": 17174, "CSS": 4796, "Shell": 2363} | package gropius.schema.query
import com.expediagroup.graphql.generator.annotations.GraphQLDescription
import com.expediagroup.graphql.server.operations.Query
import graphql.schema.DataFetchingEnvironment
import gropius.authorization.GropiusAuthorizationContext
import gropius.authorization.gropiusAuthorizationContext
import gropius.model.user.GropiusUser
import gropius.repository.user.GropiusUserRepository
import io.github.graphglue.graphql.extensions.authorizationContext
import kotlinx.coroutines.reactor.awaitSingle
import org.springframework.stereotype.Component
/**
* Contains all user-related queries
*
* @param gropiusUserRepository for getting [GropiusUser] by id
*/
@Component
class UserQueries(private val gropiusUserRepository: GropiusUserRepository) : Query {
@GraphQLDescription("The current authenticated user")
suspend fun currentUser(dfe: DataFetchingEnvironment): GropiusUser? {
return if (dfe.authorizationContext is GropiusAuthorizationContext) {
val userId = dfe.gropiusAuthorizationContext.userId
gropiusUserRepository.findById(userId).awaitSingle()
} else {
null
}
}
} | 3 | Kotlin | 1 | 0 | de0ece42541db960a08e1448cf0bd5afd65c996a | 1,173 | gropius-backend | MIT License |
app/src/main/java/info/motoaccident/dictionaries/Role.kt | rjhdby | 59,946,342 | false | null | package info.motoaccident.dictionaries
import com.google.gson.annotations.SerializedName
enum class Role {
@SerializedName("r") READ_ONLY,
@SerializedName("s") STANDARD,
@SerializedName("m") MODERATOR,
@SerializedName("d") DEVELOPER,
UNAUTHORIZED,
ANONYMOUS
} | 0 | Kotlin | 1 | 2 | 71b31e8d4991876f7c59ea8a6ea47478621a0cf6 | 285 | MotoAccident.Info | MIT License |
app/src/main/java/com/example/fitpeo/presentation/favourite/ImageRecyclerview.kt | Tabishahmad | 669,515,444 | false | null | package com.example.fitpeo.presentation.favourite
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.fitpeo.domain.model.Album
import com.example.fitpeo.presentation.list.FavListAdapter
import com.example.fitpeo.presentation.list.ImageListAdapter
class ImageRecyclerview : RecyclerView {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init()
}
private fun init() {
layoutManager = GridLayoutManager(context, 3)
adapter = ImageListAdapter()
}
private fun getMAdapter(): FavListAdapter {
return adapter as FavListAdapter
}
fun setData(list: List<Album>) {
getMAdapter().updateList(list)
}
fun setItemClickListener(listener: FavListAdapter.ItemClickListener) {
getMAdapter().setClickListener(listener)
}
}
| 0 | Kotlin | 0 | 0 | dde4964584dd2cec066eb0b0272d84c36349ab8c | 1,210 | Content-Showcase-App | MIT License |
src/main/kotlin/com/github/mrbean355/admiralbulldog/mod/compile/TextReplacements.kt | MrBean355 | 227,180,666 | false | null | package com.github.mrbean355.admiralbulldog.mod.compile
import com.github.mrbean355.admiralbulldog.mod.util.TEXT_REPLACEMENTS
import java.io.File
/**
* Only replace lines that match this pattern.
*
* Example:
* "DOTA_Tooltip_Ability_item_hand_of_midas" "Hand of Midas" // optional comment which says stuff
*/
private val FILE_ENTRY_PATTERN = Regex("^\\s*\"(.*)\"\\s*\"(.*)\".*$")
// Symbols used in the mappings file:
private const val SEPARATOR = '='
private const val EXACT_REPLACE = '!'
private const val SINGLE_REPLACE = '@'
private const val COMMENT = '#'
object TextReplacements {
private val containsReplacements = mutableMapOf<String, String>()
private val exactReplacements = mutableMapOf<String, String>()
private val singleReplacements = mutableMapOf<String, String>()
init {
loadReplacements()
}
fun applyToFile(input: File) {
require(input.exists()) { "Input file doesn't exist: ${input.absolutePath}" }
val output = StringBuilder()
input.forEachLine { line ->
val match = FILE_ENTRY_PATTERN.matchEntire(line)
if (match == null) {
output.append(line + "\n")
} else {
val key = match.groupValues[1]
val oldValue = match.groupValues[2]
var newValue = oldValue
when {
key in singleReplacements -> newValue = singleReplacements[key]!!
oldValue in exactReplacements -> newValue = exactReplacements[oldValue]!!
else -> {
containsReplacements.forEach { (k, v) ->
newValue = newValue.replace(k, v)
}
}
}
output.append(line.replace("\"$oldValue\"", "\"$newValue\"") + "\n")
}
}
input.writeText(output.toString())
}
private fun loadReplacements() {
val file = File(TEXT_REPLACEMENTS)
require(file.exists()) { "Replacements file doesn't exist: ${file.absolutePath}" }
file.readLines()
.map { it.trim() }
.filter { it.isNotEmpty() }
.filter { !it.startsWith(COMMENT) }
.forEach { line ->
val parts = line
.substringBefore(COMMENT)
.split(SEPARATOR)
require(parts.size == 2) { "Invalid syntax: $line" }
val key = parts.first().trim()
val value = parts[1].trim()
when {
key.startsWith(EXACT_REPLACE) -> exactReplacements += key.drop(1) to value
key.startsWith(SINGLE_REPLACE) -> singleReplacements += key.drop(1) to value
else -> containsReplacements += key to value
}
}
}
}
| 0 | Kotlin | 1 | 3 | 14b6f982ebb1df9c36f87cb03561450e43adbc65 | 2,946 | admiralbulldog-mod | Apache License 2.0 |
lemma-core/src/main/kotlin/lemma/jwm.kt | kubeliv | 470,008,106 | false | null | package lemma
typealias JwmWindow = io.github.humbleui.jwm.Window
| 0 | Kotlin | 0 | 0 | 40a0c58114f7045c150220fb248e5734aadf3f2b | 67 | lemma | MIT License |
src/main/kotlin/com/deflatedpickle/spnorf/Orientation.kt | DeflatedPickle | 184,711,184 | false | null | package com.deflatedpickle.spnorf
enum class Orientation {
HORIZONTAL,
VERTICAL
} | 0 | Kotlin | 0 | 1 | 7a5e6640e59af342057dd4676caf9b84d22a91ce | 90 | Spnorf | MIT License |
app/src/main/java/com/jxareas/xpensor/features/accounts/presentation/ui/actions/filter/AccountFilterViewModel.kt | jxareas | 540,284,293 | false | {"Kotlin": 260827, "Python": 1602, "Shell": 695} | package com.jxareas.xpensor.features.accounts.presentation.ui.actions.filter
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jxareas.xpensor.common.extensions.launchScoped
import com.jxareas.xpensor.common.extensions.mapEach
import com.jxareas.xpensor.core.data.local.preferences.UserPreferences
import com.jxareas.xpensor.features.accounts.domain.model.Account
import com.jxareas.xpensor.features.accounts.domain.usecase.GetAccountsUseCase
import com.jxareas.xpensor.features.accounts.domain.usecase.GetTotalAccountsAmountUseCase
import com.jxareas.xpensor.features.accounts.presentation.mapper.toAccountUi
import com.jxareas.xpensor.features.accounts.presentation.model.AccountUi
import com.jxareas.xpensor.features.accounts.presentation.model.TotalAccountsAmountUi
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import javax.inject.Inject
@HiltViewModel
class AccountFilterViewModel @Inject constructor(
private val getAccountsUseCase: GetAccountsUseCase,
private val getTotalAccountsAmountUseCase: GetTotalAccountsAmountUseCase,
private val userPreferences: UserPreferences,
) : ViewModel() {
private val _accounts = MutableStateFlow(emptyList<AccountUi>())
val accounts = _accounts.asStateFlow()
private val _totalAccountAmount = MutableStateFlow<TotalAccountsAmountUi?>(null)
val totalAccountsAmount = _totalAccountAmount.asStateFlow()
private val _eventEmitter = Channel<AccountFilterUiEvent>(Channel.UNLIMITED)
val eventSource = _eventEmitter.receiveAsFlow()
private var fetchAccountsJob: Job? = null
private var fetchAccountsAmountJob: Job? = null
init {
launchFetchAccountsJob()
launchFetchAccountAmountsJob()
}
private fun launchFetchAccountsJob() {
fetchAccountsJob?.cancel()
fetchAccountsJob = getAccountsUseCase.invoke()
.mapEach(Account::toAccountUi)
.onEach(_accounts::value::set)
.launchIn(viewModelScope)
}
fun onSelectAccountClick(account: AccountUi) = launchScoped {
_eventEmitter.send(AccountFilterUiEvent.SelectAccount(account))
}
private fun launchFetchAccountAmountsJob() {
fetchAccountsAmountJob?.cancel()
getTotalAccountsAmountUseCase.invoke()
.onEach {
val preferredCurrency = userPreferences.getPreferredCurrencyName()
_totalAccountAmount.value = TotalAccountsAmountUi(it, preferredCurrency)
}
.launchIn(viewModelScope)
}
}
| 0 | Kotlin | 3 | 35 | c8639526a7fdd710e485668093ce627e0fa1e8e5 | 2,832 | Xpensor | MIT License |
sdk/src/main/java/com/talobin/robinhood/data/stock/News.kt | talobin | 352,029,813 | false | null | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.talobin.robinhood.data.stock
import com.google.gson.annotations.SerializedName
data class News(
@field:SerializedName("api_source") val apiSource: String,
@field:SerializedName("author") val author: String,
@field:SerializedName("currency_id") val currencyId: String,
@field:SerializedName("num_clicks") val numClicks: Int,
@field:SerializedName("preview_image_url") val previewImageUrl: String,
@field:SerializedName("preview_text") val previewText: String,
@field:SerializedName("published_at") val publishedAt: String,
@field:SerializedName("related_instruments") val relatedInstruments: List<String>,
@field:SerializedName("relay_url") val relayUrl: String,
@field:SerializedName("source") val source: String,
@field:SerializedName("summary") val summary: String,
@field:SerializedName("title") val title: String,
@field:SerializedName("updated_at") val updatedAt: String,
@field:SerializedName("url") val url: String,
@field:SerializedName("uuid") val uuid: String
) | 0 | Kotlin | 0 | 0 | f32dd6d2c53bd6cd3ed57d8386277b0022f12790 | 1,701 | Robinhood-Android-SDK | Apache License 2.0 |
src/main/kotlin/AttributeProvider.kt | lindsaygelle | 833,228,388 | false | {"Kotlin": 266747} | package dqbb
interface AttributeProvider : Identifier {
fun getAttribute(attributeName: AttributeName): Int?
} | 0 | Kotlin | 0 | 0 | 85be9ba03e7de5ef25ec31f2138fe9c710e659b9 | 115 | dqbb | MIT License |
src/main/kotlin/com/bchetty/koans/SealedClasses.kt | bchetty | 562,739,527 | false | null | package com.bchetty.koans
fun eval1(expr: Expr1): Int =
when (expr) {
is Num1 -> expr.value
is Sum1 -> eval1(expr.left) + eval1(expr.right)
}
sealed interface Expr1
class Num1(val value: Int) : Expr1
class Sum1(val left: Expr1, val right: Expr1) : Expr1
fun main() {
println("Number: ${eval1(Num1(42))}")
println("Sum: ${eval1(Sum1(Num1(33), Num1(33)))}")
} | 0 | Kotlin | 0 | 0 | a85232881c65c538763c69d19fa9703a85f21bdd | 392 | kotlin-workshop | Apache License 2.0 |
src/resourceshrinker/java/com/android/build/shrinker/obfuscation/ObfuscatedClasses.kt | Col-E | 630,934,009 | false | {"Gradle": 5, "Markdown": 10, "Java Properties": 15, "Shell": 11, "Text": 172, "Ignore List": 1, "Batchfile": 2, "Python": 94, "INI": 6, "Java": 7943, "Kotlin": 194, "Jasmin": 1, "Ruby": 1, "XML": 11, "JSON": 5, "Starlark": 1, "HAProxy": 5, "Checksums": 205, "Gradle Kotlin DSL": 30, "Dockerfile": 1, "Roff": 1} | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.res.shrinker.obfuscation
import com.android.build.gradle.internal.utils.toImmutableMap
/** Contains mappings between obfuscated classes and methods to original ones. */
class ObfuscatedClasses private constructor(builder: Builder) {
companion object {
@JvmField
val NO_OBFUSCATION = Builder().build()
}
private val obfuscatedClasses = builder.obfuscatedClasses.toImmutableMap()
private val obfuscatedMethods = builder.obfuscatedMethods.toImmutableMap()
fun resolveOriginalMethod(obfuscatedMethod: ClassAndMethod): ClassAndMethod {
return obfuscatedMethods.getOrElse(obfuscatedMethod, {
val realClassName = obfuscatedClasses.getOrDefault(
obfuscatedMethod.className, obfuscatedMethod.className)
ClassAndMethod(realClassName, obfuscatedMethod.methodName)
})
}
fun resolveOriginalClass(obfuscatedClass: String): String {
return obfuscatedClasses.getOrDefault(obfuscatedClass, obfuscatedClass)
}
/**
* Builder that allows to build obfuscated mappings in a way when next method mapping is added
* to previous class mapping. Example:
* builder
* .addClassMapping(Pair(classA, obfuscatedClassA))
* .addMethodMapping(Pair(classAMethod1, obfuscatedClassAMethod1))
* .addMethodMapping(Pair(classAMethod2, obfuscatedClassAMethod2))
* .addClassMapping(Pair(classB, obfuscatedClassB))
* .addMethodMapping(Pair(classBMethod1, obfuscatedClassBMethod1))
*/
class Builder {
val obfuscatedClasses: MutableMap<String, String> = mutableMapOf()
val obfuscatedMethods: MutableMap<ClassAndMethod, ClassAndMethod> = mutableMapOf()
var currentClassMapping: Pair<String, String>? = null
/**
* Adds class mapping: original class name -> obfuscated class name.
*
* @param mapping Pair(originalClassName, obfuscatedClassName)
*/
fun addClassMapping(mapping: Pair<String, String>): Builder {
currentClassMapping = mapping
obfuscatedClasses += Pair(mapping.second, mapping.first)
return this
}
/**
* Adds method mapping: original method name -> obfuscated method name to the latest added
* class mapping.
*
* @param mapping Pair(originalMethodName, obfuscatedMethodName)
*/
fun addMethodMapping(mapping: Pair<String, String>): Builder {
if (currentClassMapping != null) {
obfuscatedMethods += Pair(
ClassAndMethod(currentClassMapping!!.second, mapping.second),
ClassAndMethod(currentClassMapping!!.first, mapping.first)
)
}
return this
}
fun build(): ObfuscatedClasses =
ObfuscatedClasses(this)
}
}
data class ClassAndMethod(val className: String, val methodName: String)
| 1 | Java | 2 | 14 | 42ca987b1ed7c4a235c2dada2dd776b187799d24 | 3,613 | r8 | Apache License 2.0 |
client/client-hapi/src/commonMain/kotlin/de/jlnstrk/transit/api/hapi/response/base/HapiResponse.kt | jlnstrk | 229,599,180 | false | {"Kotlin": 729374} | package de.jlnstrk.transit.api.hapi.response.base
import de.jlnstrk.transit.api.hafas.HapiXsd
import de.jlnstrk.transit.api.hapi.model.HapiPair
import de.jlnstrk.transit.api.hapi.serializer.HapiListUnwrapSerializer
import kotlinx.serialization.Serializable
@HapiXsd("1.29")
@Serializable
public abstract class HapiResponse {
@Serializable(with = HapiListUnwrapSerializer::class)
public val TechnicalMessages: List<HapiPair> = emptyList()
public val serverVersion: String? = null
public val dialectVersion: String? = null
public val version: String? = null
// TODO: Format?
public val planRtTs: Long? = null
public val errorCode: String? = null
public val errorText: String? = null
public val requestId: String? = null
} | 0 | Kotlin | 0 | 0 | 9f700364f78ebc70b015876c34a37b36377f0d9c | 762 | transit | Apache License 2.0 |
api/src/test/kotlin/io/quickpicks/graphql/GraphQLTest.kt | lavabear | 173,855,849 | false | null | package io.quickpicks.graphql
import io.quickpicks.db.Persistence
import io.mockk.*
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Test
import java.util.concurrent.CompletableFuture
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
private typealias GraphQLData = Map<String, List<Map<String, Any>>>
class GraphQLTest {
private val persistence = mockk<Persistence>()
// All Tests in this class will fail if GraphQL object cannot be built
private val graphql = graphql(persistence)
private val drawingsNameQuery = """
{
drawings(abbr: "powerball") {
all {
id
}
}
}
""".trimIndent()
@Test
fun `base specification - bad query`() {
val badQuery = graphql.execute("")
val specification = badQuery.toSpecification()
assertFalse(specification.isEmpty())
assertEquals(setOf("extensions", "data", "errors"), specification.keys)
assertFalse(badQuery.errors.isEmpty())
}
@Test
@Suppress("UNCHECKED_CAST")
fun `request drawings - no drawing`() {
every { persistence.drawings(any()) } returns CompletableFuture.completedFuture(emptyList())
val drawingsResult = graphql.execute(drawingsNameQuery)
verify(exactly = 1) { persistence.drawings(any()) }
val specification = drawingsResult.toSpecification()
val drawingsSpec = specification["data"] as GraphQLData
val drawings = (drawingsSpec["drawings"] as Map<String, List<Map<String, Any>>>)["all"]
assertNotNull(drawings)
assertTrue(drawings.isEmpty())
clearMocks(persistence)
}
} | 0 | Kotlin | 0 | 1 | 5a54ea7e0f4020c9cc9ddb2dbcf0ee29a078823e | 1,792 | quick_picks | MIT License |
MVVMGENERATER/app/src/main/java/com/example/mvvmgenerater/ui/BaseFragment.kt | swithun-liu | 380,738,744 | false | {"Kotlin": 427386, "Dart": 88166, "CMake": 25305, "C++": 23774, "Rust": 11694, "Ruby": 6722, "Shell": 4225, "Batchfile": 2441, "Swift": 1728, "C": 1559, "HTML": 1226, "Java": 731, "PowerShell": 695, "Objective-C": 38} | package com.example.mvvmgenerater.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import dagger.android.support.DaggerFragment
abstract class BaseFragment : DaggerFragment() {
@LayoutRes
abstract fun layoutRes(): Int
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(layoutRes(), container, false)
}
} | 0 | Kotlin | 0 | 0 | 1b94a57500bbff939cf7be6fb4a008f5f916b2d0 | 553 | practice-android | MIT License |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/ecs/CfnTaskSetServiceRegistryPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.ecs
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Number
import kotlin.String
import software.amazon.awscdk.services.ecs.CfnService
/**
* The `ServiceRegistry` property specifies details of the service registry.
*
* For more information, see [Service
* Discovery](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-discovery.html) in
* the *Amazon Elastic Container Service Developer Guide* .
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.ecs.*;
* ServiceRegistryProperty serviceRegistryProperty = ServiceRegistryProperty.builder()
* .containerName("containerName")
* .containerPort(123)
* .port(123)
* .registryArn("registryArn")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-serviceregistry.html)
*/
@CdkDslMarker
public class CfnServiceServiceRegistryPropertyDsl {
private val cdkBuilder: CfnService.ServiceRegistryProperty.Builder =
CfnService.ServiceRegistryProperty.builder()
/**
* @param containerName The container name value to be used for your service discovery service.
* It's already specified in the task definition. If the task definition that your service task
* specifies uses the `bridge` or `host` network mode, you must specify a `containerName` and
* `containerPort` combination from the task definition. If the task definition that your service
* task specifies uses the `awsvpc` network mode and a type SRV DNS record is used, you must specify
* either a `containerName` and `containerPort` combination or a `port` value. However, you can't
* specify both.
*/
public fun containerName(containerName: String) {
cdkBuilder.containerName(containerName)
}
/**
* @param containerPort The port value to be used for your service discovery service.
* It's already specified in the task definition. If the task definition your service task
* specifies uses the `bridge` or `host` network mode, you must specify a `containerName` and
* `containerPort` combination from the task definition. If the task definition your service task
* specifies uses the `awsvpc` network mode and a type SRV DNS record is used, you must specify
* either a `containerName` and `containerPort` combination or a `port` value. However, you can't
* specify both.
*/
public fun containerPort(containerPort: Number) {
cdkBuilder.containerPort(containerPort)
}
/**
* @param port The port value used if your service discovery service specified an SRV record.
* This field might be used if both the `awsvpc` network mode and SRV records are used.
*/
public fun port(port: Number) {
cdkBuilder.port(port)
}
/**
* @param registryArn The Amazon Resource Name (ARN) of the service registry.
* The currently supported service registry is AWS Cloud Map . For more information, see
* [CreateService](https://docs.aws.amazon.com/cloud-map/latest/api/API_CreateService.html) .
*/
public fun registryArn(registryArn: String) {
cdkBuilder.registryArn(registryArn)
}
public fun build(): CfnService.ServiceRegistryProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 3,529 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/recycler/kotlinvolley/network/VolleySingletion.kt | Manuaravind1989 | 109,162,163 | false | null | package com.recycler.kotlinvolley.network
import android.content.Context
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley
/**
* Created by Manu on 10/30/2017.
*/
object VolleySingletion{
private lateinit var context: Context
val requestQueque : RequestQueue by lazy {
Volley.newRequestQueue(context)
}
val imageLoader : ImageLoader by lazy {
ImageLoader(requestQueque,LruBtimapCache() )
}
fun initConfi(context:Context){
this.context =context.applicationContext
}
} | 0 | Kotlin | 2 | 4 | dda731e5e942fde7a425a7093706e13388ac4390 | 611 | Kotlin-Volley | MIT License |
aoc2018/aoc2018-kotlin/src/main/kotlin/de/havox_design/aoc2018/day22/Region.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 967489, "Java": 684008, "Scala": 57186, "Groovy": 40975, "Python": 25970} | package de.havox_design.aoc2018.day22
import de.havox_design.aoc.utils.kotlin.model.positions.Position2d
import de.havox_design.aoc.utils.kotlin.model.positions.north
import de.havox_design.aoc.utils.kotlin.model.positions.west
data class Region(val point: Position2d<Int>, val cave: HardCave) {
val geologicIndex: Int by lazy { deriveGeologicIndex() }
val erosionLevel: Int by lazy { (geologicIndex + cave.depth) % 20183 }
val regionType: RegionType by lazy { RegionType.entries[erosionLevel % 3] }
private val atEnds = point in setOf(Position2d(0, 0), cave.target)
private fun deriveGeologicIndex() =
when {
atEnds -> 0
point.y == 0 -> point.x * 16807
point.x == 0 -> point.y * 48271
else -> (cave.at(point.west()) to cave.at(point.north()))
.let { it.first.erosionLevel * it.second.erosionLevel }
}
fun toolsRequired(): Set<Tool> = if (atEnds) setOf(Tool.TORCH) else
when (regionType) {
RegionType.ROCKY -> setOf(Tool.CLIMBING_GEAR, Tool.TORCH)
RegionType.WET -> setOf(Tool.CLIMBING_GEAR, Tool.NEITHER)
RegionType.NARROW -> setOf(Tool.TORCH, Tool.NEITHER)
}
}
| 5 | Kotlin | 0 | 1 | 9194612efb3a126067b330493fbcb62dddb603b0 | 1,225 | advent-of-code | Apache License 2.0 |
src/test/kotlin/g0601_0700/s0698_partition_to_k_equal_sum_subsets/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0601_0700.s0698_partition_to_k_equal_sum_subsets
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun canPartitionKSubsets() {
assertThat(
Solution().canPartitionKSubsets(intArrayOf(4, 3, 2, 3, 5, 2, 1), 4),
equalTo(true)
)
}
@Test
fun canPartitionKSubsets2() {
assertThat(Solution().canPartitionKSubsets(intArrayOf(1, 2, 3, 4), 3), equalTo(false))
}
}
| 0 | Kotlin | 20 | 43 | 471d45c60f669ea1a2e103e6b4d8d54da55711df | 544 | LeetCode-in-Kotlin | MIT License |
common/compose/src/main/kotlin/team/duckie/app/android/common/compose/ui/constant/icon.kt | duckie-team | 503,869,663 | false | {"Kotlin": 1819917} | /*
* Designed and developed by Duckie Team, 2022
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE
*/
package team.duckie.app.android.common.compose.ui.constant
typealias SharedIcon = team.duckie.app.android.common.compose.R.drawable
| 32 | Kotlin | 1 | 8 | 5dbd5b7a42c621931d05a96e66431f67a3a50762 | 313 | duckie-android | MIT License |
lib/src/main/kotlin/org/aklimov/fall_analytics/lib/services/domain/AlreadyLoadedInfo.kt | alexandrklimov | 307,780,500 | false | null | package org.aklimov.fall_analytics.lib.services.domain
import java.time.LocalDate
data class AlreadyLoadedInfo(val tradeDate: LocalDate, val lastRowNum: Long)
| 0 | Kotlin | 0 | 0 | f39c7b548139cce7e4c94c44690ffd7c2949db52 | 161 | fall_analytics | MIT License |
src/main/kotlin/com/example/utils/Utils.kt | u9g | 557,349,138 | false | {"Kotlin": 190433, "Java": 4574} | package com.example.utils
import com.example.config.Config
import com.example.core.Feature
import com.example.misc.scheduler.NewScheduler
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.ScaledResolution
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.util.MathHelper
import net.minecraft.util.ResourceLocation
import org.apache.commons.io.IOUtils
import org.lwjgl.opengl.GL11
import java.awt.geom.Point2D
import java.io.BufferedInputStream
import java.io.IOException
import javax.vecmath.Vector3d
object Utils {
@Throws(IOException::class)
fun toByteArray(inputStream: BufferedInputStream) = inputStream.use { IOUtils.toByteArray(it) }!!
fun getPartialTicks() = Minecraft.getMinecraft().timer.renderPartialTicks
fun getCurrentTick() = NewScheduler.INSTANCE.totalTicks
private val interpolatedPlayerPosition = Vector3d()
private var lastTick: Long = 0
private var lastPartialTicks = 0f
var blockNextClick: Boolean = false
fun getPlayerViewPosition(): Vector3d {
val currentTick: Long = getCurrentTick()
val currentPartialTicks: Float = getPartialTicks()
if (currentTick != lastTick || currentPartialTicks != lastPartialTicks) {
val renderViewEntity = Minecraft.getMinecraft().renderViewEntity
interpolatedPlayerPosition.x = MathUtils.interpolateX(renderViewEntity, currentPartialTicks)
interpolatedPlayerPosition.y = MathUtils.interpolateY(renderViewEntity, currentPartialTicks)
interpolatedPlayerPosition.z = MathUtils.interpolateZ(renderViewEntity, currentPartialTicks)
lastTick = currentTick
lastPartialTicks = currentPartialTicks
}
return interpolatedPlayerPosition
}
private var depthEnabled = false
private var blendEnabled = false
private var alphaEnabled = false
private var blendFunctionSrcFactor = 0
private var blendFunctionDstFactor = 0
fun enableStandardGLOptions() {
depthEnabled = GL11.glIsEnabled(GL11.GL_DEPTH_TEST)
blendEnabled = GL11.glIsEnabled(GL11.GL_BLEND)
alphaEnabled = GL11.glIsEnabled(GL11.GL_ALPHA_TEST)
blendFunctionSrcFactor = GL11.glGetInteger(GL11.GL_BLEND_SRC)
blendFunctionDstFactor = GL11.glGetInteger(GL11.GL_BLEND_DST)
GlStateManager.disableDepth()
GlStateManager.enableBlend()
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA)
GlStateManager.enableAlpha()
GlStateManager.color(1f, 1f, 1f, 1f)
}
fun restoreGLOptions() {
if (depthEnabled) {
GlStateManager.enableDepth()
}
if (!alphaEnabled) {
GlStateManager.disableAlpha()
}
if (!blendEnabled) {
GlStateManager.disableBlend()
}
GlStateManager.blendFunc(blendFunctionSrcFactor, blendFunctionDstFactor)
}
fun playSound(sound: String, volume: Double, pitch: Double) {
Minecraft.getMinecraft().thePlayer.playSound(sound, volume.toFloat(), pitch.toFloat())
}
/**
* Rounds a float value for when it is being displayed as a string.
*
*
* For example, if the given value is 123.456789 and the decimal places is 2, this will round
* to 1.23.
*
* @param value The value to round
* @param decimalPlaces The decimal places to round to
* @return A string representation of the value rounded
*/
fun roundForString(value: Float, decimalPlaces: Int): String? {
return String.format("%." + decimalPlaces + "f", value)
}
fun setClosestAnchorPoint(feature: Feature) {
val x1: Float = feature.getActualX()
val y1: Float = feature.getActualY()
val sr = ScaledResolution(Minecraft.getMinecraft())
val maxX = sr.scaledWidth
val maxY = sr.scaledHeight
var shortestDistance = -1.0
var closestAnchorPoint = Config.AnchorPoint.BOTTOM_MIDDLE // default
for (point in Config.AnchorPoint.values()) {
val distance = Point2D.distance(x1.toDouble(), y1.toDouble(), point.getX(maxX).toDouble(), point.getY(maxY).toDouble())
if (shortestDistance == -1.0 || distance < shortestDistance) {
closestAnchorPoint = point
shortestDistance = distance
}
}
if (feature.anchorPoint === closestAnchorPoint) {
return
}
val targetX: Float = feature.getActualX()
val targetY: Float = feature.getActualY()
val x: Float = targetX - closestAnchorPoint.getX(maxX)
val y: Float = targetY - closestAnchorPoint.getY(maxY)
feature.anchorPoint = closestAnchorPoint
feature.coordinates = Pair(x, y)
}
fun normalizeValueNoStep(value: Float): Float {
return MathHelper.clamp_float(
(snapNearDefaultValue(value) - Config.GUI_SCALE_MINIMUM) / (Config.GUI_SCALE_MAXIMUM - Config.GUI_SCALE_MINIMUM),
0.0f,
1.0f
)
}
private fun snapNearDefaultValue(value: Float): Float {
return if (value != 1f && value > 1 - 0.05 && value < 1 + 0.05) {
1f
} else value
}
val ICONS = ResourceLocation("examplemod", "craftingpatterns.png")
} | 0 | Kotlin | 0 | 0 | 24da64379848220297ec15095df6b54d41fbb5b1 | 5,307 | sba-gui | The Unlicense |
app/src/main/java/demo/bookssample/repository/BooksRepository.kt | kristiankosharov | 152,720,078 | false | null | package demo.bookssample.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import demo.bookssample.AppExecutors
import demo.bookssample.OpenForTesting
import demo.bookssample.api.BooksService
import demo.bookssample.db.BooksDao
import demo.bookssample.entity.ApiResponse
import demo.bookssample.entity.Book
import demo.bookssample.entity.BooksResponse
import demo.bookssample.entity.Resource
import java.util.logging.Logger
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
@OpenForTesting
class BooksRepository @Inject constructor(
private val appExecutors: AppExecutors,
private val booksDao: BooksDao,
private val booksService: BooksService
) {
private val logger = Logger.getLogger(BooksRepository::class.java.name)
fun loadNewReleasedBooks(): LiveData<Resource<BooksResponse>> {
return object : NetworkBoundResource<BooksResponse, BooksResponse>(appExecutors) {
override fun onFetchFailed() {
super.onFetchFailed()
logger.info("Fetch fail")
}
// Clear all records with empty status to remove out-of-date records
override fun saveCallResult(item: BooksResponse) {
logger.info("SAVE FROM API ${item.books.size}")
booksDao.clearNewStatus()
for (book in item.books) {
book.newStatus = 1
}
booksDao.insert(item.books)
}
override fun shouldFetch(data: BooksResponse?): Boolean {
return true
}
override fun loadFromDb(): LiveData<BooksResponse> {
logger.info("LOAD FROM DB")
return Transformations
.map(booksDao.getNewReleasedBooks()) {
val total: Int = it?.size ?: 1
val books: List<Book> = it ?: ArrayList()
return@map BooksResponse(0, total, 1, books as ArrayList<Book>)
}
}
override fun createCall(): LiveData<ApiResponse<BooksResponse>> {
logger.info("CALL NEW RELEASED BOOKS")
return booksService.getNewReleasedBooks()
}
}.asLiveData()
}
} | 0 | Kotlin | 1 | 0 | 1f06be7365dfbdbf24987ad9fcc8e34d76844a6e | 2,337 | ITBooksStore | Apache License 2.0 |
android_app/app/src/main/java/com/pwr/sailapp/data/sail/RentalState.kt | Torak28 | 178,792,740 | false | null | package com.pwr.sailapp.data.sail
enum class RentalState {
RENTAL_SUCCESSFUL, RENTAL_FAILED
} | 9 | Kotlin | 3 | 0 | bee89576ab853d88aed11748cc9d596fad59668e | 98 | SailApp | MIT License |
app/src/main/java/ru/zzemlyanaya/pulsepower/app/navigation/NavigationRouter.kt | zzemlyanaya | 786,938,180 | false | {"Kotlin": 151814} | package ru.zzemlyanaya.pulsepower.app.navigation
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.flow.*
import ru.zzemlyanaya.pulsepower.app.navigation.MainDirections.back
import ru.zzemlyanaya.pulsepower.app.navigation.MainDirections.default
class NavigationRouter {
private val _commands = MutableLiveData(default)
val commands: LiveData<NavigationCommand> = _commands
private val resultListeners: HashMap<Int, ResultListener> = hashMapOf()
fun <T> getCurrentArgs() = _commands.value?.args?.firstOrNull() as? T
fun navigateTo(directions: NavigationCommand) {
_commands.postValue(directions)
}
fun back() {
_commands.postValue(back)
}
@Suppress("UNCHECKED_CAST")
fun <T> addResultListener(id: Int, listener: (T) -> Unit) {
resultListeners[id] = object : ResultListener {
override fun onResult(result: Any) {
(result as? T)?.let { listener(it) }
}
}
}
fun removeResultListener(id: Int) {
resultListeners.remove(id)
}
fun sendResult(id: Int, result: Any) {
resultListeners[id]?.onResult(result)
}
fun sendResultAll(result: Any) {
resultListeners.values.forEach { it.onResult(result) }
}
}
interface ResultListener {
fun onResult(result: Any)
} | 0 | Kotlin | 0 | 1 | 0ee15b97bffd735ed65655e09879339ebc0e0b68 | 1,378 | PulseAndPower | Apache License 2.0 |
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/gadget/SelectWorktopOptionRsp.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 1651536} | package org.anime_game_servers.multi_proto.gi.data.gadget
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.Version.GI_CB1
import org.anime_game_servers.core.base.annotations.proto.CommandType.RESPONSE
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
import org.anime_game_servers.multi_proto.gi.data.general.Retcode
@AddedIn(GI_CB1)
@ProtoCommand(RESPONSE)
internal interface SelectWorktopOptionRsp {
var retCode: Retcode
var gadgetEntityId: Int
var optionId: Int
} | 0 | Kotlin | 2 | 6 | 7639afe4f546aa5bbd9b4afc9c06c17f9547c588 | 552 | anime-game-multi-proto | MIT License |
app/src/main/java/com/syleiman/myfootprints/presentationLayer/customComponents/MainButton.kt | AlShevelev | 116,675,999 | false | null | package com.syleiman.myfootprints.presentationLayer.customComponents
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.syleiman.myfootprints.R
/** One button for main activity */
class MainButton : LinearLayout
{
private var buttonIcon: ImageView? = null
private var buttonText: TextView? = null
/** */
constructor(context: Context) : super(context)
{
initComponent()
}
/** */
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
{
initComponent()
initAttributes(context, attrs)
}
/** */
private fun initComponent()
{
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.cc_main_button, this)
buttonIcon = findViewById(R.id.buttonIcon) as ImageView
buttonText = findViewById(R.id.buttonText) as TextView
}
/** Init custom attributes */
private fun initAttributes(context: Context, attrs: AttributeSet)
{
val a = context.obtainStyledAttributes(attrs, R.styleable.MainButton)
val totalAttributes = a.indexCount
(0..totalAttributes - 1)
.map { a.getIndex(it) }
.forEach {
when (it)
{
R.styleable.MainButton_mainButtonText -> buttonText!!.text = a.getString(it)
R.styleable.MainButton_mainButtonIcon ->
{
val icon = a.getDrawable(it)
if (icon != null)
buttonIcon!!.setImageDrawable(icon)
}
}
}
a.recycle()
}
} | 1 | Kotlin | 1 | 2 | 11a243900f3a33b4b3aab358d4a2b08f9759dd8e | 1,863 | MyFootprints | MIT License |
feature-nft-api/src/main/java/jp/co/soramitsu/nft/domain/models/NFTCollection.kt | soramitsu | 278,060,397 | false | null | package jp.co.soramitsu.nft.domain.models
import jp.co.soramitsu.core.models.ChainId
sealed interface NFTCollection {
interface Reloading : NFTCollection {
companion object : Reloading
}
interface Loaded : NFTCollection {
val chainId: ChainId
val chainName: String
interface Result : Loaded {
interface Collection : Result {
val contractAddress: String
val collectionName: String
val description: String
val imageUrl: String
val type: String
val balance: Int
val collectionSize: Int
interface WithTokens : Collection {
val tokens: Sequence<NFT>
}
}
class Empty(
override val chainId: ChainId,
override val chainName: String
) : Result
}
class WithFailure(
override val chainId: ChainId,
override val chainName: String,
val throwable: Throwable
) : Loaded
}
}
| 15 | null | 30 | 89 | 1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2 | 1,130 | fearless-Android | Apache License 2.0 |
openweather/src/test/java/np/info/ngima/openweather/WeatherRepositoryTest.kt | ngima | 367,954,042 | false | null | package np.info.ngima.openweather
import com.google.gson.Gson
import io.reactivex.Observable
import io.reactivex.observers.TestObserver
import np.info.ngima.openweather.data.api.WeatherApi
import np.info.ngima.openweather.models.weather_response.WeatherResponse
import np.info.ngima.openweather.repo.WeatherRepository
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class WeatherRepositoryTest {
var weatherResponseString =
"{ \"coord\": { \"lon\": -10.5932, \"lat\": 6.6518 }, \"weather\": [ { \"id\": 803, \"main\": \"Clouds\", \"description\": \"broken clouds\", \"icon\": \"04n\" } ], \"base\": \"stations\", \"main\": { \"temp\": 23, \"feels_like\": 23.81, \"temp_min\": 23, \"temp_max\": 23, \"pressure\": 1011, \"humidity\": 94 }, \"visibility\": 10000, \"wind\": { \"speed\": 1.5, \"deg\": 278, \"gust\": 4.64 }, \"clouds\": { \"all\": 75 }, \"dt\": 1621199755, \"sys\": { \"type\": 1, \"id\": 2389, \"country\": \"LR\", \"sunrise\": 1621146361, \"sunset\": 1621191100 }, \"timezone\": 0, \"id\": 2274890, \"name\": \"New\", \"cod\": 200 }"
var weatherResponseNotFoundString = "{ \"cod\": \"404\", \"message\": \"city not found\" }"
var CITY_NEW = "New"
var CITY_INVALID = "Invalid"
@Mock
lateinit var weatherApi: WeatherApi
lateinit var weatherRepository: WeatherRepository
lateinit var weatherResponse: WeatherResponse
lateinit var weatherResponseNotFound: WeatherResponse
lateinit var testObserver: TestObserver<WeatherResponse>
@Before
fun setUp() {
weatherResponse = Gson().fromJson(weatherResponseString, WeatherResponse::class.java)
weatherResponseNotFound = Gson().fromJson(
weatherResponseNotFoundString,
WeatherResponse::class.java
)
Mockito.`when`(weatherApi.getWeatherByCity(CITY_NEW))
.thenReturn(Observable.just(weatherResponse))
Mockito.`when`(weatherApi.getWeatherByCity(CITY_INVALID))
.thenReturn(Observable.just(weatherResponseNotFound))
weatherRepository = WeatherRepository(weatherApi)
testObserver = TestObserver()
}
@Test
fun testGetWeatherByInvalidCity() {
weatherRepository.getWeatherByCity(CITY_INVALID)
.subscribe(testObserver)
testObserver
.assertValue(weatherResponseNotFound)
.assertSubscribed()
.assertComplete()
.assertNoErrors()
}
@Test
fun testGetWeatherByCity() {
weatherRepository.getWeatherByCity(CITY_NEW)
.subscribe(testObserver)
testObserver
.assertValue(weatherResponse)
.assertSubscribed()
.assertComplete()
.assertNoErrors()
}
} | 0 | Kotlin | 0 | 0 | f399dacb77edbc8bae79c3b5f9d8d81e86fbd975 | 2,892 | Open-Weather | Apache License 2.0 |
app/src/main/java/com/ifanr/tangzhi/ui/usercontract/UserContractViewModel.kt | cyrushine | 224,551,311 | false | {"Kotlin": 673925, "Java": 59856, "Python": 795} | package com.ifanr.tangzhi.ui.usercontract
import androidx.lifecycle.MutableLiveData
import com.ifanr.tangzhi.ext.ioTask
import com.ifanr.tangzhi.model.BaasContent
import com.ifanr.tangzhi.repository.baas.BaasRepository
import com.ifanr.tangzhi.ui.base.BaseViewModel
import com.ifanr.tangzhi.util.LoadingState
import javax.inject.Inject
class UserContractViewModel @Inject constructor (
private val repository: BaasRepository
): BaseViewModel() {
val contract = MutableLiveData<BaasContent>()
val loading = MutableLiveData<LoadingState>()
val toast = MutableLiveData<String>()
init {
repository.getContentById("1576475282813162")
.ioTask(vm = this, loadingState = loading, loadingDelay = false)
.subscribe({
contract.value = it
}, {
toast.value = "用户协议加载异常(${it.message})"
})
}
} | 0 | Kotlin | 0 | 0 | ab9a7a2eba7f53eca918e084da9d9907f7997cee | 895 | tangzhi_android | Apache License 2.0 |
Quiz/app/src/main/java/com/example/quiz/view/MainActivity.kt | KamilDonda | 321,666,752 | false | null | package com.example.quiz.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.quiz.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | 0 | Kotlin | 0 | 1 | 755580ba0eefe3e44ed12096a60b15bcd0a3b826 | 328 | QuizzzyMobile | MIT License |
core/src/main/java/com/qlk/core/adapter/viewholder/LazyLoadViewHolder.kt | QiLiKing | 205,133,603 | false | {"Gradle": 5, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "INI": 3, "Proguard": 3, "Kotlin": 69, "XML": 20, "Java": 1} | package com.qlk.core.adapter.viewholder
import android.view.View
import com.qlk.core.ILazyLoader
import com.qlk.core.isInDebugMode
/**
*
* QQ:1055329812
* Created by QiLiKing on 2019-07-17.
*
* @see LifecycleViewHolder
*/
abstract class LazyLoadViewHolder<T>(itemView: View) : LifecycleViewHolder(itemView),
ILazyLoader<T> {
// private val taskExecutor by lazy { OrderTask<Int>(this) }
/**
* Adapter stop scrolling, and you can do your heavy work now<br/>
*
* When working, you should check the "isActive" state to suspend your heavy work
*
* NOT be called if the ViewHolder has been detached from window before RecycleView stopping scroll
*/
override fun onLazyLoad(t: T) {
// if (this::taskExecutor.initialized) {
// taskExecutor.runTasks()
// }
if (isInDebugMode) println("LazyLoadViewHolder#onLazyLoad:27-> t=$t pos=$adapterPosition")
}
// /**
// * You should entrust your tasks in {@method onPrimaryLoad}, and they will be executed in {@method onLazyLoad} automatically.
// *
// * @param task you should check "isActive" state when trying to update UI. Or where before a long time task starts.
// */
// protected fun entrustLazyTask(order: Int, task: SimpleCoroutineTask) {
// taskExecutor.setTask(order, task)
// }
/* Task Delegate */
// private var taskPool: MutableList<ISimpleTask>? = null
// private var suspendTasks: MutableList<ISimpleTask>? = null
// private var runningTasks: HashMap<Job, ISimpleTask>? = null
// private var nextTaskIndex = 0
// private var maxThreadCount: Int = MAX_THREAD_COUNT
//
// /**
// * clear task pool and add new tasks to it.
// *
// * Entrust your background tasks, that should do in onLazyLoad() method, to parent.<br/>
// *
// * If some of the tasks are suspended by state, they will be continue executed when resumed.<br/>
// *
// * All tasks will be executed again every time when onPrimaryLoad() method called.
// * Before do this, the tasks that wake up by upper step will be canceled firstly.
// *
// * @param tasks you should check "isActive" state when trying to update UI in each task. Or where before a long time task starts.
// */
// protected fun entrustLazyTasks(vararg tasks: ISimpleTask /* false to retry when resumed */) {
// if (isActive) throw IllegalThreadStateException("You should not call entrustLazyTasks when isActive == true, use entrustLazyTask() instead ")
// obtainTaskPool().run {
// clear()
// addAll(tasks)
// }
//
// suspendTasks?.clear()
// }
//
// protected fun setMaxThreadCount(
// @IntRange(
// from = MIN_THREAD_COUNT.toLong(),
// to = MAX_THREAD_COUNT.toLong()
// ) maxCount: Int
// ) {
// maxThreadCount = maxCount
// }
//
// /**
// * be ready for next binding progress
// */
// private fun resetTasks() {
// taskPool = null
// suspendTasks = null
// runningTasks = null // canceled by onInactive() method, so set to null directly
//
// nextTaskIndex = 0
//// maxThreadCount = MAX_THREAD_COUNT //should keep this setting
// }
//
// private fun runTaskPool() {
// val pool = taskPool ?: return
// for (index in 0 until min(maxThreadCount(), pool.size)) {
// nextTaskIndex++
// val task = pool[index]
// GlobalScope.launch {
// task.invoke()
// }.also { job ->
// obtainRunningTasks()[job] = task
// job.invokeOnCompletion { error ->
// if (error == null) {
// runningTasks?.remove(job)
// } else {
// obtainSuspendTasks().add(task)
// }
// }
// }
// }
// }
//
// protected fun addTask(order: Int, task: ISimpleTask) {
// val pool = taskPool ?: return
// for (index in 0 until min(maxThreadCount(), pool.size)) {
// nextTaskIndex++
// val task = pool[index]
// GlobalScope.launch {
// task.invoke(v)
// }.also { job ->
// obtainRunningTasks()[job] = task
// job.invokeOnCompletion { error ->
// if (error == null) {
// obtainRunningTasks().remove(job)
// } else {
// obtainSuspendTasks().add(task)
// }
// }
// }
// }
// }
//
// private fun obtainTaskPool(): MutableList<ISimpleTask> =
// taskPool ?: mutableListOf<ISimpleTask>().also { taskPool = it }
//
// private fun obtainSuspendTasks(): MutableList<ISimpleTask> =
// suspendTasks ?: mutableListOf<ISimpleTask>().also { suspendTasks = it }
//
// private fun obtainRunningTasks(): HashMap<Job, ISimpleTask> =
// runningTasks ?: HashMap<Job, ISimpleTask>().also { runningTasks = it }
//
// companion object {
// const val DEFAULT_ACTIVE = true
// const val MIN_THREAD_COUNT = 1
// const val MAX_THREAD_COUNT = 5
// }
} | 1 | null | 1 | 1 | 8c1fc6284aaa16605cf9409563a6381aa1343bce | 5,251 | Smart-Library | Apache License 2.0 |
app/src/main/java/com/github/stephenwanjala/multiply/domain/usecase/StartGame.kt | stephenWanjala | 738,520,186 | false | {"Kotlin": 32704} | package com.github.stephenwanjala.multiply.domain.usecase
import com.github.stephenwanjala.multiply.domain.model.Game
import com.github.stephenwanjala.multiply.domain.model.repository.GameRepository
class StartGame (private val gameRepository: GameRepository) {
operator fun invoke(): Game =
gameRepository.startNewGame()
} | 0 | Kotlin | 0 | 0 | a5d392c423d6999de5a5ff9cef1f143553ea0636 | 337 | Multiply | MIT License |
ui/lists/src/androidUnitTest/kotlin/dev/alvr/katana/ui/lists/viewmodel/MangaListsViewModelTest.kt | alvr | 446,535,707 | false | null | package dev.alvr.katana.ui.lists.viewmodel
import androidx.lifecycle.SavedStateHandle
import arrow.core.left
import arrow.core.right
import dev.alvr.katana.common.core.empty
import dev.alvr.katana.common.core.zero
import dev.alvr.katana.common.tests.TestBase
import dev.alvr.katana.common.tests.coEitherJustRun
import dev.alvr.katana.domain.base.usecases.invoke
import dev.alvr.katana.domain.lists.failures.ListsFailure
import dev.alvr.katana.domain.lists.models.MediaCollection
import dev.alvr.katana.domain.lists.models.entries.MediaEntry
import dev.alvr.katana.domain.lists.models.lists.MediaList
import dev.alvr.katana.domain.lists.models.lists.MediaListGroup
import dev.alvr.katana.domain.lists.usecases.ObserveMangaListUseCase
import dev.alvr.katana.domain.lists.usecases.UpdateListUseCase
import dev.alvr.katana.ui.lists.entities.MediaListItem
import dev.alvr.katana.ui.lists.entities.UserList
import io.kotest.assertions.throwables.shouldThrowExactlyUnit
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.collections.shouldContainInOrder
import io.kotest.matchers.collections.shouldHaveSize
import io.mockk.Ordering
import io.mockk.coJustRun
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.impl.annotations.SpyK
import io.mockk.verify
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.stream.Stream
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
import org.orbitmvi.orbit.SuspendingTestContainerHost
import org.orbitmvi.orbit.test
private typealias MangaState = ListState<MediaListItem.MangaListItem>
@ExperimentalCoroutinesApi
internal class MangaListsViewModelTest : TestBase() {
@MockK
private lateinit var observeManga: ObserveMangaListUseCase
@MockK
private lateinit var updateList: UpdateListUseCase
@SpyK
private var stateHandle = SavedStateHandle()
private lateinit var viewModel:
SuspendingTestContainerHost<ListState<MediaListItem.MangaListItem>, Nothing, MangaListsViewModel>
private val initialStateWithLists: Array<MangaState.() -> MangaState>
get() = arrayOf(
{ copy(isLoading = true) },
{
copy(
isLoading = false,
isEmpty = false,
name = "MyCustomMangaList",
items = persistentListOf(mangaListItem1),
isError = false,
)
},
)
override suspend fun beforeEach() {
viewModel = MangaListsViewModel(stateHandle, updateList, observeManga).test(ListState())
}
@Nested
@DisplayName("WHEN initializing the viewModel")
inner class Init {
@Nested
@DisplayName("AND the collections are empty")
inner class Empty {
@Test
@DisplayName("THEN the collections observed should are empty")
fun `the collections are empty`() = runTest {
// GIVEN
val initialState: Array<MangaState.() -> MangaState> = arrayOf(
{ copy(isLoading = true) },
{
copy(
isLoading = false,
isEmpty = true,
items = persistentListOf(),
)
},
)
every { observeManga.flow } returns flowOf(
MediaCollection<MediaEntry.Manga>(lists = emptyList()).right(),
)
coJustRun { observeManga() }
// WHEN
viewModel.runOnCreate()
// THEN
viewModel.assert(MangaState()) { states(*initialState) }
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) {
stateHandle["collection"] = emptyMap<String, List<MediaListItem>>()
stateHandle["userLists"] = emptyArray<String>()
stateHandle.get<String>("collection")
}
}
}
@Test
@DisplayName("AND the manga collection has entries THEN it should update its state with the mapped entry")
fun `the manga collection has entries`() = runTest {
// GIVEN
mockMangaFlow()
// WHEN
viewModel.runOnCreate()
// THEN
viewModel.assert(MangaState()) { states(*initialStateWithLists) }
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) {
verifyStateHandle()
stateHandle.get<String>("collection")
}
}
@Test
@DisplayName(
"""
AND the manga collection has entries
AND getting the userLists
THEN the list should contain one element
""",
)
fun `the manga collection has entries AND getting the userLists`() = runTest {
// GIVEN
mockMangaFlow()
// WHEN
viewModel.runOnCreate()
viewModel.testIntent {
userLists
.shouldHaveSize(2)
.shouldContainInOrder(UserList("MyCustomMangaList" to 1), UserList("MyCustomMangaList2" to 1))
}
// THEN
viewModel.assert(MangaState()) { states(*initialStateWithLists) }
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) {
verifyStateHandle()
stateHandle.get<String>("collection")
stateHandle.get<Array<String>>("userLists")
}
}
@Test
@DisplayName("AND something went wrong collecting THEN update it state with isError = true")
fun `something went wrong collecting`() = runTest {
// GIVEN
every { observeManga.flow } returns flowOf(ListsFailure.GetMediaCollection.left())
coJustRun { observeManga() }
// WHEN
viewModel.runOnCreate()
// THEN
viewModel.assert(MangaState()) {
states(
{ copy(isLoading = true) },
{ copy(isError = true, isLoading = false, isEmpty = true) },
)
}
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
}
@Test
@DisplayName("AND the array of manga list names is non-existent THEN the array should be empty")
fun `the array of manga list names is non-existent`() = runTest {
// GIVEN
every { stateHandle.get<Array<String>>("userLists") } returns null
// WHEN
viewModel.testIntent { userLists.shouldBeEmpty() }
// THEN
verify(exactly = 1) { stateHandle.get<Array<String>>("userLists") }
}
}
@Nested
@DisplayName("WHEN adding a +1 to an entry")
inner class PlusOne {
@Test
@DisplayName("AND is successful THEN it should call the updateList with the progress incremented by 1")
fun `is successful`() = runTest {
// GIVEN
mockMangaFlow()
coEitherJustRun { updateList(any()) }
// WHEN
viewModel.runOnCreate()
viewModel.testIntent { addPlusOne(mangaListItem1.entryId) }
// THEN
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) {
verifyStateHandle()
stateHandle.get<String>("collection")
}
coVerify(exactly = 1) {
updateList(
MediaList(
id = Int.zero,
score = Double.zero,
progress = 234,
progressVolumes = Int.zero,
repeat = Int.zero,
private = false,
notes = String.empty,
hiddenFromStatusLists = false,
startedAt = LocalDate.MAX,
completedAt = LocalDate.MAX,
updatedAt = LocalDateTime.MAX,
),
)
}
}
@Test
@DisplayName("AND the element is not found THEN it should throw `NoSuchElementException`")
fun `the element is not found`() = runTest {
// GIVEN
mockMangaFlow()
// WHEN
viewModel.runOnCreate()
viewModel.testIntent {
// THEN
shouldThrowExactlyUnit<NoSuchElementException> { addPlusOne(234) }
}
// THEN
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) {
verifyStateHandle()
stateHandle.get<String>("collection")
}
}
}
@Nested
@DisplayName("WHEN searching")
inner class Searching {
@Test
@DisplayName(
"""
AND the manga collection has entries
AND try to fetch a existent manga list
THEN the state should be updated
""",
)
fun `the manga collection has entries AND try to fetch a existent manga list`() = runTest {
// GIVEN
mockMangaFlow()
// WHEN
viewModel.runOnCreate()
viewModel.testIntent { selectList("MyCustomMangaList2") }
// THEN
viewModel.assert(MangaState()) {
states(
*initialStateWithLists,
{
copy(
name = "MyCustomMangaList2",
items = persistentListOf(mangaListItem2),
)
},
)
}
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) { verifyStateHandle() }
verify(exactly = 2) {
stateHandle.get<ListsCollection<MediaListItem.MangaListItem>>("collection")
}
}
@Test
@DisplayName("AND try to select a non-existent manga list THEN the state should be the same")
fun `try to select a non-existent manga list`() = runTest {
// GIVEN
mockMangaFlow()
// WHEN
viewModel.runOnCreate()
viewModel.testIntent { selectList("NonExistent Manga List") }
// THEN
viewModel.assert(MangaState()) {
states(
*initialStateWithLists + emptyArray(), // No more state updates
)
}
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) { verifyStateHandle() }
verify(exactly = 2) {
stateHandle.get<ListsCollection<MediaListItem.MangaListItem>>("collection")
}
}
@Test
@DisplayName("AND the collection of manga is non-existent THEN the state should be the same")
fun `the collection of manga is non-existent`() = runTest {
// GIVEN
every { stateHandle.get<ListsCollection<MediaListItem.MangaListItem>>(any()) } returns null
// WHEN
viewModel.testIntent { selectList("MyCustomMangaList") }
// THEN
viewModel.assert(MangaState())
verify(exactly = 1) {
stateHandle.get<ListsCollection<MediaListItem.MangaListItem>>("collection")
}
}
@ArgumentsSource(SearchArguments::class)
@ParameterizedTest(name = "AND searching for {0} THEN the result should be {2}")
fun `searching an entry`(
text: String,
empty: Boolean,
result: ImmutableList<MediaListItem.MangaListItem>,
) = runTest {
// GIVEN
mockMangaFlow()
// WHEN
viewModel.runOnCreate()
viewModel.testIntent { search(text) }
// THEN
viewModel.assert(MangaState()) {
states(
*initialStateWithLists,
{
copy(
isLoading = false,
isEmpty = empty,
items = result,
)
},
)
}
verify(exactly = 1) { observeManga() }
verify(exactly = 1) { observeManga.flow }
verify(ordering = Ordering.ORDERED) {
verifyStateHandle()
stateHandle.get<String>("collection")
}
}
}
private fun mockMangaFlow() {
every { observeManga.flow } returns flowOf(
MediaCollection(
lists = listOf(
MediaListGroup(
name = "MyCustomMangaList",
entries = listOf(mangaMediaEntry1),
),
MediaListGroup(
name = "MyCustomMangaList2",
entries = listOf(mangaMediaEntry2),
),
),
).right(),
)
coJustRun { observeManga() }
}
private fun verifyStateHandle() {
stateHandle["collection"] = mapOf(
"MyCustomMangaList" to listOf(mangaListItem1),
"MyCustomMangaList2" to listOf(mangaListItem2),
)
stateHandle["userLists"] = arrayOf(
UserList("MyCustomMangaList" to 1), UserList("MyCustomMangaList2" to 1),
)
}
private class SearchArguments : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<Arguments> =
Stream.of(
Arguments.of("non-existent entry", true, persistentListOf<MediaListItem.MangaListItem>()),
Arguments.of("OnE PiEcE", false, persistentListOf(mangaListItem1)),
)
}
}
| 3 | null | 0 | 48 | 20da01af3f00e4bb6b20903a017a7716f1ecbd3c | 15,158 | katana | Apache License 2.0 |
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/rawg/game/search/GameSearch.kt | OurFriendIrony | 87,706,649 | false | null | package uk.co.ourfriendirony.medianotifier.clients.rawg.game.search
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder("count", "next", "previous", "results", "user_platforms")
class GameSearch {
@get:JsonProperty("count")
@set:JsonProperty("count")
@JsonProperty("count")
var count: Int? = null
@get:JsonProperty("next")
@set:JsonProperty("next")
@JsonProperty("next")
var next: String? = null
@get:JsonProperty("previous")
@set:JsonProperty("previous")
@JsonProperty("previous")
var previous: Any? = null
@get:JsonProperty("results")
@set:JsonProperty("results")
@JsonProperty("results")
var results: List<GameSearchResult>? = null
@get:JsonProperty("user_platforms")
@set:JsonProperty("user_platforms")
@JsonProperty("user_platforms")
var userPlatforms: Boolean? = null
} | 2 | Kotlin | 0 | 1 | 2fe4f780474dd6756a527e5cf1609c7bc27fa2a8 | 957 | MediaNotifier | Apache License 2.0 |
src/main/kotlin/viewModel/canvas/CanvasViewModel.kt | spbu-coding-2023 | 802,501,813 | false | {"Kotlin": 69436} | package viewModel.canvas
import androidx.compose.ui.geometry.Offset
import viewModel.graph.UndirectedViewModel
import viewModel.graph.VertexViewModel
import kotlin.math.abs
class CanvasViewModel(
val graphViewModel: UndirectedViewModel,
var zoom: Float,
var center: Offset,
var canvasSize: Offset,
var isOrientated: Boolean
) {
private val _vertices = graphViewModel.vertices.associateWith { v ->
VertexCanvasViewModel(v, zoom, center, canvasSize)
}.toMutableMap()
private val _edges = graphViewModel.adjacencyList.map { it.value }.flatten().map {
val vertex1 =
_vertices[it.first] ?: throw IllegalStateException("There is no VertexCanvasViewModel for ${it.first}")
val vertex2 =
_vertices[it.second] ?: throw IllegalStateException("There is no VertexCanvasViewModel for ${it.second}")
EdgeCanvasViewModel(vertex1, vertex2, it.color, it.strokeWidth, zoom, showOrientation = isOrientated)
}
val vertices
get() = _vertices.values
val edges
get() = _edges
fun getViews(): Collection<VertexCanvasViewModel> {
if (Config.optimizeCanvas) {
return _vertices.filter { abs(it.value.offset.x) < canvasSize.x && abs(it.value.offset.y) < canvasSize.y }.values
}
return _vertices.values
}
fun createVertex(offset: Offset, center: Offset, zoom: Float) {
val coordinates = offset * (1 / zoom) + center
val viewModel = graphViewModel.createVertex(coordinates) ?: return
_vertices[viewModel] = VertexCanvasViewModel(viewModel, zoom, center, canvasSize)
}
} | 1 | Kotlin | 0 | 2 | 4f95491d00e6247241b62012abde855ce01c5f1c | 1,641 | graphs-graphs-3 | MIT License |
app/src/main/java/com/brins/nba/ui/adapter/BaseNewsImageAdapter.kt | BrinsLee | 278,326,885 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 80, "XML": 43, "Java": 33, "INI": 1} | package com.brins.nba.ui.adapter
import android.app.Activity
import android.widget.ImageView
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.ViewCompat
import com.brins.nba.R
import com.brins.nba.ui.data.BaseMainContentData
import com.brins.nba.ui.data.BaseMainImageData
import com.brins.nba.utils.GlideHelper.GlideHelper
import com.brins.nba.utils.jumpToImageActivity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
/**
* @author lipeilin
* @date 2020/7/20
*/
class BaseNewsImageAdapter(list: MutableList<BaseMainImageData>) :
BaseQuickAdapter<BaseMainImageData, BaseViewHolder>(R.layout.item_news_content, list) {
override fun convert(helper: BaseViewHolder, item: BaseMainImageData) {
}
} | 1 | null | 1 | 1 | 33f09a1ec45da1a2996bf24b30a84589330c85c4 | 812 | nba | Apache License 2.0 |
app/src/main/java/com/example/lessontablepro/dummy.kt | kazarf007 | 607,975,760 | false | null | package com.example.lessontablepro
import com.jaygee.lessonschedule.model.BreakLesson
import com.jaygee.lessonschedule.model.Lesson
import com.jaygee.lessonschedule.model.SerialBreakLesson
/**
* create on 1/3/2023
**/
class InnerLesson(val x : Int ,val y : Int , val label : String) : Lesson {
override fun weekNo() = x
override fun lessonIndex() = y
override fun label() = label
}
class InnerBreakLesson(val y : Int , val label : String , val isBefore : Boolean, val sort : Int) :
SerialBreakLesson {
override fun lessonIndex() = y
override fun label() = label
override fun isBeforeLesson() = isBefore
override fun sort() = sort
}
class Inner2BreakLesson(val x : Int , var y : Int , val label : String , val isBefore : Boolean , val sort : Int) :
BreakLesson {
override fun weekNo() = x
override fun lessonIndex() = y
override fun label() = label
override fun isBeforeLesson() = isBefore
override fun sort() = sort
} | 0 | Kotlin | 0 | 3 | 53f82400006f4d65ee0e0ba8c642215232a3339f | 992 | LessonSchedulePro | Apache License 2.0 |
simter-auth-data/src/main/kotlin/tech/simter/auth/po/Team.kt | simter | 83,630,653 | false | null | package tech.simter.auth.po
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table
import tech.simter.auth.TEAM_TABLE
import tech.simter.auth.po.base.Actor
import tech.simter.auth.po.base.Branch
import tech.simter.auth.po.base.Organization
import java.time.OffsetDateTime
import java.time.temporal.ChronoUnit
/**
* A number of people who do something together as a group.
*
* Its parent organization must be a [Company], [Department], [Team] or its a top [Team] without parent.
* If its parent is a [Team] means this [Team] is a sub [Team].
*
* @author RJ
*/
@Table(TEAM_TABLE)
data class Team(
@Id override val id: Long,
override val status: Organization.Status,
override val code: String,
override val name: String,
override val branch: Branch? = null,
override val company: Company? = null,
override val createOn: OffsetDateTime = OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)
) : Organization {
override val type: Actor.Type
get() = Actor.Type.Team
} | 0 | Kotlin | 1 | 0 | ae55bdf48fc420dc7eeea33648106ff267c0a04d | 1,043 | simter-auth | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.