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
watch/src/main/java/com/mocap/watch/ui/view/RenderPhoneArmCalib.kt
wearable-motion-capture
543,293,184
false
{"Kotlin": 277610}
package com.mocap.watch.ui.view import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.wear.compose.foundation.lazy.ScalingLazyColumn import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Text import com.mocap.watch.ui.DefaultButton import com.mocap.watch.ui.RedButton import com.mocap.watch.viewmodel.DualCalibrationState import kotlinx.coroutines.flow.StateFlow @Composable fun RenderDualCalib( calibStateFlow: StateFlow<DualCalibrationState>, calibTrigger: () -> Unit, calibDone: () -> Unit ) { val calibState by calibStateFlow.collectAsState() ScalingLazyColumn( modifier = Modifier.fillMaxWidth(), //autoCentering = AutoCenteringParams(itemIndex = 0), userScrollEnabled = true ) { item { Text( text = when (calibState) { DualCalibrationState.Idle -> "Hold at 90deg at \n" + "chest height. \n" + "Then, press:" DualCalibrationState.Hold -> "Keep holding at \n" + "chest height" DualCalibrationState.Forward -> "Extend arm \n" + "forward, parallel \n" + "to ground. When vibrating \n" + "pulse stops, wait for final vibration." DualCalibrationState.Phone -> "Wait for\nphone calibration." DualCalibrationState.Error -> "Communication with\nphone failed." }, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.body1 ) } item { DefaultButton( enabled = calibState == DualCalibrationState.Idle, onClick = { calibTrigger() }, text = "Start" ) } item { DualCalibrationStateDisplay( state = calibState, modifier = Modifier.fillMaxWidth() ) } item { RedButton( onClick = { calibDone() }, text = "Exit" ) } } } /** * The simple state display during the calibration procedure of the watch. * Switches between: * Hold, Forward * Up and down are also options, which are not part of the current routine */ @Composable fun DualCalibrationStateDisplay(state: DualCalibrationState, modifier: Modifier = Modifier) { var color = when (state) { DualCalibrationState.Hold -> Color.Red DualCalibrationState.Forward -> Color.Cyan DualCalibrationState.Error -> Color.Red DualCalibrationState.Phone -> Color.Yellow DualCalibrationState.Idle -> Color.Green } Text( modifier = modifier, textAlign = TextAlign.Center, text = state.name, style = MaterialTheme.typography.body1.copy( color = color ) ) }
0
Kotlin
0
2
91f93afd8ac6b61fd21bf09356dc64e8e321636f
3,377
sensor-stream-apps
Apache License 2.0
pleo-antaeus-core/src/test/kotlin/io/pleo/antaeus/core/services/BillingServiceTest.kt
abdoolly
314,131,020
true
{"Kotlin": 34611, "Shell": 861, "Dockerfile": 249}
package io.pleo.antaeus.core.services import io.mockk.* import io.pleo.antaeus.core.exceptions.CurrencyMismatchException import io.pleo.antaeus.core.exceptions.CustomerNotFoundException import io.pleo.antaeus.core.exceptions.NetworkException import io.pleo.antaeus.core.external.PaymentProvider import io.pleo.antaeus.models.* import io.pleo.antaeus.models.Currency import kotlinx.coroutines.Job import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runBlockingTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.lang.Exception import java.math.BigDecimal import java.time.LocalDate import java.time.LocalTime import java.time.ZoneId import java.time.ZonedDateTime import java.util.* class BillingServiceTest { val paymentProvider = mockk<PaymentProvider>() val invoiceService = mockk<InvoiceService>() val customerService = mockk<CustomerService>() val notificationService = mockk<NotificationService>() var billingService: BillingService = BillingService( paymentProvider, invoiceService, customerService, notificationService ) @BeforeEach fun beforeEach() { clearAllMocks() clearStaticMockk() } @Test fun `should clean timer`() { val timer = mockk<Timer>() every { timer.cancel() } just Runs every { timer.purge() } returns 1 billingService.cleanTimer(timer) verifyOrder { timer.cancel() timer.purge() } } @Test fun `should convert zonedDate to Date`() { val zonedDate = ZonedDateTime.now() val date = billingService.zonedDateToDate(zonedDate) assertEquals(Date.from(date.toInstant()), date) } @Test fun `getNextTime should get the 1st day of the next month given any date or not give any date at all`() { val zoned = ZonedDateTime.of( LocalDate.of(2020, 11, 19), LocalTime.of(10, 0, 0), ZoneId.of("CET") ) mockkStatic(ZonedDateTime::class) every { ZonedDateTime.now(ZoneId.of("CET")) } returns zoned // without any params val date = billingService.getNextTime() assertEquals("Tue Dec 01 00:00:00 CET 2020", date.toString()) // with params val nextDate = billingService.getNextTime(zoned.plusMonths(1)) assertEquals("Fri Jan 01 00:00:00 CET 2021", nextDate.toString()) } @Test fun `getNextTime should get the same date if today was the first day`() { val zoned = ZonedDateTime.of( LocalDate.of(2020, 11, 1), LocalTime.of(10, 0, 0), ZoneId.of("CET") ) mockkStatic(ZonedDateTime::class) every { ZonedDateTime.now(ZoneId.of("CET")) } returns zoned val date = billingService.getNextTime() assertEquals("Sun Nov 01 10:00:00 CET 2020", date.toString()) } @Test fun `retryChargeInvoice should retry invoice`() = runBlockingTest { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) val billMocked = mockk<BillingService>() coEvery { billMocked.retryChargeInvoice(invoice) } coAnswers { callOriginal() } coEvery { billMocked.chargeInvoice(invoice) } returns Unit every { billMocked.retryMap } returns mutableMapOf() billMocked.retryChargeInvoice(invoice) coVerify(exactly = 1) { billMocked.chargeInvoice(invoice) } } @Test fun `retryChargeInvoice should not retry invoice more than three times`() = runBlockingTest { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) val adminNotMsg = "There is a network problem in payment provider for invoice ID ${invoice.id}" every { notificationService.notifyAdmin(adminNotMsg) } just Runs val billSpy = spyk(billingService) { coEvery { chargeInvoice(invoice) } just Runs every { retryMap } answers { mutableMapOf(1 to 3) } } billSpy.retryChargeInvoice(invoice) verify { notificationService.notifyAdmin(adminNotMsg) } } @Test fun `chargeInvoice should charge invoice correctly`() = runBlocking { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) every { paymentProvider.charge(invoice) } returns true every { invoiceService.update(invoice.copy(status = InvoiceStatus.PAID)) } returns invoice.copy(status = InvoiceStatus.PAID) val billSpy = spyk(billingService) billSpy.chargeInvoice(invoice) verify { invoiceService.update(invoice.copy(status = InvoiceStatus.PAID)) } } @Test fun `chargeInvoice should notify admin and customer in case customer did not have enough balance in his account`() = runBlocking { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) val adminMsg = "Customer with ID: ${invoice.customerId} has no enough balance to make invoice ${invoice.id}" val customerMsg = "Insufficient balance in your account for invoice ID: ${invoice.id} to be charged" every { paymentProvider.charge(invoice) } returns false every { notificationService.notifyAdmin(adminMsg) } just Runs every { notificationService.notifyCustomer(1, customerMsg) } just Runs val billSpy = spyk(billingService) billSpy.chargeInvoice(invoice) verifyOrder { notificationService.notifyAdmin(adminMsg) notificationService.notifyCustomer(1, customerMsg) } } @Test fun `chargeInvoice should notify admin on CustomerNotFoundException`() = runBlocking { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) val adminMsg = "Customer in invoice with ID: ${invoice.id} does not exist" every { paymentProvider.charge(invoice) } throws CustomerNotFoundException(1) every { notificationService.notifyAdmin(adminMsg) } just Runs val billSpy = spyk(billingService) billSpy.chargeInvoice(invoice) verify { notificationService.notifyAdmin(adminMsg) } } @Test fun `chargeInvoice should notify admin on CurrencyMismatchException`() = runBlocking { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) val adminMsg = "Invoice with ID: ${invoice.id} has mismatching currency invoice currency ${invoice.amount.currency}, customer currency ${Currency.EUR}" every { customerService.fetch(invoice.customerId) } returns Customer(1, Currency.EUR) every { notificationService.notifyAdmin(adminMsg) } just Runs every { paymentProvider.charge(invoice) } throws CurrencyMismatchException(invoice.id, invoice.customerId) val billSpy = spyk(billingService) billSpy.chargeInvoice(invoice) verify { customerService.fetch(invoice.customerId) notificationService.notifyAdmin(adminMsg) } } @Test fun `chargeInvoice should retry on NetworkException`() = runBlocking { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) every { paymentProvider.charge(invoice) } throws NetworkException() val billSpy = spyk(billingService) { coEvery { retryChargeInvoice(invoice) } returns Job() } billSpy.chargeInvoice(invoice) coVerify { billSpy.retryChargeInvoice(invoice) } } @Test fun `chargeInvoice should notify admin on any other unexpected Exception`() = runBlocking { val invoice = Invoice( id = 1, customerId = 1, amount = Money(BigDecimal.ONE, Currency.USD), status = InvoiceStatus.PENDING ) val adminMsg = "Unexpected error happened while processing invoice ID : ${invoice.id}" every { paymentProvider.charge(invoice) } throws Exception() every { notificationService.notifyAdmin(adminMsg) } just Runs val billSpy = spyk(billingService) billSpy.chargeInvoice(invoice) verify { notificationService.notifyAdmin(adminMsg) } } }
0
Kotlin
0
0
6791564c588e255deb1d932764841b849d941a39
9,278
antaeus
Creative Commons Zero v1.0 Universal
presentation/src/main/java/com/anytypeio/anytype/presentation/multiplayer/ShareSpaceViewModel.kt
anyproto
647,371,233
false
{"Kotlin": 10142121, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.presentation.multiplayer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.ObjectWrapper import com.anytypeio.anytype.core_models.multiplayer.ParticipantPermissions import com.anytypeio.anytype.core_models.multiplayer.ParticipantStatus import com.anytypeio.anytype.core_models.primitives.SpaceId import com.anytypeio.anytype.core_utils.ext.msg import com.anytypeio.anytype.domain.base.fold import com.anytypeio.anytype.domain.library.StoreSearchParams import com.anytypeio.anytype.domain.library.StorelessSubscriptionContainer import com.anytypeio.anytype.domain.multiplayer.ChangeSpaceMemberPermissions import com.anytypeio.anytype.domain.multiplayer.GenerateSpaceInviteLink import com.anytypeio.anytype.domain.multiplayer.RemoveSpaceMembers import com.anytypeio.anytype.presentation.common.BaseViewModel import com.anytypeio.anytype.presentation.search.ObjectSearchConstants import javax.inject.Inject import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import timber.log.Timber class ShareSpaceViewModel( private val params: Params, private val generateSpaceInviteLink: GenerateSpaceInviteLink, private val removeSpaceMembers: RemoveSpaceMembers, private val changeSpaceMemberPermissions: ChangeSpaceMemberPermissions, private val container: StorelessSubscriptionContainer ) : BaseViewModel() { val members = MutableStateFlow<List<ShareSpaceMemberView>>(emptyList()) val viewState = MutableStateFlow<ViewState>(ViewState.Init) val commands = MutableSharedFlow<Command>() init { proceedWithGeneratingInviteLink() viewModelScope.launch { container.subscribe( StoreSearchParams( subscription = SHARE_SPACE_SUBSCRIPTION, filters = ObjectSearchConstants.filterParticipants( spaces = listOf(params.space.id) ), sorts = listOf(ObjectSearchConstants.sortByName()), keys = ObjectSearchConstants.participantKeys ) ).map { results -> results.mapNotNull { wrapper -> ShareSpaceMemberView.fromObject(ObjectWrapper.Participant(wrapper.map)) } }.collect { members.value = it } } } private fun proceedWithGeneratingInviteLink() { viewModelScope.launch { generateSpaceInviteLink .async(params.space) .fold( onSuccess = { link -> viewState.value = ViewState.Share(link = link.scheme) }, onFailure = { Timber.e(it, "Error while generating invite link") } ) } } fun onRegenerateInviteLinkClicked() { proceedWithGeneratingInviteLink() } fun onShareInviteLinkClicked() { viewModelScope.launch { when(val value = viewState.value) { ViewState.Init -> { // Do nothing. } is ViewState.Share -> { commands.emit(Command.ShareInviteLink(value.link)) } } } } fun onViewRequestClicked(view: ShareSpaceMemberView) { viewModelScope.launch { commands.emit( Command.ViewJoinRequest( space = params.space, member = view.obj.id ) ) } } fun onApproveUnjoinRequestClicked(view: ShareSpaceMemberView) { // TODO } fun onCanEditClicked( view: ShareSpaceMemberView ) { Timber.d("onCanEditClicked") viewModelScope.launch { if (view.config != ShareSpaceMemberView.Config.Member.Writer) { changeSpaceMemberPermissions.async( ChangeSpaceMemberPermissions.Params( space = params.space, identity = view.obj.identity, permission = ParticipantPermissions.WRITER ) ).fold( onFailure = { e -> Timber.e(e, "Error while changing member permissions").also { sendToast(e.msg()) } } ) } } } fun onCanViewClicked( view: ShareSpaceMemberView ) { Timber.d("onCanViewClicked") viewModelScope.launch { if (view.config != ShareSpaceMemberView.Config.Member.Reader) { changeSpaceMemberPermissions.async( ChangeSpaceMemberPermissions.Params( space = params.space, identity = view.obj.identity, permission = ParticipantPermissions.READER ) ).fold( onFailure = { e -> Timber.e(e, "Error while changing member permissions").also { sendToast(e.msg()) } } ) } } } fun onRemoveMemberClicked( view: ShareSpaceMemberView ) { Timber.d("onRemoveMemberClicked") viewModelScope.launch { removeSpaceMembers.async( RemoveSpaceMembers.Params( space = params.space, identities = listOf(view.obj.identity) ) ).fold( onFailure = { e -> Timber.e(e, "Error while removing space member").also { sendToast(e.msg()) } } ) } } override fun onCleared() { viewModelScope.launch { container.unsubscribe(subscriptions = listOf(SHARE_SPACE_SUBSCRIPTION)) } super.onCleared() } class Factory @Inject constructor( private val params: Params, private val generateSpaceInviteLink: GenerateSpaceInviteLink, private val changeSpaceMemberPermissions: ChangeSpaceMemberPermissions, private val removeSpaceMembers: RemoveSpaceMembers, private val container: StorelessSubscriptionContainer ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T = ShareSpaceViewModel( params = params, generateSpaceInviteLink = generateSpaceInviteLink, changeSpaceMemberPermissions = changeSpaceMemberPermissions, removeSpaceMembers = removeSpaceMembers, container = container ) as T } data class Params( val space: SpaceId ) sealed class ViewState { object Init : ViewState() data class Share(val link: String): ViewState() } sealed class Command { data class ShareInviteLink(val link: String) : Command() data class ViewJoinRequest(val space: SpaceId, val member: Id) : Command() } companion object { const val SHARE_SPACE_SUBSCRIPTION = "share-space-subscription" } } data class ShareSpaceMemberView( val obj: ObjectWrapper.Participant, val config: Config = Config.Member.Owner ) { sealed class Config { sealed class Request : Config() { object Join: Request() object Unjoin: Request() } sealed class Member: Config() { object Owner: Member() object Writer: Member() object Reader: Member() object NoPermissions: Member() object Unknown: Member() } } companion object { fun fromObject(obj: ObjectWrapper.Participant) : ShareSpaceMemberView? { return when(obj.status) { ParticipantStatus.ACTIVE -> { when(obj.permissions) { ParticipantPermissions.READER -> ShareSpaceMemberView( obj = obj, config = Config.Member.Reader ) ParticipantPermissions.WRITER -> ShareSpaceMemberView( obj = obj, config = Config.Member.Writer ) ParticipantPermissions.OWNER -> ShareSpaceMemberView( obj = obj, config = Config.Member.Owner ) ParticipantPermissions.NO_PERMISSIONS -> ShareSpaceMemberView( obj = obj, config = Config.Member.NoPermissions ) null -> ShareSpaceMemberView( obj = obj, config = Config.Member.Unknown ) } } ParticipantStatus.JOINING -> ShareSpaceMemberView( obj = obj, config = Config.Request.Join ) ParticipantStatus.REMOVING -> ShareSpaceMemberView( obj = obj, config = Config.Request.Unjoin ) else -> null } } } }
37
Kotlin
25
326
c11d482acdd111dc4d6403a710d371e19a816f98
9,765
anytype-kotlin
RSA Message-Digest License
ui/widgets/modal-bottom-sheet/src/main/kotlin/com/edricchan/studybuddy/ui/widgets/modalbottomsheet/views/interfaces/ModalBottomSheetItem.kt
EdricChan03
100,260,817
false
{"Kotlin": 840248, "Ruby": 202}
package com.edricchan.studybuddy.ui.widgets.modalbottomsheet.views.interfaces import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.os.Parcelable import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources import androidx.core.graphics.drawable.toBitmap import com.edricchan.studybuddy.ui.widgets.modalbottomsheet.views.ModalBottomSheetAdapter import kotlinx.parcelize.IgnoredOnParcel import kotlinx.parcelize.Parcelize /** * Represents an item in a modal bottom sheet * @property id A non-zero integer ID for the item * @property title The title of the item * @property icon A drawable as a resource identifier * @property onItemClickListener A listener that is triggered when clicked on * @property visible Whether the item is visible * @property enabled Whether the item is enabled * @property requestDismissOnClick Whether the bottom sheet should be dismissed when this * item is clicked. * @see com.edricchan.studybuddy.ui.widgets.modalbottomsheet.views.ModalBottomSheetFragment * @see com.edricchan.studybuddy.ui.widgets.modalbottomsheet.views.dsl.item */ @Parcelize data class ModalBottomSheetItem( val id: Int = ID_NONE, val title: String, val icon: Icon? = null, @IgnoredOnParcel val onItemClickListener: ModalBottomSheetAdapter.OnItemClickListener? = null, val visible: Boolean = true, val enabled: Boolean = true, val requestDismissOnClick: Boolean = true ) : Parcelable { constructor( id: Int = ID_NONE, title: String, @DrawableRes icon: Int, onItemClickListener: ModalBottomSheetAdapter.OnItemClickListener? = null, visible: Boolean = true, enabled: Boolean = true, requestDismissOnClick: Boolean = true ) : this( id = id, title = title, icon = Icon.Resource(icon), onItemClickListener = onItemClickListener, visible = visible, enabled = enabled, requestDismissOnClick = requestDismissOnClick ) constructor( id: Int = ID_NONE, title: String, icon: Drawable, onItemClickListener: ModalBottomSheetAdapter.OnItemClickListener? = null, visible: Boolean = true, enabled: Boolean = true, requestDismissOnClick: Boolean = true ) : this( id = id, title = title, icon = Icon.Raw(icon.toBitmap()), onItemClickListener = onItemClickListener, visible = visible, enabled = enabled, requestDismissOnClick = requestDismissOnClick ) /** * The visual graphic to be used for a [ModalBottomSheetItem]. * * * To use an icon resource, use [Icon.Resource]. * * To use a raw [Drawable], use [Icon.Raw]. * * To retrieve the icon as a [Drawable], use [asDrawable]. */ @Parcelize sealed class Icon : Parcelable { /** Converts this [Icon] to its [Drawable] form given the [context]. */ abstract fun asBitmap(context: Context): Bitmap /** An [Icon] which takes a [drawable resource][iconRes]. */ data class Resource(@DrawableRes val iconRes: Int) : Icon() { /** * Loads the [iconRes] resource from the specified [context], * or throws an [IllegalArgumentException] if no such resource was found. */ override fun asBitmap(context: Context): Bitmap = requireNotNull(AppCompatResources.getDrawable(context, iconRes)) { "Resource specified (${ context.resources.getResourceEntryName(iconRes) }) does not exist" }.toBitmap() } /** An [Icon] which takes a [raw bitmap][Bitmap]. */ // We use a Bitmap instead of a Drawable as it's parcelable data class Raw(val bitmap: Bitmap) : Icon() { /** Returns the [bitmap]. */ override fun asBitmap(context: Context): Bitmap = bitmap } } companion object { /** Represents that the item should not have an ID */ const val ID_NONE = 0 } }
49
Kotlin
10
16
e8b821f989a57bdd9756470f29c0f113fb35b035
4,181
studybuddy-android
MIT License
libraries/VastTools/src/main/java/com/gcode/vasttools/skin/VastSkinSupport.kt
SakurajimaMaii
353,212,367
false
null
/* * Copyright 2022 VastGui * * 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.gcode.vasttools.skin // Author: <NAME> // Email: <EMAIL> // Date: 2022/3/27 18:17 interface VastSkinSupport { fun applySkin() }
3
Kotlin
4
19
62b0adb89d764e8e9107de076a33d2d698069b09
735
Utils
Apache License 2.0
FrontEnd/app/src/main/java/cs309/selectunes/services/AuthServiceImpl.kt
SelecTunes
259,414,351
false
{"C#": 213708, "Kotlin": 94692, "HTML": 16883, "Python": 14495, "JavaScript": 11286, "Ruby": 3898, "CSS": 1346, "Dockerfile": 642, "Makefile": 184}
package cs309.selectunes.services import android.content.Intent import androidx.appcompat.app.AppCompatActivity import com.android.volley.NetworkResponse import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.spotify.sdk.android.authentication.LoginActivity import cs309.selectunes.activities.ChooseActivity import cs309.selectunes.utils.JsonUtils class AuthServiceImpl : AuthService { override fun login(email: String, password: String, activity: AppCompatActivity) { val stringRequest = object : StringRequest(Method.POST, "https://coms-309-jr-2.cs.iastate.edu/api/auth/login", Response.Listener { val success = JsonUtils.parseLoginResponse(activity, it) if (success) activity.startActivity(Intent(activity, ChooseActivity::class.java)) }, Response.ErrorListener { println("There was an error with the response. Code: ${it.networkResponse.statusCode}") }) { override fun getParams(): Map<String, String> { val params: MutableMap<String, String> = HashMap() params["Email"] = email params["Password"] = <PASSWORD> params["ConfirmPassword"] = <PASSWORD> return params } override fun getHeaders(): Map<String, String> { val headers: MutableMap<String, String> = HashMap() headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json, text/json" return headers } override fun parseNetworkResponse(response: NetworkResponse?): Response<String> { val responseHeaders = response?.headers val rawCookies = responseHeaders?.get("Set-Cookie") if (rawCookies != null) { val search = "Holtzmann=" val cookie = rawCookies.substring(rawCookies.indexOf(search) + search.length, rawCookies.indexOf(';')) val settings = activity.getSharedPreferences("Cookie", 0) settings.edit().putString("cookie", cookie).apply() } return super.parseNetworkResponse(response) } } val requestQueue = Volley.newRequestQueue(activity) requestQueue.add(stringRequest) } override fun register(email: String, password: String, passwordConfirmed: String, activity: AppCompatActivity) { val stringRequest = object : StringRequest(Method.POST, "https://coms-309-jr-2.cs.iastate.edu/api/auth/register", Response.Listener { val success = JsonUtils.parseRegisterResponse(activity, it, 200) if (success) activity.startActivity(Intent(activity, LoginActivity::class.java)) }, Response.ErrorListener { JsonUtils.parseRegisterResponse(activity, null, it.networkResponse.statusCode) println("There was an error with the response. Code: ${it.networkResponse.statusCode}") }) { override fun getParams(): Map<String, String> { val params: MutableMap<String, String> = HashMap() params["Email"] = email params["Password"] = <PASSWORD> params["ConfirmPassword"] = <PASSWORD> return params } override fun getHeaders(): Map<String, String> { val headers: MutableMap<String, String> = HashMap() headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json, text/json" return headers } } val requestQueue = Volley.newRequestQueue(activity) requestQueue.add(stringRequest) } }
17
C#
0
3
fa0160d26d7ee9c78074dc86e13d7f9fd835e8c5
3,848
SelecTunes
Apache License 2.0
app/src/main/kotlin/com/sadashi/client/chatwork/ui/room/detail/MessageListAdapter.kt
sadashi-ota
189,266,945
false
null
package com.sadashi.client.chatwork.ui.room.detail import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.sadashi.client.chatwork.R import com.sadashi.client.chatwork.domain.rooms.Message import com.sadashi.client.chatwork.extensions.imageUrl import com.sadashi.client.chatwork.extensions.inflate import kotlinx.android.synthetic.main.item_message.view.body import kotlinx.android.synthetic.main.item_message.view.icon import kotlinx.android.synthetic.main.item_message.view.name class MessageListAdapter( private val onItemClicked: (Message) -> Unit ) : ListAdapter<Message, MessageViewHolder>(DIFF_CALLBACK) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder { val holder = MessageViewHolder(parent) holder.itemView.setOnClickListener { val message = getItem(holder.adapterPosition) ?: return@setOnClickListener onItemClicked(message) } return holder } override fun onBindViewHolder(holder: MessageViewHolder, position: Int) { val member = getItem(position) ?: return holder.bind(member) } } class MessageViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder( parent.inflate(R.layout.item_message) ) { fun bind(message: Message) { itemView.icon.imageUrl(message.account.avatarImageUrl) itemView.name.text = message.account.name itemView.body.text = message.body } } private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Message>() { override fun areItemsTheSame(oldItem: Message, newItem: Message): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Message, newItem: Message): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
458239a29ab4453f1d5e6e352efdb36af59f6d6e
1,894
chatwork_client_sample
Apache License 2.0
app/src/main/java/com/prof18/secureqrreader/style/Shapes.kt
Gozirin
586,401,887
false
null
package com.prof18.secureqrreader.style import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp internal val SecureQrReaderShapes = Shapes( small = RoundedCornerShape(16.dp), medium = RoundedCornerShape(16.dp), large = RoundedCornerShape(16.dp) )
0
Kotlin
0
0
128226f89775652cce210b842046bc1f6ab2e8c0
341
QrScanner
Apache License 2.0
ospf-kotlin-framework-gantt-scheduling/gantt-scheduling-domain-task-context/src/main/fuookami/ospf/kotlin/framework/gantt_scheduling/domain/task/model/TaskStepGraph.kt
fuookami
359,831,793
false
{"Kotlin": 2440181, "Python": 6629}
package fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task.model import kotlin.time.* import fuookami.ospf.kotlin.utils.error.* import fuookami.ospf.kotlin.utils.functional.* enum class StepRelation { And, Or } abstract class TaskStep< out T : AbstractMultiStepTask<T, S, E>, out S : AbstractTaskStepPlan<S, T, E>, out E : Executor >( val id: String, val name: String, val enabledExecutors: Set<E>, val status: Set<TaskStatus> ) { open val displayName: String? by ::name abstract fun duration(task: @UnsafeVariance T, executor: @UnsafeVariance E): Duration override fun toString(): String { return displayName ?: name } } data class ForwardTaskStepVector< out T : AbstractMultiStepTask<T, S, E>, out S : AbstractTaskStepPlan<S, T, E>, out E : Executor >( val from: TaskStep<T, S, E>, val to: List<TaskStep<T, S, E>>, val relation: StepRelation ) data class BackwardTaskStepVector< out T : AbstractMultiStepTask<T, S, E>, out S : AbstractTaskStepPlan<S, T, E>, out E : Executor >( val from: List<TaskStep<T, S, E>>, val to: TaskStep<T, S, E>, val relation: StepRelation ) open class TaskStepGraph< out T : AbstractMultiStepTask<T, S, E>, out S : AbstractTaskStepPlan<S, T, E>, out E : Executor >( val id: String, val name: String, val steps: List<TaskStep<T, S, E>>, val startSteps: Pair<List<TaskStep<T, S, E>>, StepRelation>, // must be a DAG val forwardTaskStepVector: Map< TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>, ForwardTaskStepVector<T, S, E> >, val backwardStepRelation: Map< TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>, BackwardTaskStepVector<T, S, E> > ) { companion object { fun <T : AbstractMultiStepTask<T, S, E>, S : AbstractTaskStepPlan<S, T, E>, E : Executor> build( ctx: TaskStepGraphBuilder<T, S, E>.() -> Unit ): TaskStepGraph<T, S, E> { val builder = TaskStepGraphBuilder<T, S, E>() ctx(builder) return builder() } } } data class TaskStepGraphBuilder< out T : AbstractMultiStepTask<T, S, E>, out S : AbstractTaskStepPlan<S, T, E>, out E : Executor >( var id: String? = null, var name: String? = null, val steps: MutableList<TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>> = ArrayList(), var startSteps: Pair<List<TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>>, StepRelation>? = null, private val forwardTaskStepVector: MutableMap<TaskStep<T, S, E>, ForwardTaskStepVector<T, S, E>> = HashMap(), private val backwardStepRelation: MutableMap<TaskStep<T, S, E>, BackwardTaskStepVector<T, S, E>> = HashMap() ) { val setSteps: MutableSet<TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>> = HashSet() operator fun invoke(): TaskStepGraph<T, S, E> { return TaskStepGraph( id = id!!, name = name!!, steps = steps, startSteps = startSteps!!, forwardTaskStepVector = forwardTaskStepVector, backwardStepRelation = backwardStepRelation ) } fun TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>.start( steps: List<TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>>, relation: StepRelation ): Try { if (steps.any { [email protected](it) }) { return Failed(Err(ErrorCode.ApplicationError, "step not in")) } startSteps = Pair(steps, relation) return ok } fun TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>.forward( from: TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>, to: List<TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>>, relation: StepRelation ): Try { forwardTaskStepVector[from] = ForwardTaskStepVector( from = from, to = to, relation = relation ) return ok } fun TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>.backward( from: List<TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>>, to: TaskStep<@UnsafeVariance T, @UnsafeVariance S, @UnsafeVariance E>, relation: StepRelation ): Try { for (step in from) { if ((forwardTaskStepVector[step]?.to ?: emptyList()).any { it == to }) { return Failed(Err(ErrorCode.ApplicationError, "no step to ${to.id}")) } } backwardStepRelation[to] = BackwardTaskStepVector( from = from, to = to, relation = relation ) return ok } }
0
Kotlin
0
4
b34cda509b31884e6a15d77f00a6134d001868de
4,872
ospf-kotlin
Apache License 2.0
src/main/kotlin/com/pos/kasse/adminviews/Admin.kt
davidsenkristoffer
259,775,536
false
{"Kotlin": 47635}
package com.pos.kasse.adminviews import javafx.scene.Parent import tornadofx.* class Admin : View() { override val root = borderpane { center { form { } } } }
0
Kotlin
0
0
b16a9bbc3d35f47a286ddd80ae60f22abf00f581
210
Kassesystem
MIT License
Android/app/src/test/java/ru/alexskvortsov/policlinic/ExampleUnitTest.kt
AlexSkvor
244,438,301
false
null
package ru.alexskvortsov.policlinic import org.junit.Test import org.junit.Assert.* import ru.alexskvortsov.policlinic.user_generators.UsersGenerator /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } @Test fun generateUsers() { UsersGenerator().generate(5) } @Test fun generateProcedures(){ ProceduresGenerator().generateProcedures() } }
0
Kotlin
0
0
5cc6a10a1399ee08643e69308afd4626938882b0
595
polyclinic
Apache License 2.0
app/src/main/java/com/dinesh/mynotes/rv/RestoreAdapter.kt
Dinesh2811
589,404,107
false
{"Kotlin": 121705}
package com.dinesh.mynotes.rv import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.TextView import androidx.cardview.widget.CardView import androidx.lifecycle.MutableLiveData import androidx.recyclerview.widget.RecyclerView import com.dinesh.mynotes.R import com.dinesh.mynotes.room.Note class RestoreAdapter(private val notes: List<Note>) : RecyclerView.Adapter<RestoreAdapter.ViewHolder>() { private val selectedNotes = mutableListOf<Note>() var selectedNotesLiveData = MutableLiveData<List<Note>>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.restore_item_note, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val note = notes[position] if (note.title.trim().isEmpty()) { holder.tvTitle.visibility = View.GONE } else { holder.tvTitle.text = note.title holder.tvTitle.visibility = View.VISIBLE } if (note.notes.trim().isEmpty()) { holder.tvNote.visibility = View.GONE } else { holder.tvNote.text = note.notes holder.tvNote.visibility = View.VISIBLE } holder.checkBox.isChecked = selectedNotes.contains(note) val itemClickListener = View.OnClickListener { if (selectedNotes.contains(note)) { selectedNotes.remove(note) holder.checkBox.isChecked = false } else { selectedNotes.add(note) holder.checkBox.isChecked = true } selectedNotesLiveData.value = selectedNotes } holder.rvCardView.setOnClickListener(itemClickListener) holder.itemView.setOnClickListener(itemClickListener) holder.tvTitle.setOnClickListener(itemClickListener) holder.tvNote.setOnClickListener(itemClickListener) holder.checkBox.setOnClickListener(itemClickListener) } override fun getItemCount() = notes.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val rvCardView: CardView = itemView.findViewById(R.id.rvCardView) val checkBox: CheckBox = itemView.findViewById(R.id.checkbox) val tvTitle: TextView = itemView.findViewById(R.id.tvTitle) val tvNote: TextView = itemView.findViewById(R.id.tvNote) } fun getSelectedNotes(): List<Note> { return selectedNotes } fun updateSelection(isChecked: Boolean) { if (isChecked) { selectedNotes.clear() selectedNotes.addAll(notes) } else { selectedNotes.clear() } notifyDataSetChanged() } }
0
Kotlin
0
1
aaeda7c26db0cde6159fe732057d9efeb20c03fa
2,877
MyNotes
Apache License 2.0
app/src/main/java/com/br/baseproject/repository/WordRepository.kt
Gian-f
544,413,970
false
null
package com.br.baseproject.repository import androidx.annotation.WorkerThread import com.br.baseproject.database.dao.RegistryDao import com.br.baseproject.database.model.Registry import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch class WordRepository(private val registryDao: RegistryDao) { val allWords: Flow<List<Registry>> = registryDao.getAlphabetizedWords() @Suppress("RedundantSuspendModifier") @WorkerThread suspend fun insert(registry: Registry){ registryDao.insert(registry) } fun findAll(){ CoroutineScope(Dispatchers.IO).launch { registryDao.getAllWords() } } }
0
Kotlin
0
0
3944a79c2958f9248e4a309f9f1631d1a8f575ac
742
Crud-with-RoomDatabase
MIT License
plugin/src/main/java/com/guiying712/plugin/RouterTransform.kt
guiying712
466,683,536
false
{"Kotlin": 21740}
package com.guiying712.plugin import com.android.SdkConstants import com.android.build.api.transform.* import com.android.build.gradle.internal.pipeline.TransformManager import org.apache.commons.io.FileUtils import org.gradle.api.Project import java.util.* import java.io.File class RouterTransform(private val project: Project) : Transform() { /** * ่ฟ”ๅ›ž transform ็š„ๅ็งฐ๏ผŒๆœ€็ปˆ็š„task็š„ๅ็งฐไผšๆ˜ฏ๏ผštransformClassesWithRouterForDebug */ override fun getName(): String = "Router" override fun getInputTypes(): Set<QualifiedContent.ContentType> { return TransformManager.CONTENT_CLASS } override fun getScopes(): MutableSet<in QualifiedContent.Scope> { return TransformManager.SCOPE_FULL_PROJECT } override fun isIncremental(): Boolean = false private fun TransformOutputProvider.getContentLocation( name: String, contentType: QualifiedContent.ContentType, scope: QualifiedContent.Scope, format: Format ): File = getContentLocation(name, setOf(contentType), EnumSet.of(scope), format) override fun transform(transformInvocation: TransformInvocation) { if (!transformInvocation.isIncremental) { transformInvocation.outputProvider.deleteAll() } val inputs = transformInvocation.inputs.flatMap { it.directoryInputs + it.jarInputs } val outputs: List<File> = inputs.map { input -> val format = if (input is JarInput) Format.JAR else Format.DIRECTORY // Transforms ๅฏไปฅ่ฆๆฑ‚่Žทๅ–็ป™ๅฎš่Œƒๅ›ดใ€ๅ†…ๅฎน็ฑปๅž‹ๅ’Œๆ ผๅผ็š„ไฝ็ฝฎ // ๅฆ‚ๆžœๆ ผๅผไธบ Format.DIRECTORY๏ผŒๅˆ™็ป“ๆžœไธบ็›ฎๅฝ•็š„ๆ–‡ไปถไฝ็ฝฎ // ๅฆ‚ๆžœๆ ผๅผๆ˜ฏ Format.JAR๏ผŒ้‚ฃไนˆ็ป“ๆžœๆ˜ฏไธ€ไธชไปฃ่กจ่ฆๅˆ›ๅปบ็š„ jar ็š„ๆ–‡ไปถ transformInvocation.outputProvider.getContentLocation( input.name, input.contentTypes, input.scopes, format ) } val dest = transformInvocation.outputProvider.getContentLocation( "ARouter", QualifiedContent.DefaultContentType.CLASSES, QualifiedContent.Scope.PROJECT, Format.DIRECTORY ) RouterProcessor(inputs.map { it.file }, outputs).apply { process(dest.absolutePath) } } fun process(inputs: List<File>, outputs: List<File>) { inputs.zip(outputs) { input, output -> when { input.isDirectory -> { FileUtils.copyDirectory(input,output) } input.name.endsWith(SdkConstants.DOT_JAR) -> { FileUtils.copyFile(input,output) } } } } } fun process(inputs: List<File>, outputs: List<File>) { inputs.zip(outputs) { input, output -> when { input.isDirectory -> { FileUtils.copyDirectory(input,output) } input.name.endsWith(SdkConstants.DOT_JAR) -> { FileUtils.copyFile(input,output) } } } }
0
Kotlin
1
2
fef88df211b898dcca1ce3f1e6a17f26cc9a1ae9
2,975
KotlinRouter
Apache License 2.0
src/main/kotlin/days/Day07.kt
julia-kim
435,257,054
false
{"Kotlin": 15771}
package days import readInput import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>): Int { val horizontalPositions = input[0].split(",").map { it.toInt() } val outcomes: MutableList<Int> = mutableListOf() horizontalPositions.forEach { pos -> var totalFuel = 0 horizontalPositions.forEach { val diff = (it - pos).absoluteValue totalFuel += diff } outcomes.add(totalFuel) } return outcomes.minOf { it } } fun part2(input: List<String>): Int { val horizontalPositions = input[0].split(",").map { it.toInt() } val outcomes: MutableList<Int> = mutableListOf() (0..horizontalPositions.maxOf { it }).forEach { pos -> var totalFuel = 0 horizontalPositions.forEach { var fuelCost = 0 var diff = (it - pos).absoluteValue while (diff > 0) { fuelCost += diff diff-- } totalFuel += fuelCost } outcomes.add(totalFuel) } return outcomes.minOf { it } } val testInput = readInput("Day07_test") check(part1(testInput) == 37) check(part2(testInput) == 168) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5febe0d5b9464738f9a7523c0e1d21bd992b9302
1,410
advent-of-code-2021
Apache License 2.0
src/Day08.kt
coolcut69
572,865,721
false
{"Kotlin": 36853}
fun main() { fun visibleFromTop(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x > it.x && tree.y == it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun visibleFromBottom(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x < it.x && tree.y == it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun visibleFromLeft(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x == it.x && tree.y > it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun visibleFromRight(tree: Tree, trees: MutableList<Tree>): Boolean { val filter = trees.filter { tree.x == it.x && tree.y < it.y } val maxOf = filter.maxOf { it.height } return tree.height > maxOf } fun scenicScoreLeft(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.x == right.x && tree.y > right.y } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter.reversed()) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun scenicScoreRight(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.x == right.x && tree.y < right.y } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun scenicScoreTop(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.y == right.y && tree.x > right.x } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter.reversed()) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun scenicScoreBottom(tree: Tree, trees: MutableList<Tree>): Int { val filter = trees.filter { right -> tree.y == right.y && tree.x < right.x } if (filter[0].height == tree.height) return 1 var i = 0 for (t in filter) { if (t.height < tree.height) { i++ } if (t.height >= tree.height) { i++ return i } } return i } fun createForest(inputs: List<String>): MutableList<Tree> { val trees: MutableList<Tree> = ArrayList() for ((i, row) in inputs.withIndex()) { for ((j, char) in row.toList().withIndex()) { trees.add(Tree(i, j, char.toString().toInt())) } } return trees } fun part1(inputs: List<String>): Int { val forest: MutableList<Tree> = createForest(inputs) val maxX = forest.maxOf { tree -> tree.x } - 1 val maxY = forest.maxOf { tree -> tree.y } - 1 val visibleTrees: MutableSet<Tree> = HashSet() // check left to right and right to left for (i in (1..maxX)) { val leftToRight = forest.filter { tree -> tree.x == i && tree.y != 0 && tree.y != inputs.size - 1 } for (tree in leftToRight) { if (visibleFromLeft(tree, forest)) { visibleTrees.add(tree) } if (visibleFromRight(tree, forest)) { visibleTrees.add(tree) } } } for (i in (1..maxY)) { val topToBottom = forest.filter { tree -> tree.y == i && tree.x != 0 && tree.x != inputs.size - 1 } for (tree in topToBottom) { if (visibleFromTop(tree, forest)) { visibleTrees.add(tree) } if (visibleFromBottom(tree, forest)) { visibleTrees.add(tree) } } } return visibleTrees.size + forest.size - (maxX * maxY) } fun part2(inputs: List<String>): Int { val forest: MutableList<Tree> = createForest(inputs) val maxX = forest.maxOf { tree -> tree.x } - 1 val maxY = forest.maxOf { tree -> tree.y } - 1 val scenicScores: MutableSet<Int> = HashSet() // check left to right and right to left for (i in (1..maxX)) { val leftToRight = forest.filter { tree -> tree.x == i && tree.y != 0 && tree.y != inputs.size - 1 } for (tree in leftToRight) { val scenicScore = scenicScoreTop(tree, forest) * scenicScoreLeft(tree, forest) * scenicScoreBottom(tree, forest) * scenicScoreRight(tree, forest) scenicScores.add(scenicScore) } } return scenicScores.max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") // println(part1(input)) check(part1(input) == 1538) // println(part2(input)) check(part2(input) == 496125) } data class Tree( val x: Int, val y: Int, val height: Int )
0
Kotlin
0
0
031301607c2e1c21a6d4658b1e96685c4135fd44
5,696
aoc-2022-in-kotlin
Apache License 2.0
app/src/main/kotlin/com/babelia/fansyn/network/SynologyFakeApi.kt
Babelia13
551,891,953
false
{"Kotlin": 309398, "Shell": 3830}
/* * Copyright 2022 Babelia * * 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.babelia.fansyn.network import com.babelia.fansyn.debug.previews.AlbumsMocks import com.babelia.fansyn.network.models.* import kotlinx.coroutines.delay /** * Fake class for using while developing to get mocked data. */ class SynologyFakeApi : SynologyApi { override suspend fun getAudioStationAlbums(api: String, version: Int, method: String, limit: Int, library: String): AudioStationAlbumsResponse { mockServerWork() return AudioStationAlbumsResponse( data = AudioStationAlbumsResponseData( AlbumsMocks.getAlbumsMock().map { it.toNetworkAudioStationAlbum() }, 0, 0), error = null, success = true) } override suspend fun getAudioStationAlbumSongs(api: String, version: Int, method: String, limit: Int, library: String, albumName: String, albumArtist: String): AudioStationAlbumSongsResponse { mockServerWork() return AudioStationAlbumSongsResponse( data = AudioStationAlbumSongsResponseData( 0, AlbumsMocks.getAlbumSongsMock().map { it.toNetworkAudioStationSong() }, 0), error = null, success = true) } /** * Random delay of 1-3 seconds to simulate server work. */ @Suppress("MagicNumber") private suspend fun mockServerWork() = delay((1000L..3000L).random()) }
0
Kotlin
0
0
0fe3a5c9c84a6bad85a1c999b6fb66d4c2cbb478
2,455
FancySynologyAudioPlayer
Apache License 2.0
OptiGUI/src/main/kotlin/opekope2/filter/OptionalFilter.kt
opekope2
578,779,647
false
null
package opekope2.filter import java.util.* /** * Basically a [NullGuardFilter] for Java users using [Optional]. * * @param T The type the given [filter] accepts * @param TResult The type [filter] returns * @param nullResult The result when the input is not present * @param filter The filter to evaluate */ class OptionalFilter<T, TResult>( private val nullResult: FilterResult<TResult>, private val filter: Filter<T, TResult> ) : Filter<Optional<T>, TResult>, Iterable<Filter<T, TResult>> { override fun evaluate(value: Optional<T>): FilterResult<out TResult> = if (!value.isPresent) nullResult else filter.evaluate(value.get()) override fun iterator(): Iterator<Filter<T, TResult>> = setOf(filter).iterator() override fun toString(): String = "${javaClass.name}, result on null: $nullResult" }
9
Kotlin
1
9
d61d4c2a70f2d00cb7513bd19a0bfa309e7ee66d
843
OptiGUI
MIT License
src/main/kotlin/CMouseController.kt
argcc
777,572,651
false
{"Kotlin": 665702}
package org.example var MouseController: CMouseController? = null class CMouseController : C_0073c368() { var IDirectInput7A = IDirectInput7A() var IDirectInputDevice7A = IDirectInputDevice7A() fun CreateMouseDevice(hWnd: HWND, hInst: HINSTANCE): Boolean { DirectInputCreateEx(hInst, 0x700u, IID_IDirectInput7A, IDirectInput7A, null) IDirectInput7A.CreateDeviceEx(GUID_SysMouse, IID_IDirectInputDevice7A, IDirectInputDevice7A, 0) IDirectInputDevice7A.SetDataFormat(c_dfDIMouse) IDirectInputDevice7A.SetCooperativeLevel(hWnd, DISCL_NOWINKEY) IDirectInputDevice7A.Acquire() return true } }
0
Kotlin
0
0
8edd9403e6efd3dd402bd9efdec36c34fe73780f
654
ei_reverse_consp
MIT License
src/commonMain/kotlin/ir/Visibility.kt
aripiprazole
370,489,230
false
{"Kotlin": 297789}
/* * Copyright 2022 Plank * * 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 org.plank.llvm4k.ir /** An enumeration for the kinds of visibility of global values. */ public expect enum class Visibility { /** The GV is visible. */ Default, /** The GV is hidden. */ Hidden, /** The GV is protected. */ Protected; public val value: UInt public companion object { public fun byValue(value: Int): Visibility public fun byValue(value: UInt): Visibility } }
0
Kotlin
0
3
110e1b467a5ba322954b95b7a9374ca1e052f3a8
1,033
llvm4k
Apache License 2.0
app/src/main/java/com/ouday/cryptowalletsample/common/FlowState.kt
oudaykhaled
731,418,539
false
{"Kotlin": 131611, "Python": 4720}
package com.ouday.cryptowalletsample.common import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn /** * Sealed class representing the different states of a Flow. * This allows for a unified way to handle loading, success, and error states in the UI. */ sealed class FlowState<out T> { /** * Represents the loading state before the data is fetched. * No data is associated with this state. */ object Loading : FlowState<Nothing>() /** * Represents the success state with data. * @param data The data fetched successfully. */ data class Success<T>(val data: T) : FlowState<T>() /** * Represents the error state when something goes wrong in data fetching. * @param message The error message describing what went wrong. */ data class Error(val message: String) : FlowState<Nothing>() } /** * Extension function for Flow to convert it into a Flow emitting FlowState objects. * This function transforms a regular Flow into one that emits states representing * loading, success, and error states, suitable for UI state management. * * @return A Flow emitting FlowState objects. */ fun <T> Flow<T>.asFlowState(): Flow<FlowState<T>> = flow { try { emit(FlowState.Loading) // Emit Loading state initially collect { data -> emit(FlowState.Success(data)) // Emit Success state with data when available } } catch (e: Exception) { emit(FlowState.Error(e.message ?: "Unknown error")) // Emit Error state in case of exception } }.flowOn(Dispatchers.IO) // Switch the context to IO for network/database operations
0
Kotlin
0
1
6ecf39ec148c9495852ca42ff02df1aa30c7155d
1,731
Android-Wallet-JetCompose-MVVM-Clean-Architecture-MDS3
MIT License
contests/Kotlin Heroes Episode 4/Boot_camp.kt
Razdeep
151,215,612
false
null
// https://codeforces.com/contest/1346/problem/B fun main() { var tc: Int = readLine()!!.toInt() while (tc-- > 0) { var (n, k1, k2) = readLine()!!.split(' ').map { it.toInt() } var text: String = readLine()!! var arr: MutableList<Int> = mutableListOf<Int>(); for (i in 0..(n - 1)) { if (text[i] == '0') { arr.add(0) } else { arr.add(1) } } var ans: Int = 0 for (i in 0..(n - 2)) { if (arr.get(i) == 1 && arr.get(i + 1) == 1) { ans = ans + Math.min(2 * k1, k2) arr[i] = 0 arr[i + 1] = 0 } else if (arr.get(i) == 1) { ans = ans + k1 arr[i] = 0 } } if (arr.get(n - 1) == 1) { ans = ans + k1 } println(ans) } }
0
C++
0
2
8a563f41bc31029ce030213f196b1e1355efc439
904
Codeforces-Solutions
MIT License
agent/src/main/kotlin/pt/um/lei/masb/agent/net/JSONMappedURLs.kt
brunofmf
166,305,210
true
{"Kotlin": 240087}
package pt.um.lei.masb.agent.net import kotlinx.serialization.Serializable import kotlinx.serialization.json.JSON import mu.KLogging import pt.um.lei.masb.agent.Container import pt.um.lei.masb.agent.data.DataSource import java.io.File import java.io.FileReader import java.io.InputStreamReader import java.net.URI @Serializable data class JSONMappedURLs( val apis: List<DataSource> = emptyList(), val tcp: List<DataSource> = emptyList(), val jade: List<DataSource> = emptyList() ) { companion object : KLogging() { val apiScheme = Regex.fromLiteral("http(s)?") val tcpScheme = Regex.fromLiteral("tcp") val jadeScheme = Regex.fromLiteral("jade") /** * A parser for a file based on a path string from the classpath resources. * * @param file the path string to a resource in the classpath. */ fun jsonFileUrlParser(file: String): JSONMappedURLs = InputStreamReader( Container::class.java .getResourceAsStream(file) ).use { JSON.parse(this.serializer(), it.readText()) } /** * A parser for a file at the specified URI. * * @param file */ fun jsonFileUrlParser(file: URI): JSONMappedURLs = FileReader(File(file)).use { JSON.parse(this.serializer(), it.readText()) } } }
0
Kotlin
0
0
1655c032f274f078e1d7e9fa525dcada3b6499dc
1,451
mas-blockchain-main
MIT License
app/src/main/kotlin/com/xiaocydx/sample/concat/HeaderFooterActivity.kt
xiaocydx
460,257,515
false
{"Kotlin": 1365337}
package com.xiaocydx.sample.concat import android.os.Bundle import android.util.TypedValue import android.view.Gravity import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatTextView import androidx.recyclerview.widget.HeaderFooterRemovedChecker import androidx.recyclerview.widget.RecyclerView import com.xiaocydx.cxrv.concat.ViewAdapter import com.xiaocydx.cxrv.concat.addFooter import com.xiaocydx.cxrv.concat.addHeader import com.xiaocydx.cxrv.concat.removeFooter import com.xiaocydx.cxrv.concat.removeHeader import com.xiaocydx.cxrv.divider.divider import com.xiaocydx.cxrv.itemclick.doOnSimpleItemClick import com.xiaocydx.cxrv.list.adapter import com.xiaocydx.cxrv.list.doOnAttach import com.xiaocydx.cxrv.list.grid import com.xiaocydx.cxrv.list.linear import com.xiaocydx.cxrv.list.submitList import com.xiaocydx.sample.databinding.ActionContentBinding import com.xiaocydx.sample.dp import com.xiaocydx.sample.extensions.Action import com.xiaocydx.sample.extensions.initActionList import com.xiaocydx.sample.foo.Foo import com.xiaocydx.sample.foo.FooListAdapter import com.xiaocydx.sample.layoutParams import com.xiaocydx.sample.matchParent import com.xiaocydx.sample.wrapContent /** * HeaderFooter็คบไพ‹ไปฃ็  * * @author xcc * @date 2022/12/14 */ class HeaderFooterActivity : AppCompatActivity() { private lateinit var header: View private lateinit var footer: View private lateinit var rvContent: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(contentView()) } private fun contentView() = ActionContentBinding .inflate(layoutInflater).apply { // ๆณจๆ„๏ผšๅ…ˆ่ฎพ็ฝฎfooAdapter็กฎๅฎšๅ†…ๅฎนๅŒบ๏ผŒๅ†ๆทปๅŠ headerๅ’Œfooter๏ผŒ // ่‹ฅๅœจๅˆๅง‹ๅŒ–ๆ—ถไธๆทปๅŠ headerๅ’Œfooter๏ผŒ่€Œๆ˜ฏๅŽ็ปญๆ นๆฎๆƒ…ๅ†ตๅŠจๆ€ๆทปๅŠ headerๅ’Œfooter๏ผŒ // ๅ…ˆ่ฎพ็ฝฎConcat.content(fooAdapter).concat()๏ผŒๅŽ็ปญๆทปๅŠ ๆœ‰ๅŠจ็”ปๆ•ˆๆžœไธ”ๆ€ง่ƒฝๆ›ด้ซ˜ใ€‚ // rvFoo.adapter(Concat.content(fooAdapter).concat()) val fooAdapter = FooListAdapter() fooAdapter.submitList((1..3).map(::createFoo)) rvContent.linear().divider(height = 5.dp).adapter(fooAdapter) header = createView(isHeader = true) footer = createView(isHeader = false) rvContent.addHeader(header) rvContent.addFooter(footer) [email protected] = rvContent rvAction.initActionList { submitList(HeaderFooterAction.values().toList()) doOnSimpleItemClick(::performHeaderFooterAction) doOnAttach { rv -> rv.grid(spanCount = 2) } onCreateView { root.layoutParams(matchParent, wrapContent) } } }.root private fun performHeaderFooterAction(action: HeaderFooterAction) { when (action) { HeaderFooterAction.ADD_HEADER -> rvContent.addHeader(header) HeaderFooterAction.REMOVE_HEADER -> rvContent.removeHeader(header)?.let { checkRemoved(it) } HeaderFooterAction.ADD_FOOTER -> rvContent.addFooter(footer) HeaderFooterAction.REMOVE_FOOTER -> rvContent.removeFooter(footer)?.let { checkRemoved(it) } } } /** * HeaderFooter็š„ๅฎž็Žฐ็กฎไฟไปŽRecyclerView็š„็ผ“ๅญ˜ไธญๆธ…้™คๅทฒ็งป้™ค็š„Headerๅ’ŒFooter๏ผŒ * ็งป้™คHeaderๅ’ŒFooterๅŽ๏ผŒ็”จ[HeaderFooterRemovedChecker]ๆฃ€ๆŸฅๆ˜ฏๅฆไปŽ็ผ“ๅญ˜ไธญๆธ…้™ค๏ผŒ * ่‹ฅHeaderๅ’ŒFooter่ฟ˜ๅœจ็ผ“ๅญ˜ไธญ๏ผŒๅˆ™ๆŠ›ๅ‡บ[IllegalStateException]ๅผ‚ๅธธใ€‚ * * @param viewAdapter ๆทปๅŠ Headerๅ’ŒFooterๆœ€็ปˆๆ˜ฏ่ฝฌๆขๆˆitemๅคš็ฑปๅž‹๏ผŒ * [addHeader]ๅ’Œ[addFooter]ไผšๅฐ†[View.hashCode]ไฝœไธบ`viewType`ใ€‚ */ private fun checkRemoved(viewAdapter: ViewAdapter<*>) { val viewType = viewAdapter.getItemViewType() val checker = HeaderFooterRemovedChecker(rvContent, viewType) // ็”ฑไบŽremoveๅŠจ็”ป็ป“ๆŸๅŽ๏ผŒHeaderๅ’ŒFooterๆ‰่ขซๅ›žๆ”ถ่ฟ›็ผ“ๅญ˜๏ผŒๅ› ๆญคๅœจๅŠจ็”ป็ป“ๆŸๅŽๆฃ€ๆŸฅ rvContent.itemAnimator?.isRunning(checker::check) ?: run(checker::check) } private fun createView(isHeader: Boolean) = AppCompatTextView(this).apply { gravity = Gravity.CENTER text = if (isHeader) "Header" else "Footer" layoutParams(matchParent, 100.dp) setTextSize(TypedValue.COMPLEX_UNIT_PX, 18.dp.toFloat()) setBackgroundColor(if (isHeader) 0xFF92C3FF.toInt() else 0xFF958CFF.toInt()) } private fun createFoo(id: Int): Foo = Foo(id = id.toString(), name = "Foo-$id", num = id) private enum class HeaderFooterAction(override val text: String) : Action { ADD_HEADER("ๆทปๅŠ Header"), REMOVE_HEADER("็งป้™คHeader"), ADD_FOOTER("ๆทปๅŠ Footer"), REMOVE_FOOTER("็งป้™คFooter") } }
0
Kotlin
0
9
27749927bb10c30d18b9a9639cdefbf03156d552
4,542
CXRV
Apache License 2.0
app/src/main/java/com/ycz/lanhome/fragment/UpdateFragment.kt
Sanlorng
274,937,991
false
null
package com.ycz.lanhome.fragment import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.ycz.lanhome.R import com.ycz.lanhome.viewmodel.UpdateViewModel class UpdateFragment : Fragment() { companion object { fun newInstance() = UpdateFragment() } private lateinit var viewModel: UpdateViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.update_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(UpdateViewModel::class.java) // TODO: Use the ViewModel } }
0
Kotlin
0
0
f66e44888deffcc61f12d9778103de68f9eaf5fc
938
LANHome
Apache License 2.0
app/src/main/java/com/seif/booksislandapp/presentation/home/my_ads/sell/MySellAdsViewModel.kt
SeifEldinMohamed
570,587,114
false
null
package com.seif.booksislandapp.presentation.home.my_ads.sell import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.seif.booksislandapp.R import com.seif.booksislandapp.domain.usecase.usecase.my_ads.sell.GetMySellAdsUseCase import com.seif.booksislandapp.domain.usecase.usecase.shared_preference.GetFromSharedPreferenceUseCase import com.seif.booksislandapp.utils.Resource import com.seif.booksislandapp.utils.ResourceProvider import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class MySellAdsViewModel @Inject constructor( private val getMySellAdsUseCase: GetMySellAdsUseCase, private val getFromSharedPreferenceUseCase: GetFromSharedPreferenceUseCase, private val resourceProvider: ResourceProvider ) : ViewModel() { private var _mySellAdsState = MutableStateFlow<MySellAdsState>(MySellAdsState.Init) val mySellAdsState get() = _mySellAdsState.asStateFlow() fun fetchAllSellAdvertisement(userId: String) { setLoading(true) viewModelScope.launch(Dispatchers.IO) { getMySellAdsUseCase.invoke(userId).collect { when (it) { is Resource.Error -> { withContext(Dispatchers.Main) { setLoading(false) showError(it.message) } } is Resource.Success -> { withContext(Dispatchers.Main) { setLoading(false) } _mySellAdsState.value = MySellAdsState.FetchAllMySellAdsSuccessfully(it.data) } } } } } private fun setLoading(status: Boolean) { when (status) { true -> { _mySellAdsState.value = MySellAdsState.IsLoading(true) } false -> { _mySellAdsState.value = MySellAdsState.IsLoading(false) } } } private fun showError(message: String) { when (message) { resourceProvider.string(R.string.no_internet_connection) -> { _mySellAdsState.value = MySellAdsState.NoInternetConnection(message) } else -> { _mySellAdsState.value = MySellAdsState.ShowError(message) } } } fun <T> getFromSP(key: String, clazz: Class<T>): T { return getFromSharedPreferenceUseCase(key, clazz) } }
0
Kotlin
0
0
d7ff7f448b774aaad929a39686f04de4fd0ec19e
2,781
Books-Island-App
Apache License 2.0
src/test/kotlin/com/github/michaelbull/advent2021/day17/Day17Test.kt
michaelbull
433,565,311
false
null
package com.github.michaelbull.advent2021.day17 import com.github.michaelbull.advent2021.day17.Day17.part1 import kotlin.test.Test import kotlin.test.assertEquals class Day17Test { @Test fun `example 1`() { val input = "target area: x=20..30, y=-10..-5" assertEquals(45, Day17.solve(::part1, input)) } @Test fun `answer 1`() { assertEquals(11781, Day17.solve(::part1)) } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
425
advent-2021
ISC License
app/src/main/java/com/example/eventlink/other/DatabaseLocale.kt
lrnzznn1
795,386,983
false
{"Kotlin": 79706}
@file:OptIn(InternalCoroutinesApi::class) package com.example.eventlink.other import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.internal.synchronized @Database(entities = [EventoLocale::class], version = 3) abstract class DatabaseLocale : RoomDatabase(){ abstract fun DAOEventoLocale():DAOEventoLocale companion object{ @Volatile private var INSTANCE : DatabaseLocale? = null @OptIn(InternalCoroutinesApi::class) fun getInstance(context: Context): DatabaseLocale{ return INSTANCE ?: synchronized(this){ val instance = Room.databaseBuilder( context.applicationContext, DatabaseLocale::class.java, "app_database" ).fallbackToDestructiveMigration().allowMainThreadQueries().build() INSTANCE= instance instance } } fun clearAllTables(){ INSTANCE?.clearAllTables() } } }
0
Kotlin
0
1
c1433b9d21478c4539a5a53a70896a4573f64c21
1,146
EventLink
MIT License
app/src/main/java/com/jacobdamiangraham/groceryhelper/model/DialogInformation.kt
JacobGraham02
790,757,293
false
{"Kotlin": 85761}
package com.jacobdamiangraham.groceryhelper.model data class DialogInformation(val title: String, val message: String) {}
0
Kotlin
0
0
ca7e46b5426723579597dc4181baa65be3f9777e
122
GroceryHelper
MIT License
linea/src/commonMain/kotlin/compose/icons/lineaicons/software/LayoutHeader4boxes.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineaicons.software import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.lineaicons.SoftwareGroup public val SoftwareGroup.LayoutHeader4boxes: ImageVector get() { if (_layoutHeader4boxes != null) { return _layoutHeader4boxes!! } _layoutHeader4boxes = Builder(name = "LayoutHeader4boxes", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.0f, 1.0f) horizontalLineToRelative(62.0f) verticalLineToRelative(14.0f) horizontalLineToRelative(-62.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.0f, 39.0f) horizontalLineToRelative(31.0f) verticalLineToRelative(24.0f) horizontalLineToRelative(-31.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 39.0f) horizontalLineToRelative(31.0f) verticalLineToRelative(24.0f) horizontalLineToRelative(-31.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.0f, 15.0f) horizontalLineToRelative(31.0f) verticalLineToRelative(24.0f) horizontalLineToRelative(-31.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 15.0f) horizontalLineToRelative(31.0f) verticalLineToRelative(24.0f) horizontalLineToRelative(-31.0f) close() } } .build() return _layoutHeader4boxes!! } private var _layoutHeader4boxes: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
3,548
compose-icons
MIT License
sensorlib/src/test/java/com/handmonitor/sensorlib/v1/SensorEventProducerTest.kt
Supercaly
816,167,478
false
{"Kotlin": 130658}
package com.handmonitor.sensorlib.v1 import android.content.Context import android.hardware.Sensor import android.hardware.SensorEventListener import android.hardware.SensorManager import android.os.Handler import android.util.Log import com.handmonitor.sensorlib.mockLog import com.handmonitor.sensorlib.mockSensorEvent import io.mockk.Runs import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.just import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(MockKExtension::class) class SensorEventProducerTest { companion object { private const val WINDOW_SIZE = 100 private const val SAMPLING_P_MS = 20 private const val TIMESTAMP_NS = 314159265358979000L } @MockK private lateinit var mContext: Context @MockK(relaxed = true) private lateinit var mData: SensorSharedData @MockK private lateinit var mSensorManager: SensorManager @MockK private lateinit var mAcc: Sensor @MockK private lateinit var mGyr: Sensor @MockK private lateinit var mHandler: Handler @BeforeEach fun setup() { mockLog() every { mContext.getSystemService(Context.SENSOR_SERVICE) } returns mSensorManager every { mAcc.type } returns Sensor.TYPE_ACCELEROMETER every { mGyr.type } returns Sensor.TYPE_GYROSCOPE } @Test fun `startListening starts supported sensors`() { // Start listening with all sensors supported every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr every { mSensorManager.registerListener(any(), any(), any(), any(), any()) } returns true var listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) listener.startListening() verify { mSensorManager.registerListener(any(), mAcc, any(), any(), any()) mSensorManager.registerListener(any(), mGyr, any(), any(), any()) } // Start listening with only accelerometer supported every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns null listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) listener.startListening() verify { mSensorManager.registerListener(any(), mAcc, any(), any(), any()) } // Start listening with only gyroscope supported every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns null listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) listener.startListening() verify { mSensorManager.registerListener(any(), mGyr, any(), any(), any()) } } @Test fun `startListening skips multiple calls without stopListening`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr every { mSensorManager.registerListener(any(), any(), any(), any(), any()) } returns true val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) listener.startListening() verify { mSensorManager.registerListener(any(), mAcc, any(), any(), any()) mSensorManager.registerListener(any(), mGyr, any(), any(), any()) } listener.startListening() verify(atMost = 1) { mSensorManager.registerListener(any(), mAcc, any(), any(), any()) mSensorManager.registerListener(any(), mGyr, any(), any(), any()) } } @Test fun `stopListening stops listening to sensors`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr every { mSensorManager.unregisterListener(any<SensorEventListener>()) } just Runs val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) listener.stopListening() verify { mSensorManager.unregisterListener(any<SensorEventListener>()) } } @Test fun `startListening, stopListening and then startListening again`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr every { mSensorManager.registerListener(any(), any(), any(), any(), any()) } returns true every { mSensorManager.unregisterListener(any<SensorEventListener>()) } just Runs val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) listener.startListening() verify { mSensorManager.registerListener(any(), mAcc, any(), any(), any()) mSensorManager.registerListener(any(), mGyr, any(), any(), any()) } listener.stopListening() verify { mSensorManager.unregisterListener(any<SensorEventListener>()) } listener.startListening() verify { mSensorManager.registerListener(any(), mAcc, any(), any(), any()) mSensorManager.registerListener(any(), mGyr, any(), any(), any()) } } @Test fun `onSensorChanged appends new data from the correct sensor`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) val accEvent = mockSensorEvent(mAcc) listener.onSensorChanged(accEvent) verify { mData.putAcc(any()) } val gyrEvent = mockSensorEvent(mGyr) listener.onSensorChanged(gyrEvent) verify { mData.putGyro(any()) } } @Test fun `onSensorChanged discards events faster than the sampling rate`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) var timestamp = TIMESTAMP_NS // Send one accelerometer event to simulate the previous ones var accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify { mData.putAcc(any()) } // Accelerometer event faster than the sampling rate is discarded timestamp = TIMESTAMP_NS + 5_000_000 accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(atMost = 1) { mData.putAcc(any()) } // Accelerometer event slightly faster than the sampling rate is discarded timestamp = TIMESTAMP_NS + ((SAMPLING_P_MS * 1_000_000) - SensorEventProducer.SAMPLING_RANGE - 1) accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(atMost = 1) { mData.putAcc(any()) } // Send one gyroscope event to simulate the previous ones timestamp = TIMESTAMP_NS var gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify { mData.putGyro(any()) } // Gyroscope events faster than the sampling rate is discarded timestamp = TIMESTAMP_NS + 5_000_000 gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(atMost = 1) { mData.putGyro(any()) } // Gyroscope event slightly faster than the sampling rate is discarded timestamp = TIMESTAMP_NS + ((SAMPLING_P_MS * 1_000_000) - SensorEventProducer.SAMPLING_RANGE - 1) gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(atMost = 1) { mData.putGyro(any()) } } @Test fun `onSensorChanged accepts events in range of sampling rate`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) var timestamp = TIMESTAMP_NS // Send one accelerometer event to simulate the previous ones var accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify { mData.putAcc(any()) } // Accelerometer event on time is accepted timestamp = TIMESTAMP_NS + 20_000_000 accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(exactly = 2) { mData.putAcc(any()) } // Accelerometer event in range is accepted timestamp += 20_000_000 + SensorEventProducer.SAMPLING_RANGE accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(exactly = 3) { mData.putAcc(any()) } // Accelerometer event in range is accepted timestamp += 20_000_000 - SensorEventProducer.SAMPLING_RANGE accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(exactly = 4) { mData.putAcc(any()) } // Send one gyroscope event to simulate the previous ones timestamp = TIMESTAMP_NS var gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify { mData.putGyro(any()) } // Accelerometer event on time is accepted timestamp = TIMESTAMP_NS + 20_000_000 gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(exactly = 2) { mData.putGyro(any()) } // Accelerometer event in range is accepted timestamp += 20_000_000 + SensorEventProducer.SAMPLING_RANGE gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(exactly = 3) { mData.putGyro(any()) } // Accelerometer event in range is accepted timestamp += 20_000_000 - SensorEventProducer.SAMPLING_RANGE gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(exactly = 4) { mData.putGyro(any()) } } @Test fun `onSensorChanged accepts with hesitation events later than the sampling rate`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) var timestamp = TIMESTAMP_NS // Send one accelerometer event to simulate the previous ones var accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify { mData.putAcc(any()) } // Accelerometer event late is accepted timestamp = TIMESTAMP_NS + 25_000_000 accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(exactly = 2) { mData.putAcc(any()) } verify(exactly = 1) { Log.d(any(), any()) } // Accelerometer event slightly later than the sampling rate is accepted timestamp += (SAMPLING_P_MS * 1_000_000) + SensorEventProducer.SAMPLING_RANGE + 1 accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(exactly = 3) { mData.putAcc(any()) } verify(exactly = 2) { Log.d(any(), any()) } // Send one gyroscope event to simulate the previous ones timestamp = TIMESTAMP_NS var gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify { mData.putGyro(any()) } // Gyroscope event late is accepted timestamp = TIMESTAMP_NS + 25_000_000 gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(exactly = 2) { mData.putGyro(any()) } verify(exactly = 3) { Log.d(any(), any()) } // Gyroscope event slightly later than the sampling rate is accepted timestamp += (SAMPLING_P_MS * 1_000_000) + SensorEventProducer.SAMPLING_RANGE + 1 gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(exactly = 3) { mData.putGyro(any()) } verify(exactly = 4) { Log.d(any(), any()) } } @Test fun `onSensorChanged discards events at the same time or earlier`() { every { mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns mAcc every { mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) } returns mGyr val listener = SensorEventProducer(mContext, mData, mHandler, WINDOW_SIZE, SAMPLING_P_MS) var timestamp = TIMESTAMP_NS // Send one accelerometer event to simulate the previous ones var accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify { mData.putAcc(any()) } // Accelerometer event at the same time than the last is discarded timestamp = TIMESTAMP_NS accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(atMost = 1) { mData.putAcc(any()) } // Accelerometer event at a time before the last is discarded timestamp = TIMESTAMP_NS - 5_000_000 accEvent = mockSensorEvent(mAcc, timestamp = timestamp) listener.onSensorChanged(accEvent) verify(atMost = 1) { mData.putAcc(any()) } verify(exactly = 1) { Log.wtf(any(), any<String>()) } // Send one gyroscope event to simulate the previous ones timestamp = TIMESTAMP_NS var gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify { mData.putGyro(any()) } // Gyroscope event at the same time than the last is discarded timestamp = TIMESTAMP_NS gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(atMost = 1) { mData.putGyro(any()) } // Gyroscope event at a time before the last is discarded timestamp = TIMESTAMP_NS - 5_000_000 gyroEvent = mockSensorEvent(mGyr, timestamp = timestamp) listener.onSensorChanged(gyroEvent) verify(atMost = 1) { mData.putGyro(any()) } verify(exactly = 2) { Log.wtf(any(), any<String>()) } } }
0
Kotlin
0
0
88b22c82d5c28fda9681554f126721d076938e1c
15,352
android-sensorlib
MIT License
src/linuxMain/kotlin/ksubprocess/Process.kt
DrewCarlson
372,115,257
true
{"Kotlin": 107277}
/* * Copyright 2019 Felix Treede * * 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 ksubprocess import kotlinx.cinterop.* import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import ksubprocess.io.PosixException import ksubprocess.io.UnixFileHandle import ksubprocess.iop.fork_and_run import okio.BufferedSink import okio.BufferedSource import okio.FileHandle import okio.buffer import platform.posix.* import kotlin.time.* // safely close an fd private fun Int.closeFd() { if (this != -1) { close(this) } } // read and write fds for a pipe. Also used to store other fds for convenience. private data class RedirectFds(val readFd: Int, val writeFd: Int) { constructor(fd: Int, isRead: Boolean) : this( if (isRead) fd else -1, if (isRead) -1 else fd ) } private fun Redirect.openFds(stream: String): RedirectFds = when (this) { Redirect.Null -> { val fd = open("/dev/null", O_RDWR) if (fd == -1) { throw ProcessConfigException( "Error opening null file for $stream", PosixException.forErrno("open") ) } RedirectFds(fd, stream == "stdin") } Redirect.Inherit -> RedirectFds(-1, -1) Redirect.Pipe -> { val fds = IntArray(2) val piperes = fds.usePinned { pipe(it.addressOf(0)) } if (piperes == -1) { throw ProcessConfigException( "Error opening $stream pipe", PosixException.forErrno("pipe") ) } RedirectFds(fds[0], fds[1]) } is Redirect.Read -> { val fd = open(file, O_RDONLY) if (fd == -1) { throw ProcessConfigException( "Error opening input file $file for $stream", PosixException.forErrno("open") ) } RedirectFds(fd, -1) } is Redirect.Write -> { val fd = open( file, if (append) O_WRONLY or O_APPEND or O_CREAT else O_WRONLY or O_CREAT, 0x0777 ) if (fd == -1) { throw ProcessConfigException( "Error opening output file $file for $stream", PosixException.forErrno("open") ) } RedirectFds(-1, fd) } Redirect.Stdout -> throw IllegalStateException("Redirect.Stdout must be handled separately.") } private fun MemScope.toCStrVector(data: List<String>): CArrayPointer<CPointerVar<ByteVar>> { val res = allocArray<CPointerVar<ByteVar>>(data.size + 1) for (i in data.indices) { res[i] = data[i].cstr.ptr } res[data.size] = null return res } public actual class Process actual constructor( public actual val args: ProcessArguments ) { // set to true when done private var terminated = false // exit status - only valid once terminated = true private var _exitStatus = -1 private val childPid: pid_t // file descriptors for child pipes internal val stdoutFd: Int internal val stderrFd: Int private val stdinFd: Int init { // find executable var executable = args.arguments[0] if ('/' !in executable) { // locate on path executable = findExecutable(executable) ?: throw ProcessConfigException("Unable to find executable '$executable' on PATH") } // verify working directory args.workingDirectory?.let { // try to open it, that's generally enough val dir = opendir(it) ?: throw ProcessConfigException("Working directory '$it' cannot be used!") closedir(dir) } // init redirects/pipes var stdout: RedirectFds? = null var stderr: RedirectFds? = null var stdin: RedirectFds? = null try { // init redirects stdout = args.stdout.openFds("stdout") stderr = if (args.stderr == Redirect.Stdout) { // use stdout RedirectFds(-1, stdout.writeFd) } else { args.stderr.openFds("stderr") } stdin = args.stdin.openFds("stdin") val pid = memScoped { // convert c lists val arguments = toCStrVector(args.arguments) val env = args.environment?.let { toCStrVector(it.map { e -> "${e.key}=${e.value}" }) } fork_and_run( executable = executable, args = arguments, cd = args.workingDirectory, env = env, stdout_fd = stdout.writeFd, stderr_fd = stderr.writeFd, stdin_fd = stdin.readFd, op_stdout = stdout.readFd, op_stderr = stderr.readFd, op_stdin = stdin.writeFd ) } if (pid == -1) { // fork failed throw ProcessException( "Error staring subprocess", PosixException.forErrno("fork") ) } childPid = pid // store file descriptors stdoutFd = stdout.readFd stderrFd = stderr.readFd stdinFd = stdin.writeFd // close unused fds (don't need to watch stderr=stdout here) stdout.writeFd.closeFd() stderr.writeFd.closeFd() stdin.readFd.closeFd() } catch (t: Throwable) { // close fds on error stdout?.readFd?.closeFd() stdout?.writeFd?.closeFd() if (args.stderr != Redirect.Stdout) { stderr?.readFd?.closeFd() stderr?.writeFd?.closeFd() } stdin?.readFd?.closeFd() stdin?.writeFd?.closeFd() throw t } } private fun cleanup() { // close fds as needed. Errors are ignored. stdoutFd.closeFd() stderrFd.closeFd() stdinFd.closeFd() } private fun checkState(block: Boolean = false) { if (terminated) return var options = 0 if (!block) { options = options or WNOHANG } memScoped { val info = alloc<siginfo_t>() val res = waitid(idtype_t.P_PID, childPid.convert(), info.ptr, options or WEXITED) if (res == -1) { // an error throw ProcessException( "Error querying process state", PosixException.forErrno("waitpid") ) } when (info.si_code) { CLD_EXITED, CLD_KILLED, CLD_DUMPED -> { // process has terminated terminated = true _exitStatus = info._sifields._sigchld.si_status cleanup() } } // else we are not done } } public actual val isAlive: Boolean get() { checkState() return !terminated } public actual val exitCode: Int? get() { checkState() return if (terminated) _exitStatus else null } public actual suspend fun waitFor(): Int { while (!terminated) { checkState(true) } return _exitStatus } public actual suspend fun waitFor(timeout: Duration): Int? { require(timeout.isPositive()) { "Timeout must be positive!" } // there is no good blocking solution, so use an active loop with sleep in between. val end = TimeSource.Monotonic.markNow() + timeout while (true) { checkState(false) // return if done or now passed the deadline if (terminated) return _exitStatus if (end.hasPassedNow()) return null delay(POLLING_DELAY) } } public actual fun terminate() { sendSignal(SIGTERM) } public actual fun kill() { sendSignal(SIGKILL) } /** * Send the given signal to the child process. * * @param signal signal number */ public fun sendSignal(signal: Int) { if (terminated) return if (kill(childPid, signal) != 0) { throw ProcessException( "Error terminating process", PosixException.forErrno("kill") ) } } private val stdinHandle: FileHandle? by lazy { if (stdinFd != -1) { val fd = fdopen(stdinFd, "w") ?: throw PosixException.forErrno("fdopen") UnixFileHandle(true, fd) } else null } private val stdoutHandle: FileHandle? by lazy { if (stdoutFd != -1) { val fd = fdopen(stdoutFd, "r") ?: throw PosixException.forErrno("fdopen") UnixFileHandle(false, fd) } else null } private val stderrHandle: FileHandle? by lazy { if (stderrFd != -1) { val fd = fdopen(stderrFd, "r") ?: throw PosixException.forErrno("fdopen") UnixFileHandle(false, fd) } else null } public actual val stdin: BufferedSink? by lazy { stdinHandle?.sink()?.buffer() } public actual val stdout: BufferedSource? by lazy { stdoutHandle?.source()?.buffer() } public actual val stderr: BufferedSource? by lazy { stderrHandle?.source()?.buffer() } public actual val stdoutLines: Flow<String> get() = stdout.lines() public actual val stderrLines: Flow<String> get() = stderr.lines() public actual fun closeStdin() { stdin?.close() stdinHandle?.close() } }
13
Kotlin
0
2
b974087517956a1a7b199b57eb45d61dab03ee78
10,265
ksubprocess
Apache License 2.0
VerifiableCredential/src/main/java/com/merative/watson/healthpass/verifiablecredential/models/credential/CredentialSchema.kt
digitalhealthpass
563,978,682
false
{"Kotlin": 1047923, "HTML": 79495, "Python": 22113, "Java": 1959}
package com.merative.watson.healthpass.verifiablecredential.models.credential import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class CredentialSchema( @SerializedName("id") var id: String?, @SerializedName("type") var type: String? ) : Parcelable
0
Kotlin
0
0
2b086f6fad007d1a574f8f0511fff0e65e100930
346
dhp-android-app
Apache License 2.0
src/commonMain/kotlin/com/jeffpdavidson/kotwords/model/Crossword.kt
jpd236
143,651,464
false
null
package com.jeffpdavidson.kotwords.model import com.jeffpdavidson.kotwords.formats.FONT_FAMILY_TIMES_ROMAN import com.jeffpdavidson.kotwords.formats.Pdf.asPdf import com.jeffpdavidson.kotwords.formats.PdfFontFamily import com.jeffpdavidson.kotwords.formats.Puzzleable /** * A representation of a crossword puzzle with standard numbering. * * For non-standard words/numbering, use [Puzzle] directly. * * @constructor Construct a new puzzle. * @param title The title of the puzzle. * @param creator The author of the puzzle. * @param copyright The copyright of the puzzle. * @param description Optional notes about the puzzle. * @param grid The grid of [Puzzle.Cell]s in the form of a list of rows going from top to bottom, with * each row going from left to right. * @param acrossClues Mapping from across clue number to the clue for that number. * @param downClues Mapping from down clue number to the clue for that number. * @param hasHtmlClues Whether clue contents are in HTML. */ data class Crossword( val title: String, val creator: String, val copyright: String, val description: String = "", val grid: List<List<Puzzle.Cell>>, val acrossClues: Map<Int, String>, val downClues: Map<Int, String>, val hasHtmlClues: Boolean = false, ) : Puzzleable { init { // Validate that grid is a rectangle. val width = grid[0].size grid.forEachIndexed { index, row -> require(row.size == width) { "Invalid grid - row $index has width ${row.size} but should be $width" } } // TODO: Validate standard grid numbering / clues. } override fun asPuzzle(): Puzzle { val acrossPuzzleClues = mutableListOf<Puzzle.Clue>() val downPuzzleClues = mutableListOf<Puzzle.Clue>() val words = mutableListOf<Puzzle.Word>() // Generate numbers and words based on standard crossword numbering. val gridNumbers = mutableMapOf<Pair<Int, Int>, Int>() forEachCell(grid) { x, y, clueNumber, isAcross, isDown, _ -> if (clueNumber != null) { gridNumbers[x to y] = clueNumber } if (isAcross) { val word = mutableListOf<Puzzle.Coordinate>() var i = x while (i < grid[y].size && !grid[y][i].cellType.isBlack()) { word.add(Puzzle.Coordinate(x = i, y = y)) i++ } if (clueNumber != null && acrossClues.containsKey(clueNumber)) { acrossPuzzleClues.add( Puzzle.Clue(clueNumber, "$clueNumber", acrossClues[clueNumber]!!) ) words.add(Puzzle.Word(clueNumber, word)) } } if (isDown) { val word = mutableListOf<Puzzle.Coordinate>() var j = y while (j < grid.size && !grid[j][x].cellType.isBlack()) { word.add(Puzzle.Coordinate(x = x, y = j)) j++ } if (clueNumber != null && downClues.containsKey(clueNumber)) { downPuzzleClues.add( Puzzle.Clue(1000 + clueNumber, "$clueNumber", downClues[clueNumber]!!) ) words.add(Puzzle.Word(1000 + clueNumber, word)) } } } val acrossTitle = if (hasHtmlClues) "<b>Across</b>" else "Across" val downTitle = if (hasHtmlClues) "<b>Down</b>" else "Down" return Puzzle( title, creator, copyright, description, grid.mapIndexed { y, row -> row.mapIndexed { x, cell -> val number = gridNumbers[x to y] if (number == null) { cell } else { cell.copy(number = number.toString()) } } }, listOf(Puzzle.ClueList(acrossTitle, acrossPuzzleClues), Puzzle.ClueList(downTitle, downPuzzleClues)), words.sortedBy { it.id }, hasHtmlClues = hasHtmlClues, ) } /** * Render this crossword as a PDF document. * * @param fontFamily Font family to use for the PDF. * @param blackSquareLightnessAdjustment Percentage (from 0 to 1) indicating how much to brighten black/colored * squares (i.e. to save ink). 0 indicates no adjustment; 1 would be fully * white. */ fun asPdf( fontFamily: PdfFontFamily = FONT_FAMILY_TIMES_ROMAN, blackSquareLightnessAdjustment: Float = 0f ): ByteArray = asPuzzle().asPdf(fontFamily, blackSquareLightnessAdjustment) companion object { /** Execute the given function for each cell in the grid. */ fun forEachCell( grid: List<List<Puzzle.Cell>>, fn: ( x: Int, y: Int, clueNumber: Int?, isAcross: Boolean, isDown: Boolean, cell: Puzzle.Cell ) -> Unit ) { var currentClueNumber = 1 for (y in grid.indices) { for (x in grid[y].indices) { if (grid[y][x].cellType.isBlack()) { fn( x, y, /* clueNumber= */ null, /* isAcross= */ false, /* isDown= */ false, grid[y][x] ) } else { val isAcross = needsAcrossNumber(grid, x, y) val isDown = needsDownNumber(grid, x, y) val clueNumber = if (isAcross || isDown) { currentClueNumber++ } else { null } fn(x, y, clueNumber, isAcross, isDown, grid[y][x]) } } } } /** Execute the given function for each numbered cell in the given grid. */ fun forEachNumberedCell( grid: List<List<Puzzle.Cell>>, fn: ( x: Int, y: Int, clueNumber: Int, isAcross: Boolean, isDown: Boolean ) -> Unit ) { forEachCell(grid) { x, y, clueNumber, isAcross, isDown, _ -> if (isAcross || isDown) { fn(x, y, clueNumber!!, isAcross, isDown) } } } private fun needsAcrossNumber(grid: List<List<Puzzle.Cell>>, x: Int, y: Int): Boolean { return !grid[y][x].cellType.isBlack() && (x == 0 || grid[y][x - 1].cellType.isBlack()) && (x + 1 < grid[0].size && !grid[y][x + 1].cellType.isBlack()) } private fun needsDownNumber(grid: List<List<Puzzle.Cell>>, x: Int, y: Int): Boolean { return !grid[y][x].cellType.isBlack() && (y == 0 || grid[y - 1][x].cellType.isBlack()) && (y + 1 < grid.size && !grid[y + 1][x].cellType.isBlack()) } } }
10
Kotlin
2
10
8055daf8a9117ee3d8e5189ffc8e54ce2744277f
7,372
kotwords
Apache License 2.0
app/src/main/java/com/tapcrew/rickmorty/alfonso_sotelo/di/NetworkModule.kt
poncho10101
306,465,475
false
null
package com.tapcrew.rickmorty.alfonso_sotelo.di import com.haroldadmin.cnradapter.NetworkResponseAdapterFactory import com.tapcrew.rickmorty.alfonso_sotelo.repository.remote.NetworkConstants import com.tapcrew.rickmorty.alfonso_sotelo.repository.remote.RickMortyService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @InstallIn(ApplicationComponent::class) @Module class NetworkModule { @Singleton @Provides fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() } @Singleton @Provides fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(NetworkConstants.SERVER_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(NetworkResponseAdapterFactory()) .client(okHttpClient) .build() } @Singleton @Provides fun providePortfolioService(retrofit: Retrofit): RickMortyService { return retrofit.create(RickMortyService::class.java) } }
0
Kotlin
0
0
865048675a8c20d76f273022ad5e84c59193d173
1,442
rickandmorty
Apache License 2.0
frogoadmob/src/main/java/com/frogobox/admob/ui/IFrogoAdmobActivity.kt
amirisback
218,685,692
false
null
package com.frogobox.admob.ui import com.frogobox.admob.core.IFrogoAdmob import com.google.android.gms.ads.AdView /* * Created by faisalamir on 01/07/21 * FrogoAdmob * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2021 FrogoBox Inc. * All rights reserved * */ interface IFrogoAdmobActivity { // Setup Admob Publisher fun setupAdsPublisher(mPublisherId: String) // Setup Admob Banner fun setupAdsBanner(mAdUnitId: String) // Setup Admob Interstitial fun setupAdsInterstitial(mAdUnitId: String) // Setup Admob Rewarded fun setupAdsRewarded(mAdUnitId: String) // Setup Admob RewardedInterstitial fun setupAdsRewardedInterstitial(mAdUnitId: String) // Show Banner Ads fun setupShowAdsBanner(mAdView: AdView) // Show Interstitial Ads fun setupShowAdsInterstitial() // Show Rewarded Ads fun setupShowAdsRewarded(callback: IFrogoAdmob.UserEarned) // Show Rewarded Interstitial Ads fun setupShowAdsRewardedInterstitial(callback: IFrogoAdmob.UserEarned) }
3
Kotlin
8
30
7f5cad584689a83f837913584ea195e50d0701f3
1,179
frogo-admob
Apache License 2.0
app/src/main/java/com/codility/roomdatabase/database/UserModelDao.kt
AndroidCodility
132,444,009
false
null
package com.codility.roomdatabase.database import android.arch.lifecycle.LiveData import android.arch.persistence.room.* import android.arch.persistence.room.OnConflictStrategy.REPLACE import com.codility.roomdatabase.User @Dao interface UserModelDao { @Query("select * from User") fun getAllUserItems(): LiveData<List<User>> @Query("select * from User where id = :id") fun getItemById(id: String): User @Insert(onConflict = REPLACE) fun addUserModel(user: User) @Update fun updateUser(user: User) @Delete fun deleteUser(user: User) @Insert fun insertAll(vararg users: User) @Query("delete from User") fun deleteAll() }
1
Kotlin
1
1
c9ac4d72de8e5b8bb2f2beb8464ae81f634a1d39
685
RoomDatabase
MIT License
core-data/src/main/java/io/github/zohrevand/dialogue/core/data/repository/OfflineFirstContactsRepository.kt
zohrevand
510,113,579
false
{"Kotlin": 271495}
package io.github.zohrevand.dialogue.core.data.repository import io.github.zohrevand.core.model.data.Contact import io.github.zohrevand.dialogue.core.data.model.asEntity import io.github.zohrevand.dialogue.core.database.dao.ContactDao import io.github.zohrevand.dialogue.core.database.model.ContactEntity import io.github.zohrevand.dialogue.core.database.model.asExternalModel import javax.inject.Inject import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class OfflineFirstContactsRepository @Inject constructor( private val contactDao: ContactDao ) : ContactsRepository { override fun getContact(jid: String): Flow<Contact> = contactDao.getContactEntity(jid).map(ContactEntity::asExternalModel) override fun getContactsStream(): Flow<List<Contact>> = contactDao.getContactEntitiesStream() .map { it.map(ContactEntity::asExternalModel) } override fun getShouldAddToRosterStream(): Flow<List<Contact>> = contactDao.getShouldAddToRosterStream() .map { it.map(ContactEntity::asExternalModel) } override suspend fun updateContacts(contacts: List<Contact>) = contactDao.upsert(contacts.map(Contact::asEntity)) }
1
Kotlin
2
11
9607aed6f182d3eb051e5da4cee6ddf82c659690
1,209
dialogue
Apache License 2.0
app/src/main/java/com/example/myapplication/graphs/RootNavGraph.kt
Osman0812
698,538,398
false
{"Kotlin": 185794}
package com.example.myapplication.graphs import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.navigation import com.example.myapplication.ui.screen.home.HomeScreen import com.example.myapplication.ui.screen.login.LoginScreen import com.example.myapplication.ui.screen.login.LoginViewModel import com.example.myapplication.ui.screen.home.movieshome.MoviesHomeScreen import com.example.myapplication.ui.screen.home.movieshome.MoviesHomeScreenViewModel import com.example.myapplication.ui.screen.splash.SplashScreen import com.example.myapplication.ui.screen.home.tvseries.TvSeriesScreen import com.example.myapplication.ui.screen.home.tvseries.TvSeriesViewModel import com.example.myapplication.ui.screen.webview.WebViewScreen @Composable fun RootNavGraph( navController: NavHostController, ) { NavHost( navController = navController, route = Graph.ROOT, startDestination = Graph.HOME ) { authNavGraph( navHostController = navController ) composable(route = Graph.HOME) { HomeScreen() } } } object Graph { const val ROOT = "root_graph" const val AUTHENTICATION = "auth_graph" const val HOME = "home_graph" }
0
Kotlin
0
0
c83e22c25e6cf88b00eeb10eb523683a4e518b80
1,377
MoveeApp
MIT License
great-wall-server/src/main/kotlin/cc/shacocloud/greatwall/service/client/dto/output/CertificateListOutput.kt
Lorwell
830,322,172
false
{"TypeScript": 447508, "Kotlin": 425986, "JavaScript": 3275, "CSS": 2340, "Shell": 1157, "Less": 726, "HTML": 344}
package cc.shacocloud.greatwall.service.client.dto.output import com.fasterxml.jackson.annotation.JsonAlias /** * ่ฏไนฆ่ฏฆๆƒ…ๆŽฅๅฃ็š„่พ“ๅ‡บ * * [ๆ–‡ๆกฃ](https://www.yuque.com/osfipin/letsencrypt/rwsy01) */ data class CertificateListOutput( val c: Int, val m: String, val v: CertificateListVOutput ) data class CertificateListVOutput( val all: Int, val mpage: Int, val pnum: Int, val num: Int, val list: List<CertificateListDataOutput>, ) data class CertificateListDataOutput( /** * ่ฏไนฆ่‡ชๅŠจ็Šถๆ€ */ @JsonAlias("auto_status") val autoStatus: String, /** * ๅŸŸๅ๏ผŒๆ•ฐ็ป„ */ val domains: List<String>, /** * ่ฏไนฆid */ val id: String, /** * ่ฏไนฆๅค‡ๆณจ */ val mark: String, /** * ๆ˜ฏๅฆไฝฟ็”จ็‹ฌ็ซ‹้€š้“ */ val quicker: Boolean, /** * ็Šถๆ€ */ val status: String, /** * ๅˆ›ๅปบๆ—ถ้—ด */ @JsonAlias("time_add") val timeAdd: String, /** * ่ฏไนฆๅˆฐๆœŸๆ—ถ้—ด(ๆˆ–้ชŒ่ฏๆˆช่‡ณๆ—ถ้—ด) */ @JsonAlias("time_end") val timeEnd: String )
0
TypeScript
0
11
0bb9f6b4d567a85289bd176a9bc4b2ae528b09f4
1,030
great-wall
Apache License 2.0
codeSnippets/snippets/client-parallel-requests/src/test/kotlin/ApplicationTest.kt
ktorio
278,572,893
false
null
import e2e.WithTestServer import e2e.defaultServer import e2e.readString import e2e.runGradleAppWaiting import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class ApplicationTest: WithTestServer() { override val server = defaultServer { routing { get("/path1") { call.respondText { "path1" } } get("/path2") { call.respondText { "path2" } } } } @Test fun concatenatedResponseFromBothRequests(): Unit = runBlocking { assertEquals("path1\npath2\n", runGradleAppWaiting().inputStream.readString()) } }
5
Kotlin
94
95
4ede19d93a98dd25c3e1665702f13a8468a364aa
692
ktor-documentation
Apache License 2.0
src/main/kotlin/dev3/blockchainapiservice/features/payout/service/PinataIpfsService.kt
0xDev3
539,904,697
false
{"Kotlin": 4025801, "Java": 200980, "Solidity": 13345, "HTML": 2675}
package dev3.blockchainapiservice.features.payout.service import com.fasterxml.jackson.databind.JsonNode import dev3.blockchainapiservice.exception.IpfsUploadFailedException import dev3.blockchainapiservice.features.payout.model.json.PinataResponse import dev3.blockchainapiservice.features.payout.util.IpfsHash import mu.KLogging import org.springframework.stereotype.Service import org.springframework.web.client.RestClientException import org.springframework.web.client.RestTemplate @Service class PinataIpfsService(private val pinataRestTemplate: RestTemplate) : IpfsService { companion object : KLogging() override fun pinJsonToIpfs(json: JsonNode): IpfsHash { try { val response = pinataRestTemplate.postForEntity("/pinning/pinJSONToIPFS", json, PinataResponse::class.java) if (response.statusCode.is2xxSuccessful) { return response.body?.ipfsHash?.let { IpfsHash(it) } ?: run { logger.warn { "IPFS hash is missing on upload response" } throw IpfsUploadFailedException() } } logger.warn { "IPFS upload failed" } throw IpfsUploadFailedException() } catch (ex: RestClientException) { logger.warn(ex) { "IPFS client call exception" } throw IpfsUploadFailedException() } } }
0
Kotlin
0
0
a98a03cf75fc45ccf96c5cbb50a6c0ab0dd3e549
1,375
blockchain-api-service
MIT License
src/main/java/com/github/shynixn/blockball/impl/service/YamlServiceImpl.kt
Shynixn
78,865,055
false
{"Kotlin": 632990, "Dockerfile": 2558}
package com.github.shynixn.blockball.impl.service import com.github.shynixn.blockball.deprecated.YamlService import org.bukkit.configuration.MemorySection import org.bukkit.configuration.file.YamlConfiguration import java.nio.file.Path @Deprecated("Use FastXml serializer.") class YamlServiceImpl : YamlService { /** * Writes the given [content] to the given [path]. */ override fun write(path: Path, content: Map<String, Any?>) { val configuration = YamlConfiguration() val key = content.keys.toTypedArray()[0] configuration.set(key, content[key]) configuration.save(path.toFile()) } /** * Reads the content from the given [path]. */ override fun read(path: Path): Map<String, Any?> { val configuration = YamlConfiguration() configuration.load(path.toFile()) val section = configuration.getValues(true) deserialize(section) return section } /** * Deserializes the given section. */ private fun deserialize(section: MutableMap<String, Any?>) { for (key in section.keys) { if (section[key] is MemorySection) { val map = (section[key] as MemorySection).getValues(false) deserialize(map) section[key] = map } } } }
2
Kotlin
26
66
28709f1d04fb60e16ae89e289b40faa007e67749
1,342
BlockBall
Apache License 2.0
src/main/kotlin/no/nav/tjenestepensjon/simulering/v1/models/error/StillingsprosentListeKanIkkeLeveres.kt
navikt
184,583,998
false
{"Kotlin": 337080, "Dockerfile": 97}
package no.nav.tjenestepensjon.simulering.v1.models.error class StillingsprosentListeKanIkkeLeveres : StelvioFault()
2
Kotlin
0
0
0b99839a4587253ce1d42d2a5594f52f98bbfc80
117
tjenestepensjon-simulering
MIT License
app/src/main/kotlin/com/github/feed/sample/ext/ViewModelExt.kt
markspit93
105,769,386
false
null
package com.github.feed.sample.ext import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider inline fun <reified T : ViewModel> ViewModelProvider.get(): T = get(T::class.java)
0
Kotlin
0
0
f37bbf8656e2e3964212fd12d4ce3864df553590
208
Github-Feed-Sample
Apache License 2.0
app/src/main/java/com/gggames/hourglass/presentation/gameon/Reducer.kt
giladgotman
252,945,764
false
null
package com.gggames.hourglass.presentation.gameon
25
Kotlin
0
0
0f0fa11fbe1131387148e4d6d1b7d85c23d6e5f0
50
celebs
MIT License
vector/src/main/java/im/vector/app/features/voicebroadcast/usecase/GetVoiceBroadcastUseCase.kt
watcha-fr
558,303,557
false
null
/* * Copyright (c) 2022 New Vector Ltd * * 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 im.vector.app.features.voicebroadcast.usecase import im.vector.app.features.voicebroadcast.model.VoiceBroadcastEvent import im.vector.app.features.voicebroadcast.model.asVoiceBroadcastEvent import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.events.model.RelationType import org.matrix.android.sdk.api.session.getRoom import timber.log.Timber import javax.inject.Inject class GetVoiceBroadcastUseCase @Inject constructor( private val session: Session, ) { fun execute(roomId: String, eventId: String): VoiceBroadcastEvent? { val room = session.getRoom(roomId) ?: error("Unknown roomId: $roomId") Timber.d("## GetVoiceBroadcastUseCase: get voice broadcast $eventId") val initialEvent = room.timelineService().getTimelineEvent(eventId)?.root?.asVoiceBroadcastEvent() // Fallback to initial event val relatedEvents = room.timelineService().getTimelineEventsRelatedTo(RelationType.REFERENCE, eventId).sortedBy { it.root.originServerTs } return relatedEvents.mapNotNull { it.root.asVoiceBroadcastEvent() }.lastOrNull() ?: initialEvent } }
41
Kotlin
0
0
4b7f030dfc1adc9524fe39b14c29cc6e533bc713
1,746
watcha-android
Apache License 2.0
app/src/main/java/com/example/notate/BroadCast/AlarmReceiver.kt
KareemHussen
493,690,143
false
null
package com.example.notate.BroadCast import android.app.PendingIntent import android.app.TaskStackBuilder import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.example.notate.R import com.example.notate.uii.fragments.MainActivity import kotlinx.android.synthetic.main.fragment_detailes.* const val id = 1 const val channelId = "channelId" class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { var args = intent!!.getStringExtra("noteTitle") var bundle = Bundle() bundle.putString("note" , args.toString()) val intent = Intent(context , MainActivity::class.java) val pendingIntent = TaskStackBuilder.create(context).run { addNextIntentWithParentStack(intent) getPendingIntent(1 , PendingIntent.FLAG_UPDATE_CURRENT) } val builder = NotificationCompat.Builder(context!! , channelId) .setSmallIcon(R.drawable.reminder_icon) .setContentTitle("My Notes") .setContentText(args!!.toString()) .setAutoCancel(true) .setContentIntent(pendingIntent) .setDefaults(NotificationCompat.DEFAULT_ALL) .setPriority(NotificationCompat.PRIORITY_HIGH) val notificationManger = NotificationManagerCompat.from(context) notificationManger.notify(id , builder.build()) } }
0
Kotlin
0
1
ce4cfc7237948c827ff2bb19f73f33541fd82192
1,573
Notate
The Unlicense
app/src/main/java/com/github/wangyung/app/model/AnimationParameterSet.kt
wangyung
384,290,194
false
null
package com.github.wangyung.app.model import com.github.wangyung.persona.particle.ParticleSystemParameters import com.github.wangyung.persona.particle.generator.parameter.RandomizeParticleGeneratorParameters import com.github.wangyung.persona.particle.transformation.TransformationParameters data class AnimationParameterSet( val generatorParameters: RandomizeParticleGeneratorParameters, val particleSystemParameters: ParticleSystemParameters, val transformationParameters: TransformationParameters, )
0
Kotlin
1
6
e4c0b87c600e7756232da7963505b01f49b48b3b
517
persona
Apache License 2.0
app/src/main/java/com/abbaraees/weatherly/ui/components/WeatherInfo.kt
Abbaraees
777,191,517
false
{"Kotlin": 49003}
package com.abbaraees.weatherly.ui.components import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.abbaraees.weatherly.R @Composable fun WeatherInfo( cityName: String, temperature: String, weatherCondition: String, time: String, @DrawableRes weatherIcon: Int, modifier: Modifier = Modifier ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), modifier = modifier ) { Text( text = cityName, style = MaterialTheme.typography.headlineLarge, modifier = Modifier.padding(bottom = 16.dp) ) Image( painter = painterResource(id = weatherIcon), contentDescription = "Weather Icon", contentScale = ContentScale.Fit ) Text( text = temperature, style = MaterialTheme.typography.headlineMedium ) Text( text = weatherCondition, style = MaterialTheme.typography.labelLarge ) Text( text = time, style = MaterialTheme.typography.labelLarge ) } } @Preview(showBackground = true) @Composable fun PreviewWeatherInfo() { WeatherInfo( cityName = "Daura", temperature = "32 C", weatherCondition = "Partly Cloudy", time = "7:30 AM", weatherIcon = R.drawable.cloudy ) }
0
Kotlin
0
0
0fd1adf393e36dde1868ec7ffb3af70a122cb462
2,071
weatherly
Apache License 2.0
libB/src/main/java/package_B_2/Foo_B_212.kt
lekz112
118,451,085
false
null
package package_B_2 class Foo_B_212 { fun foo0() { var i=0 i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() i+=Math.random().toInt() Foo_B_211().foo0() } }
0
Kotlin
0
0
8182b7f6e92f9d65efb954c32ca640fe50ae6b79
581
ModuleTest
Apache License 2.0
core/src/main/kotlin/consulo/toml/ide/TomlASTFactory.kt
consulo
811,997,471
false
{"Kotlin": 183900, "Lex": 2190, "HTML": 167}
package consulo.toml.ide import consulo.annotation.component.ExtensionImpl import consulo.language.ast.IElementType import consulo.language.impl.ast.ASTCompositeFactory import consulo.language.impl.ast.CompositeElement import jakarta.annotation.Nonnull import org.toml.lang.psi.TomlElementTypes import org.toml.lang.psi.impl.* import java.util.* import java.util.function.Function @ExtensionImpl class TomlASTFactory : ASTCompositeFactory, TomlElementTypes { private val map: MutableMap<IElementType, Function<IElementType, CompositeElement>> = HashMap() init { map[TomlElementTypes.KEY_VALUE] = Function<IElementType, CompositeElement> { type: IElementType -> TomlKeyValueImpl(type) } map[TomlElementTypes.KEY_SEGMENT] = Function<IElementType, CompositeElement> { type: IElementType -> TomlKeySegmentImpl(type) } map[TomlElementTypes.KEY] = Function<IElementType, CompositeElement> { type: IElementType -> TomlKeyImpl(type) } map[TomlElementTypes.LITERAL] = Function<IElementType, CompositeElement> { type: IElementType -> TomlLiteralImpl(type) } map[TomlElementTypes.ARRAY] = Function<IElementType, CompositeElement> { type: IElementType -> TomlArrayImpl(type) } map[TomlElementTypes.TABLE] = Function<IElementType, CompositeElement> { type: IElementType -> TomlTableImpl(type) } map[TomlElementTypes.TABLE_HEADER] = Function<IElementType, CompositeElement> { type: IElementType -> TomlTableHeaderImpl(type) } map[TomlElementTypes.INLINE_TABLE] = Function<IElementType, CompositeElement> { type: IElementType -> TomlInlineTableImpl(type) } map[TomlElementTypes.ARRAY_TABLE] = Function<IElementType, CompositeElement> { type: IElementType -> TomlArrayTableImpl(type) } } @Nonnull override fun createComposite(@Nonnull type: IElementType): CompositeElement { val function = map[type]!! return function.apply(type) } override fun test(type: IElementType): Boolean { return map.containsKey(type) } }
0
Kotlin
0
0
3fc05880ce70d58ec09da849837c4104fdf4479c
2,139
consulo-toml
Apache License 2.0
common/src/commonMain/kotlin/model/CwpRatingStub.kt
crowdproj
518,714,370
false
null
package com.crowdproj.rating.common.model /** * @author <NAME> * @version 1.0 * @date 13.03.2023 12:36 */ enum class CwpRatingStub { NONE, SUCCESS, NOT_FOUND, BAD_ID, }
0
Kotlin
2
0
668859f333e9d397870f4492463dc948bdfea83a
192
crowdproj-ratings
Apache License 2.0
app/src/main/kotlin/day02/Day02.kt
W3D3
726,573,421
false
{"Kotlin": 81242}
package day02 import common.InputRepo import common.readSessionCookie import common.solve import util.splitIntoPair fun main(args: Array<String>) { val day = 2 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay02Part1, ::solveDay02Part2) } fun solveDay02Part1(input: List<String>): Int { val games = input.map { parseGameRecord(it) } println(games) var sum = 0 for ((id, pulls) in games) { val invalidPull = pulls.find { map -> map.getOrDefault(Color.RED, 0) > 12 || map.getOrDefault(Color.GREEN, 0) > 13 || map.getOrDefault(Color.BLUE, 0) > 14 } if (invalidPull != null) { println(invalidPull) println(id) } else { sum += id } } return sum } fun solveDay02Part2(input: List<String>): Int { val games = input.map { parseGameRecord(it) } println(games) val sum = games.sumOf { val pulls = it.pulls val redPull = pulls.maxBy { map -> map.getOrDefault(Color.RED, 0) }.getOrDefault(Color.RED, 0) val greenPull = pulls.maxBy { map -> map.getOrDefault(Color.GREEN, 0) }.getOrDefault(Color.GREEN, 0) val bluePull = pulls.maxBy { map -> map.getOrDefault(Color.BLUE, 0) }.getOrDefault(Color.BLUE, 0) redPull * greenPull * bluePull } return sum } enum class Color { BLUE, RED, GREEN, } private fun parseGameRecord(line: String): GameRecord { val moveRegex = """Game (\d+): (.*)$""".toRegex() return moveRegex.matchEntire(line) ?.destructured ?.let { (id, pulls) -> GameRecord(id.toInt(), pulls.split(';').map { s -> s.split(',').map { it.trim().splitIntoPair(" ") .let { pair -> Pair(Color.valueOf(pair.second.uppercase()), pair.first.toInt()) } }.toMap() }) } ?: throw IllegalArgumentException("Bad input '$line'") } data class GameRecord(val id: Int, val pulls: List<Map<Color, Int>>)
0
Kotlin
0
0
da174508f6341f85a1a92159bde3ecd5dcbd3c14
2,159
AdventOfCode2023
Apache License 2.0
app/src/androidTest/java/org/wikipedia/fintechuitest/espresso/screens/ExploreScreen.kt
Bluemoonnoomeulb
632,000,606
false
null
package org.wikipedia.fintechuitest.espresso.screens import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.matcher.ViewMatchers.withId import org.wikipedia.R class ExploreScreen { private val buttonNavMoreMatcher = withId(R.id.nav_more_container) private val buttonOpenSettingsMatchers = withId(R.id.main_drawer_settings_container) private val buttonLogInMatchers = withId(R.id.main_drawer_account_container) fun clickNavMoreButton() { onView(buttonNavMoreMatcher) .perform(click()) } fun clickSettingsButton() { onView(buttonOpenSettingsMatchers) .perform(click()) } fun clickLogInButton() { onView(buttonLogInMatchers) .perform(click()) } companion object { inline operator fun invoke(crossinline block: ExploreScreen.() -> Unit) = ExploreScreen().block() } }
0
Kotlin
0
0
1b548d4ba1bbcaf68a0c6fc5ea69e04f613f750a
956
autotests_for_wiki
Apache License 2.0
LI61N/demos/hvac-spring-mvc/src/main/kotlin/isel/leic/daw/hvac/common/model/simulation/SensorSimulator.kt
isel-leic-daw
347,182,700
false
null
package isel.leic.daw.hvac.common.model.simulation import isel.leic.daw.hvac.common.model.Sensor import isel.leic.daw.hvac.common.model.Temperature import isel.leic.daw.threadSafe import org.springframework.stereotype.Component import kotlin.properties.Delegates.observable /** * Implementation of a sensor simulator that always reports the last written temperature. */ @Component class SensorSimulator(initialTemperature: Temperature = Temperature.HUMAN_COMFORT) : Sensor { override var temperature: Temperature by threadSafe(observable(initialTemperature) { _, _, newValue: Temperature -> onChange?.invoke(newValue) }) @Volatile override var onChange: ((Temperature) -> Unit)? = null }
5
Kotlin
7
36
73225fff919054f5ce74cbcc077861129b28c99f
718
2021v-public
Apache License 2.0
app/src/main/java/com/derdilla/spiritLevel/MainActivity.kt
NobodyForNothing
666,740,984
false
{"Kotlin": 9308}
package com.derdilla.spiritLevel import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement.Center import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import java.text.DecimalFormat import kotlin.math.abs import kotlin.math.sign class MainActivity : ComponentActivity(), SensorEventListener { private lateinit var sensorManager: SensorManager private var gravitySensor: Sensor? = null private var accelerometer: Sensor? = null private var useFallback = false private var x = 0.0f private var y = 0.0f private var xCorrection = 0.0f private var yCorrection = 0.0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager determineSensors() draw() } override fun onSensorChanged(event: SensorEvent?) { x = event!!.values[0] y = event.values[1] draw() } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { onPause() determineSensors() onResume() } override fun onResume() { super.onResume() if (useFallback) { sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) } else { sensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_NORMAL) } } override fun onPause() { super.onPause() sensorManager.unregisterListener(this) } private fun determineSensors() { if (sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null) { val gravSensors: List<Sensor> = sensorManager.getSensorList(Sensor.TYPE_GRAVITY) gravitySensor = gravSensors.reduce { a, b -> if (a.resolution < b.resolution) { a } else { b } } } if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) { val accSensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER) accelerometer = accSensors.reduce { a, b -> if (a.resolution < b.resolution) { a } else { b } } } if (gravitySensor == null) useFallback = true } private fun draw() { val df = DecimalFormat("##.##") setContent { WaterLevelTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( "X: " + df.format((abs(x - xCorrection) / 9.81) * 90) + "ยฐ\n" + " Y: " + df.format((abs(y - yCorrection) / 9.81) * 90) + "ยฐ", modifier = Modifier.paddingFromBaseline(bottom = 20.dp), fontSize = 30.sp, ) Canvas( modifier = Modifier .size(size = 300.dp) ) { drawCircle( color = Color.LightGray, radius = 150.dp.toPx() ) drawCircle( color = Color.Green, radius = 25.dp.toPx() ) drawCircle( color = Color.Black, radius = 10.dp.toPx(), center = Offset( x = (this.size.width.toDp() .toPx() / 2 + sign(x - xCorrection) * f(x - xCorrection) * 250).toDp() .toPx(), y = (this.size.height.toDp() .toPx() / 2 - sign(y - yCorrection) * f(y - yCorrection) * 250).toDp() .toPx() // substract for direction ) ) } IconButton( onClick = { xCorrection = x yCorrection = y }, modifier = Modifier.scale(2f).padding(30.dp) ) { Icon( painter = painterResource(R.drawable.my_location_fill0_wght400_grad0_opsz48), contentDescription = stringResource(id = R.string.calibrate), ) } } } } } } /** * function to calculate the position of the knob returns a value between 0 and 1 */ private fun f(x: Float): Float { return 1 - 1*(1/(0.5* abs(x) + 1)).toFloat() } }
0
Kotlin
0
0
ab705fccd44cedff471b0d4eb9831abef8c22d9d
6,558
spirit-level-android
MIT License
app/src/main/java/com/derdilla/spiritLevel/MainActivity.kt
NobodyForNothing
666,740,984
false
{"Kotlin": 9308}
package com.derdilla.spiritLevel import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement.Center import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import java.text.DecimalFormat import kotlin.math.abs import kotlin.math.sign class MainActivity : ComponentActivity(), SensorEventListener { private lateinit var sensorManager: SensorManager private var gravitySensor: Sensor? = null private var accelerometer: Sensor? = null private var useFallback = false private var x = 0.0f private var y = 0.0f private var xCorrection = 0.0f private var yCorrection = 0.0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager determineSensors() draw() } override fun onSensorChanged(event: SensorEvent?) { x = event!!.values[0] y = event.values[1] draw() } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { onPause() determineSensors() onResume() } override fun onResume() { super.onResume() if (useFallback) { sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) } else { sensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_NORMAL) } } override fun onPause() { super.onPause() sensorManager.unregisterListener(this) } private fun determineSensors() { if (sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null) { val gravSensors: List<Sensor> = sensorManager.getSensorList(Sensor.TYPE_GRAVITY) gravitySensor = gravSensors.reduce { a, b -> if (a.resolution < b.resolution) { a } else { b } } } if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) { val accSensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER) accelerometer = accSensors.reduce { a, b -> if (a.resolution < b.resolution) { a } else { b } } } if (gravitySensor == null) useFallback = true } private fun draw() { val df = DecimalFormat("##.##") setContent { WaterLevelTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( "X: " + df.format((abs(x - xCorrection) / 9.81) * 90) + "ยฐ\n" + " Y: " + df.format((abs(y - yCorrection) / 9.81) * 90) + "ยฐ", modifier = Modifier.paddingFromBaseline(bottom = 20.dp), fontSize = 30.sp, ) Canvas( modifier = Modifier .size(size = 300.dp) ) { drawCircle( color = Color.LightGray, radius = 150.dp.toPx() ) drawCircle( color = Color.Green, radius = 25.dp.toPx() ) drawCircle( color = Color.Black, radius = 10.dp.toPx(), center = Offset( x = (this.size.width.toDp() .toPx() / 2 + sign(x - xCorrection) * f(x - xCorrection) * 250).toDp() .toPx(), y = (this.size.height.toDp() .toPx() / 2 - sign(y - yCorrection) * f(y - yCorrection) * 250).toDp() .toPx() // substract for direction ) ) } IconButton( onClick = { xCorrection = x yCorrection = y }, modifier = Modifier.scale(2f).padding(30.dp) ) { Icon( painter = painterResource(R.drawable.my_location_fill0_wght400_grad0_opsz48), contentDescription = stringResource(id = R.string.calibrate), ) } } } } } } /** * function to calculate the position of the knob returns a value between 0 and 1 */ private fun f(x: Float): Float { return 1 - 1*(1/(0.5* abs(x) + 1)).toFloat() } }
0
Kotlin
0
0
ab705fccd44cedff471b0d4eb9831abef8c22d9d
6,558
spirit-level-android
MIT License
SharedCode/src/commonMain/kotlin/com/architecture/business/weather/repository/WeatherRepository.kt
hoanggiang063
232,681,426
false
null
package com.architecture.business.weather.repository import com.architecture.business.core.repository.BaseRepository import com.architecture.business.weather.info.WeatherInfo import com.architecture.business.weather.usecase.WeatherRequest interface WeatherRepository : BaseRepository<WeatherRequest, WeatherInfo>
0
Kotlin
0
0
f1297ceb5f14f3969f81b1f616a9bf14a923d020
314
simple-clean-multi-platforms
Apache License 2.0
src/main/kotlin/com/qualape/api/utils/Cryptographer.kt
rodrigopedro81
606,270,717
false
null
package com.qualape.api.utils import java.io.UnsupportedEncodingException import java.nio.charset.Charset import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import java.util.* import javax.crypto.BadPaddingException import javax.crypto.Cipher import javax.crypto.IllegalBlockSizeException import javax.crypto.NoSuchPaddingException import javax.crypto.spec.SecretKeySpec object Cryptographer { private const val ALGORITHM_NAME = "Blowfish" private const val CHARSET_NAME = "UTF-8" private val key: ByteArray = "developer".toByteArray() private val cipher: Cipher by lazy { Cipher.getInstance(ALGORITHM_NAME) } @Throws( NoSuchAlgorithmException::class, NoSuchPaddingException::class, InvalidKeyException::class, IllegalBlockSizeException::class, BadPaddingException::class, UnsupportedEncodingException::class ) fun String.cryptographed(): String { val keySpec = SecretKeySpec(key, ALGORITHM_NAME) cipher.init(Cipher.ENCRYPT_MODE, keySpec) return Base64.getEncoder().encodeToString( cipher. doFinal(this.toByteArray(charset(CHARSET_NAME)))) } @Throws( NoSuchAlgorithmException::class, NoSuchPaddingException::class, InvalidKeyException::class, IllegalBlockSizeException::class, BadPaddingException::class ) fun String.decryptographed(): String { val keySpec = SecretKeySpec(key, ALGORITHM_NAME) val bytes = Base64.getDecoder().decode(this) cipher.init(Cipher.DECRYPT_MODE, keySpec) val decrypted = cipher.doFinal(bytes) return String(decrypted, Charset.forName(CHARSET_NAME)) } }
0
Kotlin
0
0
88fa0a93f613a89b13e6d9a4b48d4c93cdfa7a23
1,739
QualApeApi
Apache License 2.0
app/src/main/java/com/example/dndquiz/CheatActivity.kt
MCS374
773,826,057
false
{"Kotlin": 8230}
package com.example.dndquiz import android.app.Activity import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.dndquiz.databinding.ActivityCheatBinding // have a constant const val EXTRA_ANSWER_SHOWN = "com.example.dndquiz.answer_shown" private const val EXTRA_ANSWER_IS_TRUE = "com.example.dndquiz.answer_is_true" class CheatActivity : AppCompatActivity() { private lateinit var binding: ActivityCheatBinding private var answerIsTrue = false; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // activate the binding binding = ActivityCheatBinding.inflate(layoutInflater) setContentView(binding.root) answerIsTrue = intent.getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false) binding.showAnswerButton.setOnClickListener { val answerText=when { answerIsTrue -> R.string.true_button else -> R.string.false_button } binding.answerTextView.setText(answerText) setAnswerShownResult(true) } } private fun setAnswerShownResult (isAnswerShown:Boolean){ val data = Intent().apply{ putExtra (EXTRA_ANSWER_SHOWN, isAnswerShown) } setResult(Activity.RESULT_OK,data) } // set a cheating button listener companion object{ fun newIntent(packageContext: Context, answerIsTrue: Boolean): Intent{ return Intent (packageContext, CheatActivity::class.java).apply{ putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue) } } } }
0
Kotlin
0
0
40687d3dd7767532d90ae49f8b76cd6903c33823
1,695
androidStudioProject
MIT License
app/src/main/java/com/gcode/vastutils/ActivityLauncher.kt
SakurajimaMaii
353,212,367
false
null
/* * Copyright 2022 VastGui * * 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.gcode.vastutils import android.content.Context import android.content.Intent import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.gcode.vastutils.activity.ResultFragment /** * @OriginalAuthor: <NAME> * @OriginalDate: * @EditAuthor: <NAME> * @EditDate: 2022/2/1 */ class ActivityLauncher private constructor(activity: FragmentActivity) { companion object { const val TAG = "ActLauncherUtils" fun init(fragment: Fragment): ActivityLauncher { return init(fragment.requireActivity()) } fun init(activity: FragmentActivity): ActivityLauncher { return ActivityLauncher(activity) } } private var mContext: Context = activity private var mResultFragment: ResultFragment? = null init { mResultFragment = getResultFragment(activity) } private fun getResultFragment(activity: FragmentActivity): ResultFragment { var resultFragment: ResultFragment? = findResultFragment(activity) if (null == resultFragment) { resultFragment = ResultFragment().newInstance() val fragmentManager: FragmentManager = activity.supportFragmentManager fragmentManager .beginTransaction() .add(resultFragment, TAG) .commitAllowingStateLoss() fragmentManager.executePendingTransactions() } return resultFragment } private fun findResultFragment(activity: FragmentActivity) = if (null != activity.supportFragmentManager.findFragmentByTag(TAG)) { activity.supportFragmentManager.findFragmentByTag(TAG) as ResultFragment } else { null } fun startActivityForResult(clazz: Class<*>?, callback: Callback?) { val intent = Intent(mContext, clazz) startActivityForResult(intent, callback) } fun startActivityForResult(intent: Intent?, callback: Callback?) { if (mResultFragment != null) { mResultFragment!!.startActivityForResult(intent, callback) } else { throw RuntimeException("please do init first!") } } interface Callback { fun onActivityResult(resultCode: Int, data: Intent?) } }
3
Kotlin
4
19
62b0adb89d764e8e9107de076a33d2d698069b09
2,927
Utils
Apache License 2.0
presentation/favorites/src/main/java/com/jojalvo/favorites/viewmodel/FavoritesUIState.kt
jose-ojalvo
619,971,179
false
null
package com.jojalvo.favorites.viewmodel /** * @author jojalvo * @since 3/5/23 * @email <EMAIL> */ interface FavoritesUIState<out T> { object Loading : FavoritesUIState<Nothing> data class Error(val throwable: Throwable) : FavoritesUIState<Nothing> data class UsersData<T>(val result: T) : FavoritesUIState<T> object Empty : FavoritesUIState<Nothing> }
0
Kotlin
0
0
1e8528c9868aec7d08e6c3bee5ffbae07d0c769e
378
MobileChallenge
Apache License 2.0
app/src/main/java/com/wcsm/confectionaryadmin/ui/theme/Color.kt
WallaceMartinsTI
835,736,123
false
{"Kotlin": 410093}
package com.wcsm.confectionaryadmin.ui.theme import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) /* * Custom Colors * */ // Colors val StrongDarkPurpleColor = Color(0xFF6C085C) val LightDarkPurpleColor = Color(0xFFD20FB3) val LightRedColor = Color(0xFFDC3545) val ValueColor = Color(0xFF0D6B04) val BrownColor = Color(0xFF47260F) val GrayColor = Color(0xFFACA7A7) val PrimaryColor = Color(0xFF3E0540) val ScreenDescriptionColor = Color(0xFF775378) val ButtonBackgroundColor = Color(0xFFD88BD5) val TextFieldBackgroundColor = Color(0x33FF00C7) val DarkGreenColor = Color(0xFF097107) // Status Colors val QuotationStatusColor = Color(0xFF007BFF) val ConfirmedStatusColor = Color(0xFF28A745) val InProductionStatusColor = Color(0xFFFFF73A) val FinishedStatusColor = Color(0xFF004085) val DeliveredStatusColor = Color(0xFF7800C8) val CancelledStatusColor = LightRedColor // Linear Colors (Brush) val AppBackgroundColor = Brush.horizontalGradient(listOf(Color(0xFFC0B4D7), Color(0xFFF495CF))) val InvertedAppBackgroundColor = Brush.horizontalGradient(listOf(Color(0xFFF495CF), Color(0xFFC0B4D7))) val AppTitleGradientColor = Brush.horizontalGradient(listOf(StrongDarkPurpleColor, LightDarkPurpleColor))
0
Kotlin
0
1
975edc2d7591ce648dd6062218465ff5069e1f8c
1,441
ConfectioneryAdmin
MIT License
src/main/kotlin/net/vyrek/tutorialmod/datagen/ModItemTagProvider.kt
VyrekXD
731,301,810
false
{"Kotlin": 47604, "Java": 3602}
package net.vyrek.tutorialmod.datagen import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider import net.minecraft.registry.RegistryWrapper import net.minecraft.registry.tag.ItemTags import net.vyrek.tutorialmod.item.ModItems import java.util.concurrent.CompletableFuture class ModItemTagProvider( output: FabricDataOutput, completableFuture: CompletableFuture<RegistryWrapper.WrapperLookup> ) : FabricTagProvider.ItemTagProvider(output, completableFuture) { override fun configure(arg: RegistryWrapper.WrapperLookup?) { getOrCreateTagBuilder(ItemTags.TRIMMABLE_ARMOR) .add(ModItems.RUBY_HELMET, ModItems.RUBY_CHESTPLATE, ModItems.RUBY_LEGGINGS, ModItems.RUBY_BOOTS) } }
0
Kotlin
0
1
0d8d03e0882edb3ea1ccdc66a1189ce474612787
754
tutorial-mod
Creative Commons Zero v1.0 Universal
app/src/main/java/com/geovnn/meteoapuane/presentation/provincia/composables/PaginaProvincia.kt
geovnn
806,232,559
false
{"Kotlin": 379465}
package com.geovnn.meteoapuane.presentation.provincia.composables import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Nightlight import androidx.compose.material.icons.filled.WbSunny import androidx.compose.material.icons.outlined.Nightlight import androidx.compose.material.icons.outlined.WbSunny import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.geovnn.meteoapuane.domain.models.ProvinciaPageTab import com.geovnn.meteoapuane.presentation.utils.composables.BodyText import com.geovnn.meteoapuane.presentation.utils.composables.TitleText import kotlinx.coroutines.launch @OptIn(ExperimentalFoundationApi::class) @Composable fun PaginaProvincia( modifier : Modifier = Modifier, uiState: ProvinciaPageTab ) { Column( modifier = modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { val pagerState = rememberPagerState(pageCount = { 2 }) val coroutineScope = rememberCoroutineScope() TabRow(selectedTabIndex = pagerState.currentPage) { Tab( text = { Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = if (pagerState.currentPage == 0) Icons.Filled.WbSunny else Icons.Outlined.WbSunny, contentDescription = "Mattina") Spacer(modifier = modifier.width(3.dp)) Text( text = "Mattina", fontSize = MaterialTheme.typography.titleSmall.fontSize, fontWeight = MaterialTheme.typography.titleSmall.fontWeight, fontFamily = MaterialTheme.typography.titleSmall.fontFamily, fontStyle = MaterialTheme.typography.titleSmall.fontStyle ) } }, selected = pagerState.currentPage == 0, onClick = { coroutineScope.launch { pagerState.animateScrollToPage(0) } } ) Tab( text = { Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = if (pagerState.currentPage == 1) Icons.Filled.Nightlight else Icons.Outlined.Nightlight, contentDescription = "Sera") Spacer(modifier = modifier.width(3.dp)) Text(text = "Sera", fontSize = MaterialTheme.typography.titleSmall.fontSize, fontWeight = MaterialTheme.typography.titleSmall.fontWeight, fontFamily = MaterialTheme.typography.titleSmall.fontFamily, fontStyle = MaterialTheme.typography.titleSmall.fontStyle) } }, selected = pagerState.currentPage == 1, onClick = { coroutineScope.launch { pagerState.animateScrollToPage(1) } } ) } HorizontalPager( state = pagerState, userScrollEnabled = false, beyondBoundsPageCount = 1 ) { page -> Column( modifier = Modifier.fillMaxSize() ) { when(page) { 0 -> { if (uiState.mappaMattina!=null) { MappaProvincia(mappa = uiState.mappaMattina) } } 1 -> { if (uiState.mappaSera!=null) { MappaProvincia(mappa = uiState.mappaSera) } } } } } ElevatedCard( modifier = Modifier.padding(5.dp), elevation = CardDefaults.elevatedCardElevation(defaultElevation = 8.dp), colors = CardDefaults.elevatedCardColors( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.onPrimaryContainer, ) ) { BodyText(modifier = Modifier.padding(5.dp),text = uiState.testo) } ElevatedCard( modifier = Modifier.padding(5.dp), elevation = CardDefaults.elevatedCardElevation(defaultElevation = 8.dp), colors = CardDefaults.elevatedCardColors( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.onPrimaryContainer, ) ) { Column(modifier = Modifier.padding(5.dp)) { TitleText(modifier = Modifier.fillMaxWidth(), text = "TEMPERATURE") BodyText(text = uiState.testoTemperature) HorizontalDivider(modifier = Modifier.padding(vertical = 2.dp),color = MaterialTheme.colorScheme.onPrimaryContainer) TitleText(modifier = Modifier.fillMaxWidth(), text = "VENTI") BodyText(text = uiState.testoVenti) HorizontalDivider(modifier = Modifier.padding(vertical = 2.dp),color = MaterialTheme.colorScheme.onPrimaryContainer) TitleText(modifier = Modifier.fillMaxWidth(), text = "MARE") BodyText(text = uiState.testoMare) } } ElevatedCard( modifier = Modifier.padding(5.dp), elevation = CardDefaults.elevatedCardElevation(defaultElevation = 8.dp), colors = CardDefaults.elevatedCardColors( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.onPrimaryContainer, ) ) { Column(modifier = Modifier.padding(5.dp)) { TitleText(modifier = Modifier.fillMaxWidth(), text = "TEMPERATURE (ยฐC)") Row { BodyText(modifier = Modifier.weight(4f),text = "") BodyText(modifier = Modifier.weight(1f),text = "MIN") BodyText(modifier = Modifier.weight(1f),text = "MAX") } HorizontalDivider(modifier = Modifier.padding(vertical = 2.dp),color = MaterialTheme.colorScheme.onPrimaryContainer) Row { BodyText(modifier = Modifier.weight(4f),text = "MASSA") BodyText(modifier = Modifier.weight(1f),text = uiState.temperatureMassa.first.toString()) BodyText(modifier = Modifier.weight(1f),text = uiState.temperatureMassa.second.toString()) } HorizontalDivider(modifier = Modifier.padding(vertical = 2.dp),color = MaterialTheme.colorScheme.onPrimaryContainer) Row { BodyText(modifier = Modifier.weight(4f),text = "CARRARA") BodyText(modifier = Modifier.weight(1f),text = uiState.temperatureCarrara.first.toString()) BodyText(modifier = Modifier.weight(1f),text = uiState.temperatureCarrara.second.toString()) } HorizontalDivider(modifier = Modifier.padding(vertical = 2.dp),color = MaterialTheme.colorScheme.onPrimaryContainer) Row { BodyText(modifier = Modifier.weight(4f),text = "AULLA") BodyText(modifier = Modifier.weight(1f),text = uiState.temperatureAulla.first.toString()) BodyText(modifier = Modifier.weight(1f),text = uiState.temperatureAulla.second.toString()) } HorizontalDivider(modifier = Modifier.padding(vertical = 2.dp),color = MaterialTheme.colorScheme.onPrimaryContainer) Row { BodyText(modifier = Modifier.weight(4f),text = "PONTREMOLI") BodyText(modifier = Modifier.weight(1f),text = uiState.temperaturePontremoli.first.toString()) BodyText(modifier = Modifier.weight(1f),text = uiState.temperaturePontremoli.second.toString()) } } } } }
0
Kotlin
0
0
74df9986f4504ead5c42d4be85574f27a639d77b
9,407
MeteoApuane-App
MIT License
backend/app/src/test/kotlin/io/tolgee/controllers/PublicControllerTest.kt
tolgee
303,766,501
false
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.controllers import com.posthog.java.PostHog import io.tolgee.dtos.misc.CreateProjectInvitationParams import io.tolgee.dtos.request.auth.SignUpDto import io.tolgee.fixtures.andAssertResponse import io.tolgee.fixtures.andIsBadRequest import io.tolgee.fixtures.andIsOk import io.tolgee.fixtures.generateUniqueString import io.tolgee.fixtures.waitForNotThrowing import io.tolgee.model.enums.ProjectPermissionType import io.tolgee.testing.AbstractControllerTest import io.tolgee.testing.assert import io.tolgee.testing.assertions.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.argThat import org.mockito.kotlin.eq import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.HttpHeaders import kotlin.properties.Delegates @AutoConfigureMockMvc class PublicControllerTest : AbstractControllerTest() { private var canCreateOrganizations by Delegates.notNull<Boolean>() @BeforeEach fun setup() { Mockito.reset(postHog) canCreateOrganizations = tolgeeProperties.authentication.userCanCreateOrganizations } @AfterEach fun tearDown() { tolgeeProperties.authentication.userCanCreateOrganizations = canCreateOrganizations } @MockBean @Autowired lateinit var postHog: PostHog @Test fun `creates organization`() { val dto = SignUpDto( name = "Pavel Novak", password = "aaaaaaaaa", email = "[email protected]", organizationName = "Hello", ) performPost("/api/public/sign_up", dto).andIsOk assertThat(organizationRepository.findAllByName("Hello")).hasSize(1) } @Test fun `creates organization when no invitation`() { val dto = SignUpDto(name = "Pavel Novak", password = "aaaaaaaaa", email = "[email protected]") performPost("/api/public/sign_up", dto).andIsOk assertThat(organizationRepository.findAllByName("Pavel Novak")).hasSize(1) } @Test fun `logs event to external monitor`() { val dto = SignUpDto(name = "Pavel Novak", password = "aaaaaaaaa", email = "[email protected]") performPost( "/api/public/sign_up", dto, HttpHeaders().also { it["X-Tolgee-Utm"] = "eyJ1dG1faGVsbG8iOiJoZWxsbyJ9" // hypothetically every endpoint might be triggered from SDK it["X-Tolgee-SDK-Type"] = "Unreal" it["X-Tolgee-SDK-Version"] = "1.0.0" }, ).andIsOk var params: Map<String, Any?>? = null waitForNotThrowing(timeout = 10000) { verify(postHog, times(1)).capture( any(), eq("SIGN_UP"), argThat { params = this true }, ) } params!!["utm_hello"].assert.isEqualTo("hello") params!!["sdkType"].assert.isEqualTo("Unreal") params!!["sdkVersion"].assert.isEqualTo("1.0.0") } @Test fun `doesn't create organization when invitation provided`() { val base = dbPopulator.createBase(generateUniqueString()) val project = base.project val invitation = invitationService.create( CreateProjectInvitationParams(project, ProjectPermissionType.EDIT), ) val dto = SignUpDto( name = "Pavel Novak", password = "aaaaaaaaa", email = "[email protected]", invitationCode = invitation.code, ) performPost("/api/public/sign_up", dto).andIsOk assertThat(organizationRepository.findAllByName("Pavel Novak")).hasSize(0) } @Test fun `doesn't create orgs when disabled`() { tolgeeProperties.authentication.userCanCreateOrganizations = false val dto = SignUpDto( name = "Pavel Novak", password = "aaaaaaaaa", email = "[email protected]", organizationName = "Jejda", ) performPost("/api/public/sign_up", dto).andIsOk assertThat(organizationRepository.findAllByName("Jejda")).hasSize(0) } @Test fun testSignUpValidationBlankEmail() { val dto = SignUpDto(name = "Pavel Novak", password = "aaaa", email = "") performPost("/api/public/sign_up", dto) .andIsBadRequest .andAssertResponse.error().isStandardValidation.onField("email") } @Test fun testSignUpValidationBlankName() { val dto = SignUpDto(name = "", password = "aaaa", email = "[email protected]") performPost("/api/public/sign_up", dto) .andIsBadRequest .andAssertResponse.error().isStandardValidation.onField("name") } @Test fun testSignUpValidationInvalidEmail() { val dto = SignUpDto(name = "", password = "aaaa", email = "aaaaaa.cz") performPost("/api/public/sign_up", dto) .andIsBadRequest .andAssertResponse.error().isStandardValidation.onField("email") } }
170
TypeScript
188
1,837
6e01eec3a19c151a6e0aca49e187e2d0deef3082
4,986
tolgee-platform
Apache License 2.0
domain/src/main/java/com/fudie/domain/model/MealCategory.kt
jerimkaura
575,501,780
false
null
package com.fudie.domain.model data class MealCategory( val strCategory: String, val idCategory: String, val strCategoryDescription: String, val strCategoryThumb: String )
4
Kotlin
2
8
49b2e3efda674d66853ff8211d718e5b0271c4e6
189
Fudie
The Unlicense
imagepicker/src/main/java/com/wilinz/imagepicker/ui/theme/Theme.kt
wilinz
489,705,420
false
{"Kotlin": 36733}
package com.wilinz.imagepicker.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import com.google.accompanist.systemuicontroller.rememberSystemUiController object ImagePickerTheme { var ImagePreviewDarkColorPalette = darkColors( primary = Color.Black, primaryVariant = Color.Gray, secondary = Teal200 ) var ImagePreviewLightColorPalette = lightColors( primary = Color.Black, primaryVariant = Color.Gray, secondary = Teal200 ) var DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) var LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 ) var Typography = com.wilinz.imagepicker.ui.theme.Typography var Shapes = com.wilinz.imagepicker.ui.theme.Shapes } /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ @Composable fun ImagePickerTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { ImagePickerTheme.DarkColorPalette } else { ImagePickerTheme.LightColorPalette } MaterialTheme( colors = colors, typography = ImagePickerTheme.Typography, shapes = ImagePickerTheme.Shapes, content = { SetSystemUi(color = MaterialTheme.colors.primary) content() } ) } @Composable fun ImagePreviewTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { ImagePickerTheme.ImagePreviewDarkColorPalette } else { ImagePickerTheme.ImagePreviewLightColorPalette } MaterialTheme( colors = colors, typography = ImagePickerTheme.Typography, shapes = ImagePickerTheme.Shapes, content = { SetSystemUi(color = Color.Transparent) content() } ) } @Composable fun SetSystemUi(color: Color) { val systemUiController = rememberSystemUiController() val useDarkIcons = MaterialTheme.colors.isLight SideEffect { systemUiController.setStatusBarColor( color = color, darkIcons = useDarkIcons ) } }
0
Kotlin
0
0
bf55835557fcc045040363c64ddabfea0db8c487
2,705
ImagePicker
Apache License 2.0
src/Day3/Day03.kt
mhlavac
574,023,170
false
{"Kotlin": 11179, "Makefile": 612}
package Day3 import java.io.File fun main() { val lines = File("src", "Day3/input.txt").readLines() var totalPriority = 0 lines.forEach { val firstChars = it.substring(0, it.length/2).toCharArray() val secondChars = it.substring(it.length/2, it.length).toCharArray() // Get the character val char = firstChars.intersect(secondChars.toList()).first() val score = score(char) println("$it: $char $score") totalPriority += score } println("Points: $totalPriority") } fun score(char: Char): Int { if (char.code >= 97) { return char.code - 96 } return char.code - 38 }
0
Kotlin
0
0
240dbd396c0a9d72959a0b0ed31f77c356c0c0bd
666
advent-of-code-2022
Apache License 2.0
src/nativeMain/kotlin/name/stepin/config/ConfigFile.kt
stepin
839,166,819
false
{"Kotlin": 42055, "Shell": 5095, "Dockerfile": 681}
package name.stepin.config import kotlinx.serialization.Serializable import name.stepin.utils.FileUtils import name.stepin.utils.FileUtils.load import net.mamoe.yamlkt.Yaml import okio.Path @Serializable data class ConfigFile( val group: String? = null, val artifact: String? = null, val name: String? = null, val description: String? = null, val type: String? = null, val preset: String? = null, val extensions: List<String> = emptyList(), val variables: Map<String, String> = emptyMap(), val notes: String? = null, ) { companion object { fun read(path: Path): ConfigFile { val fileContent = load(path) return Yaml.decodeFromString(serializer(), fileContent) } } override fun toString(): String { return Yaml.encodeToString(serializer(), this) } fun write(path: Path) { FileUtils.write(path, this.toString()) } }
0
Kotlin
0
0
4db2227dcde08982ade806763b9e3230c60f4c4f
935
kbre
MIT License
api/ktor/src/main/kotlin/com/rafael/http/Routes.kt
RafaelPereiraSantos
278,705,536
false
null
package com.rafael.http import com.rafael.common.models.Eligible import com.rafael.common.models.ExceptionMessage import com.rafael.common.models.HttpException import com.rafael.common.models.RegisteringEndUser import com.rafael.common.service.EndUserAssociation import com.rafael.common.service.EligibilitySearch import io.ktor.application.call import io.ktor.features.MissingRequestParameterException import io.ktor.http.HttpStatusCode import io.ktor.http.Parameters import io.ktor.request.receive import io.ktor.response.respond import io.ktor.routing.Route import io.ktor.routing.get import io.ktor.routing.post fun Route.health() { get("/health") { call.respond(mapOf("status" to "OK")) } } fun Route.register(){ post("/register") { // TODO receive json in snake_case val registeringEndUser = call.receive<RegisteringEndUser>() call.respond(HttpStatusCode.Created, registeringEndUser) } } fun Route.associate(endUserAssociation: EndUserAssociation) { post("/associate") { val cookies = call.request.cookies // TODO implement an authorizer interceptor if (cookies["session"].isNullOrBlank()) { throw HttpException(401, ExceptionMessage("valid session's token not present", "client.unauthenticated")) } val endUser = Eligible("<EMAIL>", "<PASSWORD>", "2948", 0) endUserAssociation.associate(endUser) call.respond(HttpStatusCode.Created) } } fun Route.eligibility() { get("/eligibility") { // TODO implement an interceptor to check params rule val params = call.request.queryParameters if (params.missingParams()) throw MissingRequestParameterException("Missing at least one parameter") val result = EligibilitySearch().searchBy( params["email"], params["token"], params["personal_document"] ) call.respond(result.uniqueResult() ?: HttpStatusCode.NotFound) } } fun Parameters.missingParams(): Boolean { return this["email"].isNullOrEmpty() && this["token"].isNullOrEmpty() && this["personal_document"].isNullOrEmpty() }
0
Kotlin
0
2
557e8972f7125fea13ed574b8b9ba692b6b2464a
2,155
signup-service
MIT License
app/src/main/java/com/vincent/composedemo/navigator/Router.kt
v1ncent9527
734,159,361
false
{"Kotlin": 15542}
package com.vincent.composedemo.navigator object Router { const val LANDING_PAGE = "LANDING_PAGE" const val NAVIGATOR_PAGE = "NAVIGATOR_PAGE" const val MODIFIER_PAGE = "MODIFIER_PAGE" }
0
Kotlin
0
0
7bc689c4a555ac20321dad278224738ab6f90155
198
ComposeStudy
Apache License 2.0
src/Server.kt
AllanWang
109,920,703
false
null
/** * Created by <NAME> on 2017-11-07. */ /** * The resource manager is held on the server * and has actual implementation of the given commands */ interface ResourceManager : Contract { } interface Server { val manager: ResourceManager val callback: Callback fun onInputReceived(cmd: String) = Command.execute(this, cmd) }
0
Kotlin
0
0
9dead44eaf45f23355e9692d4bc44631cca2d5e8
343
Distributed-Systems
Apache License 2.0
examples/example/src/test/kotlin/com/driver733/mapstructfluent/EmployeeMapperTest.kt
driver733
270,643,208
false
null
package com.driver733.mapstructfluent import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.compilation.shouldNotCompile import io.kotest.matchers.shouldBe import org.mapstruct.factory.Mappers class EmployeeMapperTest : FunSpec({ test("mapstruct impl") { val model = EmployeeModel("Alex") val actual = model.toEmployeeView() actual.apply { shouldBe(EmployeeView("Alex")) shouldBe(Mappers.getMapper(EmployeeMapper::class.java).toEmployeeView(model)) } } test("mapstruct additional arguments") { val model = EmployeeModel("Alex") val actual = model.toEmployeeCompanyView("amazon") actual.apply { shouldBe(EmployeeCompanyView("Alex", "amazon")) shouldBe(Mappers.getMapper(EmployeeMapper::class.java).toEmployeeCompanyView(model, "amazon")) } } test("ignore BeforeMapping impl") { Mappers .getMapper(EmployeeMapper::class.java) .toEmployeeViewBefore() """ package com.driver733.mapstructfluent class A { fun b() { EmployeeModel("Alex").toEmployeeViewBefore() } } """.trimIndent() .shouldNotCompile() } test("ignore AfterMapping impl") { Mappers .getMapper(EmployeeMapper::class.java) .toEmployeeViewAfter() """ package com.driver733.mapstructfluent class A { fun b() { EmployeeModel("Alex").toEmployeeViewAfter() } } """.trimIndent() .shouldNotCompile() } })
5
Kotlin
2
2
62b61d5ec043436a3af1d2b383f0234fb18b4a37
1,720
mapstruct-fluent
MIT License
app/src/main/java/com/minosai/archusers/di/component/AppComponent.kt
MINOSai
132,878,398
false
null
package com.minosai.archusers.di.component import android.app.Application import com.minosai.archusers.di.module.* import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import javax.inject.Singleton @Singleton @Component(modules = [ AndroidInjectionModule::class, AppModule::class, ActivityModule::class ]) interface AppComponent{ @Component.Builder interface Builder { @BindsInstance fun application(application: Application) : Builder fun build() : AppComponent } fun inject(cryptoApp: CryptoApp) }
0
Kotlin
2
7
ef39cccd46f42fa1bdd39b6d916bda57040c919d
637
CrpytoWatch-Jetpack
MIT License
trixnity-client/src/commonMain/kotlin/net/folivo/trixnity/client/user/LazyMemberEventHandler.kt
benkuly
330,904,570
false
{"Kotlin": 3997992, "JavaScript": 5163, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1243}
package net.folivo.trixnity.client.user import net.folivo.trixnity.core.model.events.Event import net.folivo.trixnity.core.model.events.m.room.MemberEventContent interface LazyMemberEventHandler { suspend fun handleLazyMemberEvents(memberEvents: List<Event<MemberEventContent>>) }
0
Kotlin
3
26
03fa8ac5df76de482adf6696d697cec8e5c69c68
286
trixnity
Apache License 2.0
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/InitializationCell.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: InitializationCell * * Full name: System`InitializationCell * * Usage: InitializationCell is an option for Cell that specifies whether the cell should be tagged to be evaluated by the Wolfram Language kernel immediately before the first evaluation performed by the user after the notebook is opened. * * Options: None * * Attributes: Protected * * local: paclet:ref/InitializationCell * Documentation: web: http://reference.wolfram.com/language/ref/InitializationCell.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun initializationCell(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("InitializationCell", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,159
mathemagika
Apache License 2.0
formatters/src/commonMain/kotlin/lexi/FormatterConfigurationUtils.kt
aSoft-Ltd
592,348,487
false
{"Kotlin": 48702}
package lexi fun Map<String, String>.toJsonFormatterOptions() = JsonLogFormatterOptions( verbose = getOrElse("verbose") { "true" }.toBoolean(), source = getOrElse("source") { "true" }.toBoolean(), status = getOrElse("status") { "true" }.toBoolean() ) fun Map<String, String>.toSimpleFormatterOptions() = SimpleLogFormatterOptions( verbose = getOrElse("verbose") { "true" }.toBoolean(), source = getOrElse("source") { "true" }.toBoolean(), status = getOrElse("status") { "true" }.toBoolean() )
0
Kotlin
0
0
cd3aaba761fc484cc5c5bba0dde0e19a396520e1
518
lexi
MIT License
app/src/main/java/com/github/rixspi/simpleflickrgallery/repository/images/ImagesRepository.kt
rixspi
139,967,647
false
{"Kotlin": 100826}
package com.github.rixspi.simpleflickrgallery.repository.images import android.support.annotation.VisibleForTesting import com.github.rixspi.simpleflickrgallery.repository.images.model.Image import com.github.rixspi.simpleflickrgallery.repository.net.FlickrApi import io.reactivex.Observable import io.reactivex.Single import java.util.* import kotlin.NoSuchElementException class ImagesRepository( private val flickrApi: FlickrApi) : ImagesRepoInterface { @VisibleForTesting var cachedImages: MutableMap<String, Image>? = null @VisibleForTesting var cacheIsDirty = false private fun getAndSaveRemoteImages(): Single<List<Image>> { return flickrApi.getImages() .flatMap { images -> Observable.fromIterable(images.items) .doOnNext { image -> cachedImages!![image.id()] = image }.toList() } .doOnSuccess { cacheIsDirty = false } } override fun getImages(): Single<List<Image>> { if (cachedImages != null && !cacheIsDirty) { return Observable.fromIterable(cachedImages!!.values).toList() } else if (cachedImages == null) { cachedImages = LinkedHashMap() } return getAndSaveRemoteImages() } override fun refreshImages() { cacheIsDirty = true //Clearing because of refreshing nature of flickr feed cachedImages?.clear() } override fun getImageFromCache(imageId: String): Single<Image> { return cachedImages?.get(imageId)?.let { Single.just(it) } ?: run { Single.error<Image>(NoSuchElementException("Image wasn't found in the cache!")) } } }
0
Kotlin
0
0
c172eb446117014a54dd497523924e772e87d5c1
1,792
simpleFlickrGallery
Apache License 2.0
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/team/ChangeTeamNameRsp.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.team import org.anime_game_servers.core.base.Version.GI_CB2 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand import org.anime_game_servers.multi_proto.gi.data.general.Retcode @AddedIn(GI_CB2) @ProtoCommand(RESPONSE) internal interface ChangeTeamNameRsp { var retcode: Retcode var teamId: Int var teamName: String }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
534
anime-game-multi-proto
MIT License
src/main/kotlin/com/baulsupp/oksocial/services/microsoft/MicrosoftAuthInterceptor.kt
umerkiani
106,153,725
true
{"Kotlin": 345221, "Shell": 8250, "JavaScript": 1691}
package com.baulsupp.oksocial.services.microsoft import com.baulsupp.oksocial.authenticator.AuthInterceptor import com.baulsupp.oksocial.authenticator.AuthUtil import com.baulsupp.oksocial.authenticator.JsonCredentialsValidator import com.baulsupp.oksocial.authenticator.ValidatedCredentials import com.baulsupp.oksocial.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.oksocial.authenticator.oauth2.Oauth2Token import com.baulsupp.oksocial.output.OutputHandler import com.baulsupp.oksocial.secrets.Secrets import okhttp3.* import java.io.IOException import java.util.concurrent.Future /** * https://graph.microsoft.io/en-us/docs/authorization/app_authorization * http://graph.microsoft.io/en-us/docs/authorization/permission_scopes */ class MicrosoftAuthInterceptor : AuthInterceptor<Oauth2Token> { override fun serviceDefinition(): Oauth2ServiceDefinition { return Oauth2ServiceDefinition("graph.microsoft.com", "Microsoft API", "microsoft", "https://graph.microsoft.io/en-us/docs/get-started/rest", "https://apps.dev.microsoft.com/#/appList") } @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response { var request = chain.request() val token = credentials.accessToken request = request.newBuilder().addHeader("Authorization", "Bearer " + token).build() return chain.proceed(request) } @Throws(IOException::class) override fun authorize(client: OkHttpClient, outputHandler: OutputHandler<*>, authArguments: List<String>): Oauth2Token { System.err.println("Authorising Microsoft API") val clientId = Secrets.prompt("Microsoft Client Id", "microsoft.clientId", "", false) val clientSecret = Secrets.prompt("Microsoft Client Secret", "microsoft.clientSecret", "", true) return MicrosoftAuthFlow.login(client, outputHandler, clientId, clientSecret) } override fun canRenew(credentials: Oauth2Token): Boolean { return credentials.isRenewable() } @Throws(IOException::class) override fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token? { val body = FormBody.Builder().add("grant_type", "refresh_token") .add("redirect_uri", "http://localhost:3000/callback") .add("client_id", credentials.clientId) .add("client_secret", credentials.clientSecret) .add("refresh_token", credentials.refreshToken) .add("resource", "https://graph.microsoft.com/") .build() val request = Request.Builder().url("https://login.microsoftonline.com/common/oauth2/token") .post(body) .build() val responseMap = AuthUtil.makeJsonMapRequest(client, request) // TODO check if refresh token in response? return Oauth2Token(responseMap["access_token"] as String, credentials.refreshToken, credentials.clientId, credentials.clientSecret) } @Throws(IOException::class) override fun validate(client: OkHttpClient, requestBuilder: Request.Builder, credentials: Oauth2Token): Future<ValidatedCredentials> { return JsonCredentialsValidator( MicrosoftUtil.apiRequest("/v1.0/me", requestBuilder), { it["displayName"] as String }).validate( client) } override fun hosts(): Set<String> { return MicrosoftUtil.API_HOSTS } }
0
Kotlin
0
0
046221a33eebd403609342ba159963100636b97e
3,592
oksocial
Apache License 2.0
app/src/main/java/com/octopus/moviesapp/ui/main/MainActivity.kt
b-alramlawi
606,522,847
false
{"Kotlin": 288183}
package com.octopus.moviesapp.ui.main import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.databinding.DataBindingUtil import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.octopus.moviesapp.MyApplication import com.octopus.moviesapp.R import com.octopus.moviesapp.databinding.ActivityMainBinding import com.octopus.moviesapp.util.SettingsService import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! private val settingsService = SettingsService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() setTheme() _binding = DataBindingUtil.setContentView(this, R.layout.activity_main) setStartDestination() } override fun onResume() { super.onResume() val navController = findNavController(R.id.main_fragment_container_view) binding.bottomNavigationView.setupWithNavController(navController) } fun setBottomNavigationVisibility(visibility: Int) { binding.bottomNavigationView.visibility = visibility } override fun onDestroy() { super.onDestroy() _binding = null } private fun setStartDestination() { val navHostFragment = supportFragmentManager.findFragmentById(R.id.main_fragment_container_view) as NavHostFragment val graph = navHostFragment.navController.navInflater.inflate(R.navigation.main_navigation) if (MyApplication.isFirstTimeLaunch) { graph.setStartDestination(R.id.loginFragment) } else { graph.setStartDestination(R.id.homeFragment) } navHostFragment.navController.setGraph(graph, intent.extras) } private fun setTheme() { MyApplication.chosenAppTheme?.let { settingsService.updateAppTheme(it) } } }
0
Kotlin
0
0
81c315d24c34cb6a2d2fbbb4c12cf65ac0ae3826
2,189
Movies_app
Apache License 2.0
app/src/main/java/com/udeshcoffee/android/recyclerview/EmptyRecyclerView.kt
anagram-software
115,889,178
false
null
package com.udeshcoffee.android.recyclerview import android.content.Context import android.util.AttributeSet import android.view.View import androidx.recyclerview.widget.RecyclerView /** * Created by Udathari on 8/27/2017. */ class EmptyRecyclerView : RecyclerView { private var emptyView: View? = null private val observer = object : RecyclerView.AdapterDataObserver() { override fun onChanged() { checkIfEmpty() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { checkIfEmpty() } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { checkIfEmpty() } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) internal fun checkIfEmpty() { if (emptyView != null && adapter != null) { val emptyViewVisible = adapter?.itemCount == 0 emptyView!!.visibility = if (emptyViewVisible) VISIBLE else GONE visibility = if (emptyViewVisible) GONE else VISIBLE } } override fun setAdapter(adapter: Adapter<RecyclerView.ViewHolder>?) { getAdapter()?.unregisterAdapterDataObserver(observer) super.setAdapter(adapter) adapter?.registerAdapterDataObserver(observer) checkIfEmpty() } fun setEmptyView(emptyView: View) { this.emptyView = emptyView checkIfEmpty() } }
3
Kotlin
13
32
2a43d15a23d4a8e9a37b2fd68edeb5afac606216
1,600
CoffeeMusicPlayer
Apache License 2.0
kandy-lets-plot/src/test/kotlin/org/jetbrains/kotlinx/kandy/letsplot/samples/guides/scatterPlot.kt
Kotlin
502,039,936
false
{"Kotlin": 1588044}
package org.jetbrains.kotlinx.kandy.letsplot.samples.guides import org.jetbrains.kotlinx.dataframe.api.convert import org.jetbrains.kotlinx.dataframe.api.dataFrameOf import org.jetbrains.kotlinx.dataframe.api.with import org.jetbrains.kotlinx.kandy.dsl.categorical import org.jetbrains.kotlinx.kandy.dsl.invoke import org.jetbrains.kotlinx.kandy.dsl.plot import org.jetbrains.kotlinx.kandy.letsplot.feature.Position import org.jetbrains.kotlinx.kandy.letsplot.feature.layout import org.jetbrains.kotlinx.kandy.letsplot.feature.position import org.jetbrains.kotlinx.kandy.letsplot.layers.points import org.jetbrains.kotlinx.kandy.letsplot.samples.SampleHelper import org.jetbrains.kotlinx.kandy.letsplot.settings.Symbol import kotlin.reflect.typeOf import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull class Scatter : SampleHelper("geoms", "guides") { private val rand = java.util.Random(123) private val n = 20 private val dataset = dataFrameOf( "cond" to List(n / 2) { "A" } + List(n / 2) { "B" }, "xvar" to List(n) { i: Int -> i }, "yvar" to List(n) { i: Int -> i + rand.nextGaussian() * 3 } ) private val cond = "cond"<String>() private val xvar = "xvar"<Int>() private val yvar = "yvar"<Double>() private val datasetOverlapping = dataset.convert { xvar and yvar }.with { (it.toDouble() / 5).toInt() * 5 } @Test fun guideScatterData() { // SampleStart // This example was found at: // www.cookbook-r.com/Graphs/Scatterplots_(ggplot2) val rand = java.util.Random(123) val n = 20 val dataset = dataFrameOf( "cond" to List(n / 2) { "A" } + List(n / 2) { "B" }, "xvar" to List(n) { i: Int -> i }, "yvar" to List(n) { i: Int -> i + rand.nextGaussian() * 3 } ) val cond = "cond"<String>() val xvar = "xvar"<Int>() val yvar = "yvar"<Double>() // SampleEnd assertNotNull(dataset[cond]) assertNotNull(dataset[xvar]) assertNotNull(dataset[yvar]) } @Test fun guideScatterBasicScatterPlot() { // SampleStart plot(dataset) { points { x(xvar) y(yvar) symbol = Symbol.CIRCLE_OPEN } } // SampleEnd .saveSample() } @Test fun guideScatterScatterPlotWithDiffSymbol() { // SampleStart plot(dataset) { points { x(xvar) y(yvar) color(cond) symbol(cond) size = 5.0 } layout { size = 700 to 350 } } // SampleEnd .saveSample() } @Test fun guideScatterScatterPlotWithOpenSymbol() { // SampleStart plot(dataset) { points { x(xvar) y(yvar) color(cond) symbol(cond) { scale = categorical(range = listOf(Symbol.CIRCLE_OPEN, Symbol.TRIANGLE_OPEN)) } size = 5.0 } layout { size = 700 to 350 } } // SampleEnd .saveSample() } @Test fun guideScatterDatasetOverlapping() { // SampleStart // Create data with overlapping points. val datasetOverlapping = dataset.convert { xvar and yvar }.with { (it.toDouble() / 5).toInt() * 5 } // SampleEnd assertEquals(typeOf<Int>(), datasetOverlapping[xvar].type()) assertEquals(typeOf<Int>(), datasetOverlapping[yvar].type()) } @Test fun guideScatterHandlingOverPlotting() { // SampleStart plot(datasetOverlapping) { points { x(xvar) { axis.breaks(listOf(0, 5, 10, 15)) } y(yvar) alpha = .3 size = 7.0 } layout { size = 700 to 350 } } // SampleEnd .saveSample() } @Test fun guideScatterHandlingOverPlottingJitter() { // SampleStart plot(datasetOverlapping) { points { x(xvar) { axis.breaks(listOf(0, 5, 10, 15)) } y(yvar) symbol = Symbol.CIRCLE_OPEN position = Position.jitter(.1, .1) } layout { size = 700 to 350 } } // SampleEnd // .saveSample() } }
131
Kotlin
15
585
3de2c8bfb0f196583e9786334557c6513b970723
4,730
kandy
Apache License 2.0
common/src/main/kotlin/br/com/stonks/common/exception/StonksException.kt
jonathanarodr
792,544,529
false
{"Kotlin": 189661, "Shell": 832}
package br.com.stonks.common.exception import okhttp3.internal.http2.ConnectionShutdownException import retrofit2.HttpException import java.net.ConnectException import java.net.UnknownHostException open class StonksException( message: String? = null, cause: Throwable? = null, ) : Exception(message, cause) enum class ResultError { UNKNOWN, UNAVAILABLE_NETWORK, REQUEST_NETWORK, IO, } open class StonksApiException( override val message: String, override val cause: Throwable, val errorType: ResultError = ResultError.UNKNOWN, ) : StonksException(message, cause) open class StonksIOException( override val message: String, override val cause: Throwable, val errorType: ResultError = ResultError.UNKNOWN, ) : StonksException(message, cause) fun Throwable.isConnectionError(): Boolean { return this is ConnectException || this is ConnectionShutdownException || this is UnknownHostException } fun Throwable.isRequestHttpError(): Boolean { return this is HttpException }
0
Kotlin
0
0
3303211e4ad5bde4dd4f2a00685884568a5eaeec
1,046
stonks
MIT License
nextgen-middleware/src/main/java/com/nextgenbroadcast/mobile/middleware/atsc3/utils/TimeUtils.kt
jjustman
418,004,011
false
null
package com.nextgenbroadcast.mobile.middleware.atsc3.utils import kotlin.math.roundToLong /** * based on https://github.com/Free-Software-for-Android/NTPSync/blob/master/NTPSync/src/main/java/org/apache/commons/net/ntp/TimeStamp.java * */ internal object TimeUtils { /** * baseline NTP time if bit-0=0 -> 7-Feb-2036 @ 06:28:16 UTC */ private var msb0baseTime = 2085978496000L /** * baseline NTP time if bit-0=1 -> 1-Jan-1900 @ 01:00:00 UTC */ private var msb1baseTime = -2208988800000L /* init { val utcZone = TimeZone.getTimeZone("UTC") val calendar = Calendar.getInstance(utcZone) calendar[1900, Calendar.JANUARY, 1, 0, 0] = 0 calendar[Calendar.MILLISECOND] = 0 msb1baseTime = calendar.time.time calendar[2036, Calendar.FEBRUARY, 7, 6, 28] = 16 calendar[Calendar.MILLISECOND] = 0 msb0baseTime = calendar.time.time } */ /*** * Convert 64-bit NTP timestamp to Java standard time. * * Note that java time (milliseconds) by definition has less precision * then NTP time (picoseconds) so converting NTP timestamp to java time and back * to NTP timestamp loses precision. For example, Tue, Dec 17 2002 09:07:24.810 EST * is represented by a single Java-based time value of f22cd1fc8a, but its * NTP equivalent are all values ranging from c1a9ae1c.cf5c28f5 to c1a9ae1c.cf9db22c. * * @param ntpTimeValue * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT * represented by this NTP timestamp value. */ fun ntpTimeToUtc(ntpTimeValue: Long): Long { val seconds = ntpTimeValue ushr 32 and 0xffffffffL // high-order 32-bits val fraction = ntpTimeValue and 0xffffffffL // low-order 32-bits return ntpToUtc(seconds, fraction) } fun ntpSecondsToUtc(ntpSeconds: Long) = ntpToUtc(ntpSeconds, 0) private fun ntpToUtc(ntpSeconds: Long, ntpFraction: Long): Long { // Use round-off on fractional part to preserve going to lower precision val fraction = (1000.0 * ntpFraction / 0x100000000L).roundToLong() /* * If the most significant bit (MSB) on the seconds field is set we use * a different time base. The following text is a quote from RFC-2030 (SNTP v4): * * If bit 0 is set, the UTC time is in the range 1968-2036 and UTC time * is reckoned from 0h 0m 0s UTC on 1 January 1900. If bit 0 is not set, * the time is in the range 2036-2104 and UTC time is reckoned from * 6h 28m 16s UTC on 7 February 2036. */ val msb = ntpSeconds and 0x80000000L return if (msb == 0L) { // use base: 7-Feb-2036 @ 06:28:16 UTC msb0baseTime + ntpSeconds * 1000 + fraction } else { // use base: 1-Jan-1900 @ 01:00:00 UTC msb1baseTime + ntpSeconds * 1000 + fraction } } }
0
Kotlin
0
5
f0d91240d7c68c57c7ebfd0739148c86a38ffa58
2,971
libatsc3-middleware-sample-app
MIT License
BusinessCard/app/src/main/java/me/daniel/businesscard/data/AppDatabase.kt
Daniel-Froes
509,127,496
false
null
package me.daniel.businesscard.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [BusinessCard::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun businessDao() : BusinessCardDao companion object { @Volatile private var INSTACE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { return INSTACE?: synchronized(this){ val instace = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "businesscard_db" ).build() INSTACE = instace instace } } } }
0
Kotlin
0
0
2b373e148eec43a485754bdb29b3f71dc3599a47
810
cartao-de-visitas-App
MIT License
components/info/impl/src/main/java/com/flipperdevices/info/impl/compose/info/ComposableFirmwareVersion.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.info.impl.compose.info import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.flipperdevices.core.ui.R as DesignSystem import com.flipperdevices.info.impl.R import com.flipperdevices.info.impl.model.FirmwareVersion @Composable fun ComposableFirmwareVersion( firmwareVersion: FirmwareVersion?, firmwareVersionInProgress: Boolean ) { if (firmwareVersion == null) { ComposableDeviceInfoRow( R.string.info_device_info_version, firmwareVersionInProgress, null ) return } ComposableDeviceInfoRow( R.string.info_device_info_version, firmwareVersionInProgress ) { ComposableFirmwareVersionValue(it, firmwareVersion) } } @Composable fun ComposableFirmwareBuildDate( firmwareVersion: FirmwareVersion?, firmwareVersionInProgress: Boolean ) { if (firmwareVersion == null) { ComposableDeviceInfoRow( R.string.info_device_info_build_date, firmwareVersionInProgress, null ) return } ComposableDeviceInfoRowWithText( R.string.info_device_info_build_date, firmwareVersionInProgress, firmwareVersion.buildDate ) } @Composable private fun ComposableFirmwareVersionValue( modifier: Modifier = Modifier, version: FirmwareVersion ) { val prefixId = when (version) { is FirmwareVersion.Dev -> R.string.info_device_firmware_version_dev is FirmwareVersion.Release -> R.string.info_device_firmware_version_release is FirmwareVersion.ReleaseCandidate -> R.string.info_device_firmware_version_rc } val versionText = when (version) { is FirmwareVersion.Dev -> version.commitSHA is FirmwareVersion.Release -> version.version is FirmwareVersion.ReleaseCandidate -> version.version } val colorId = when (version) { is FirmwareVersion.Dev -> DesignSystem.color.red is FirmwareVersion.ReleaseCandidate -> DesignSystem.color.purple is FirmwareVersion.Release -> R.color.device_info_release } ComposableDeviceInfoRowText( modifier, text = "${stringResource(prefixId)} $versionText", colorId = colorId ) }
2
Kotlin
31
293
522f873d6dcf09a8f1907c1636fb0c3a996f5b44
2,341
Flipper-Android-App
MIT License
app/src/main/java/com/xin/wanandroid/ui/wechat/WeChatViewModel.kt
coolxinxin
294,916,632
false
null
/* * Copyright 2020 Leo * 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.xin.wanandroid.ui.wechat import androidx.lifecycle.MutableLiveData import com.xin.wanandroid.base.BaseViewModel import com.xin.wanandroid.core.bean.WeChatData /** * โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–’โ–ˆ โ–ˆโ–ˆ โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–„ โ–ˆโ–ˆ โ–„โ–ˆโ–€ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— * โ–“โ–ˆโ–ˆ โ–’ โ–ˆโ–ˆ โ–“โ–ˆโ–ˆโ–’โ–’โ–ˆโ–ˆโ–€ โ–€โ–ˆ โ–ˆโ–ˆโ–„โ–ˆโ–’ โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• * โ–’โ–ˆโ–ˆโ–ˆโ–ˆ โ–‘โ–“โ–ˆโ–ˆ โ–’โ–ˆโ–ˆโ–‘โ–’โ–“โ–ˆ โ–„ โ–“โ–ˆโ–ˆโ–ˆโ–„โ–‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ•— * โ–‘โ–“โ–ˆโ–’ โ–‘โ–“โ–“โ–ˆ โ–‘โ–ˆโ–ˆโ–‘โ–’โ–“โ–“โ–„ โ–„โ–ˆโ–ˆโ–’โ–“โ–ˆโ–ˆ โ–ˆโ–„ โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ * โ–‘โ–’โ–ˆโ–‘ โ–’โ–’โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–“ โ–’ โ–“โ–ˆโ–ˆโ–ˆโ–€ โ–‘โ–’โ–ˆโ–ˆโ–’ โ–ˆโ–„ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• * โ–’ โ–‘ โ–‘โ–’โ–“โ–’ โ–’ โ–’ โ–‘ โ–‘โ–’ โ–’ โ–‘โ–’ โ–’โ–’ โ–“โ–’ โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• * โ–‘ โ–‘โ–‘โ–’โ–‘ โ–‘ โ–‘ โ–‘ โ–’ โ–‘ โ–‘โ–’ โ–’โ–‘ * โ–‘ โ–‘ โ–‘โ–‘โ–‘ โ–‘ โ–‘ โ–‘ โ–‘ โ–‘โ–‘ โ–‘ * โ–‘ โ–‘ โ–‘ โ–‘ โ–‘ * @author : Leo * @date : 2020/9/13 18:49 * @desc : * @since : [email protected] */ class WeChatViewModel : BaseViewModel() { val isReload: MutableLiveData<Boolean> = MutableLiveData() val weChatData: MutableLiveData<MutableList<WeChatData>> = MutableLiveData() fun getWeChatData() { isReload.value = false request( { weChatData.value = mApiRepository.getWeChatData() }, { isReload.value = weChatData.value.isNullOrEmpty() } ,isShowDialog = weChatData.value.isNullOrEmpty() ) } }
0
Kotlin
0
3
fbb65064bee0b3208a0b69f4feaa49c01818f854
1,891
WanAndroid-JetpackMvvm
Apache License 2.0
plugin/src/main/kotlin/com/astrainteractive/astranpcs/events/ClickNpcEvent.kt
Astra-Interactive
425,296,925
false
{"Kotlin": 51688}
package com.astrainteractive.astranpcs.events import com.astrainteractive.astranpcs.api.events.NPCInteractionEvent import org.bukkit.Bukkit import ru.astrainteractive.astralibs.events.DSLEvent import kotlin.random.Random class ClickNpcEvent { val interactionEvent = DSLEvent.event(NPCInteractionEvent::class.java) { e -> val player = e.player val enpc = e.clicked.empireNPC if (enpc.phrases?.isNotEmpty() == true) { val phrases = enpc.phrases val phrase = phrases?.get(Random.nextInt(phrases.size)) phrase?.let(e.player::sendMessage) } for (command in enpc.commands ?: listOf()) { if (command.asConsole) Bukkit.dispatchCommand(Bukkit.getServer().consoleSender, command.command) else player.performCommand(command.command) } } }
0
Kotlin
0
0
dd4399d470f7bf818aae92bae9140013ef6dabe2
877
AstraNPCS
MIT License
0/b.kt
DarkoKukovec
159,875,185
false
{"JavaScript": 38238, "Kotlin": 9620}
import java.io.File; fun main0B() { println( File("input.txt") .readText(Charsets.UTF_8) .split(" ") .map({ word: String -> word.toUpperCase() }) .joinToString("-") ) }
0
JavaScript
0
0
58a46dcb9c3e493f91d773ccc0440db9bd3b24b5
216
adventofcode2018
MIT License
src/main/kotlin/org/example/rest_api_mongodb_spring/dto/CityRequest.kt
Subhanshu-2411
754,779,574
false
{"Kotlin": 6074, "Batchfile": 181}
package org.example.rest_api_mongodb_spring.dto import lombok.AllArgsConstructor import lombok.Builder import lombok.Data import lombok.NoArgsConstructor @Data @NoArgsConstructor @Builder @AllArgsConstructor data class CityRequest( val name: String, val country: String, val populationM: Float ) { init { require(name.isNotBlank()) { "Name cannot be blank" } require(country.isNotBlank()) { "Country cannot be blank" } require(populationM > 0) { "Population must be greater than 0" } } }
0
Kotlin
0
0
07b06dc7cf9294004b3795404dcb67b5b32c9cf2
546
REST_API_MONGODB_SPRING
MIT License
di/src/main/java/com/comit/di/RepositoryModule.kt
Team-ComIT
511,156,689
false
null
@file:Suppress("UnnecessaryAbstractClass") package com.comit.di import com.comit.data.repository.AuthRepositoryImpl import com.comit.data.repository.CommonsRepositoryImpl import com.comit.data.repository.EmailRepositoryImpl import com.comit.data.repository.FileRepositoryImpl import com.comit.data.repository.HolidayRepositoryImpl import com.comit.data.repository.MenuRepositoryImpl import com.comit.data.repository.ScheduleRepositoryImpl import com.comit.domain.repository.AuthRepository import com.comit.domain.repository.CommonsRepository import com.comit.domain.repository.EmailRepository import com.comit.domain.repository.FileRepository import com.comit.domain.repository.HolidayRepository import com.comit.domain.repository.MenuRepository import com.comit.domain.repository.ScheduleRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Singleton @Binds abstract fun provideAuthRepository( authRepositoryImpl: AuthRepositoryImpl, ): AuthRepository @Singleton @Binds abstract fun provideFileRepository( fileRepositoryImpl: FileRepositoryImpl, ): FileRepository @Singleton @Binds abstract fun provideCommonsRepository( commonsRepositoryImpl: CommonsRepositoryImpl, ): CommonsRepository @Singleton @Binds abstract fun provideMenuRepository( menuRepositoryImpl: MenuRepositoryImpl, ): MenuRepository @Singleton @Binds abstract fun provideEmailRepository( emailRepositoryImpl: EmailRepositoryImpl, ): EmailRepository @Singleton @Binds abstract fun provideScheduleRepository( scheduleRepositoryImpl: ScheduleRepositoryImpl, ): ScheduleRepository @Singleton @Binds abstract fun provideHolidayRepository( holidayRepositoryImpl: HolidayRepositoryImpl, ): HolidayRepository }
2
Kotlin
0
31
48293d51264908cc2f1ece572bf42c8c2f93880d
2,037
SimTong-Android
Apache License 2.0
app/src/main/java/dk/itu/moapd/copenhagenbuzz/fcag/MainActivity.kt
FrankCaglianone
753,609,912
false
{"Kotlin": 2081}
package dk.itu.moapd.copenhagenbuzz.fcag import android.os.Bundle import android.widget.ArrayAdapter import androidx.appcompat.app.AppCompatActivity import android.widget.AutoCompleteTextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createDropdownEventType() } /** * * DropDown Item for the Event Type. * * val eventTypes is the string array of options in res/values/strings.xml "event_types" * val arrayAdapter is * val autoCompleteTextView is * */ private fun createDropdownEventType() { val eventTypes = resources.getStringArray(R.array.event_types) val arrayAdapter = ArrayAdapter(this, R.layout.dropdown_item_layout, eventTypes) val autoCompleteTextView = findViewById<AutoCompleteTextView>(R.id.autoCompleteTextView) autoCompleteTextView.setAdapter(arrayAdapter) } }
0
Kotlin
0
0
93840dea6759538fc0d8b6f99db02b00b52c4d28
1,034
CopenaghenBuzz
MIT License
app/src/main/java/com/yly/sunnyweather/ui/place/PlaceFragment.kt
Mayo92
260,641,362
false
null
package com.yly.sunnyweather.ui.place import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.yly.sunnyweather.MainActivity import com.yly.sunnyweather.R import com.yly.sunnyweather.ui.weather.WeatherActivity import kotlinx.android.synthetic.main.fragment_place.* /* * ้กน็›ฎๅ๏ผš SunnyWeather * ๅŒ… ๅ๏ผš com.yly.sunnyweather.ui.place * ๆ–‡ไปถๅ๏ผš PlaceFragment * ๅˆ›ๅปบ่€…๏ผš YLY * ๆ—ถ ้—ด๏ผš 2020-05-02 19:43 * ๆ ่ฟฐ๏ผš TODO */ class PlaceFragment : Fragment() { val viewModel by lazy { ViewModelProviders.of(this).get(PlaceViewModel::class.java) } private lateinit var adapter: PlaceAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_place,container,false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if(activity is MainActivity && viewModel.isPlaceSaved()){ val place = viewModel.getSavedPlace() val intent = Intent(context, WeatherActivity::class.java).apply { putExtra("location_lng",place.location.lng) putExtra("location_lat",place.location.lat) putExtra("place_name",place.name) } startActivity(intent) activity?.finish() return } val layoutManager = LinearLayoutManager(activity) recyclerView.layoutManager = layoutManager adapter = PlaceAdapter(this,viewModel.placeList) recyclerView.adapter = adapter searchPlaceEdit.addTextChangedListener { editable -> val content = editable.toString() if(content.isNotEmpty()){ viewModel.searchPlaces(content) }else{ recyclerView.visibility = View.GONE bgImageView.visibility = View.VISIBLE viewModel.placeList.clear() adapter.notifyDataSetChanged() } } viewModel.placeLiveData.observe(this, Observer {result -> val places = result.getOrNull() if(places != null){ recyclerView.visibility = View.VISIBLE bgImageView.visibility = View.GONE viewModel.placeList.clear() viewModel.placeList.addAll(places) adapter.notifyDataSetChanged() }else{ Toast.makeText(activity,"ๆœชๆŸฅๅˆฐๅœฐ็‚น",Toast.LENGTH_SHORT).show() result.exceptionOrNull()?.printStackTrace() } }) } }
0
Kotlin
0
0
c0b2378290d18b5f2a6318eca73597cae9014563
2,984
SunnyWeather
Apache License 2.0
services/hierarchy/src/test/kotlin/ProductServiceTest.kt
eclipse-apoapsis
760,319,414
false
{"Kotlin": 3574868, "TypeScript": 515434, "Dockerfile": 28077, "Shell": 8649, "JavaScript": 4916, "CSS": 4099, "PLpgSQL": 1137, "HTML": 1075, "Java": 446}
/* * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.eclipse.apoapsis.ortserver.services import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.WordSpec import io.mockk.coEvery import io.mockk.coVerify import io.mockk.just import io.mockk.mockk import io.mockk.runs import io.mockk.spyk import org.eclipse.apoapsis.ortserver.dao.repositories.DaoProductRepository import org.eclipse.apoapsis.ortserver.dao.repositories.DaoRepositoryRepository import org.eclipse.apoapsis.ortserver.dao.test.DatabaseTestExtension import org.eclipse.apoapsis.ortserver.dao.test.Fixtures import org.eclipse.apoapsis.ortserver.model.Product import org.eclipse.apoapsis.ortserver.model.RepositoryType import org.jetbrains.exposed.sql.Database class ProductServiceTest : WordSpec({ val dbExtension = extension(DatabaseTestExtension()) lateinit var db: Database lateinit var productRepository: DaoProductRepository lateinit var repositoryRepository: DaoRepositoryRepository lateinit var fixtures: Fixtures beforeEach { db = dbExtension.db productRepository = dbExtension.fixtures.productRepository repositoryRepository = dbExtension.fixtures.repositoryRepository fixtures = dbExtension.fixtures } "createRepository" should { "create Keycloak permissions" { val authorizationService = mockk<AuthorizationService> { coEvery { createRepositoryPermissions(any()) } just runs coEvery { createRepositoryRoles(any()) } just runs } val service = ProductService(db, productRepository, repositoryRepository, authorizationService) val repository = service.createRepository(RepositoryType.GIT, "https://example.com/repo.git", fixtures.product.id) coVerify(exactly = 1) { authorizationService.createRepositoryPermissions(repository.id) authorizationService.createRepositoryRoles(repository.id) } } } "deleteProduct" should { "delete Keycloak permissions" { val authorizationService = mockk<AuthorizationService> { coEvery { deleteProductPermissions(any()) } just runs coEvery { deleteProductRoles(any()) } just runs } val service = ProductService(db, productRepository, repositoryRepository, authorizationService) service.deleteProduct(fixtures.product.id) coVerify(exactly = 1) { authorizationService.deleteProductPermissions(fixtures.product.id) authorizationService.deleteProductRoles(fixtures.product.id) } } } "addUserToGroup" should { "throw an exception if the organization does not exist" { val service = ProductService(db, productRepository, repositoryRepository, mockk()) shouldThrow<ResourceNotFoundException> { service.addUserToGroup("username", 1, "readers") } } "throw an exception if the group does not exist" { val authorizationService = mockk<AuthorizationService> { coEvery { addUserToGroup(any(), any()) } just runs } // Create a spy of the service to partially mock it val service = spyk( ProductService( db, productRepository, repositoryRepository, authorizationService ) ) { println(getProduct(1)) coEvery { getProduct(any()) } returns Product(1, 1, "name") } shouldThrow<ResourceNotFoundException> { service.addUserToGroup("username", 1, "viewers") } } "generate the Keycloak group name" { val authorizationService = mockk<AuthorizationService> { coEvery { addUserToGroup(any(), any()) } just runs } // Create a spy of the service to partially mock it val service = spyk( ProductService( db, productRepository, repositoryRepository, authorizationService ) ) { coEvery { getProduct(any()) } returns Product(1, 1, "name") } service.addUserToGroup("username", 1, "readers") coVerify(exactly = 1) { authorizationService.addUserToGroup( "username", "PRODUCT_1_READERS" ) } } } "removeUsersFromGroup" should { "throw an exception if the organization does not exist" { val service = ProductService(db, productRepository, repositoryRepository, mockk()) shouldThrow<ResourceNotFoundException> { service.removeUserFromGroup("username", 1, "readers") } } "throw an exception if the group does not exist" { val authorizationService = mockk<AuthorizationService> { coEvery { addUserToGroup(any(), any()) } just runs } // Create a spy of the service to partially mock it val service = spyk( ProductService( db, productRepository, repositoryRepository, authorizationService ) ) { coEvery { getProduct(any()) } returns Product(1, 1, "name") } shouldThrow<ResourceNotFoundException> { service.removeUserFromGroup("username", 1, "viewers") } } "generate the Keycloak group name" { val authorizationService = mockk<AuthorizationService> { coEvery { removeUserFromGroup(any(), any()) } just runs } // Create a spy of the service to partially mock it val service = spyk( ProductService( db, productRepository, repositoryRepository, authorizationService ) ) { coEvery { getProduct(any()) } returns Product(1, 1, "name") } service.removeUserFromGroup("username", 1, "readers") coVerify(exactly = 1) { authorizationService.removeUserFromGroup( "username", "PRODUCT_1_READERS" ) } } } })
80
Kotlin
8
17
9768de2ed69a9b810efbac9ed73f76ef586146fc
7,410
ort-server
Apache License 2.0
Android/app/src/main/java/ru/alexskvortsov/policlinic/data/service/PatientProfileService.kt
AlexSkvor
244,438,301
false
null
package ru.alexskvortsov.policlinic.data.service import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.functions.BiFunction import ru.alexskvortsov.policlinic.data.storage.database.dao.PatientDao import ru.alexskvortsov.policlinic.data.storage.database.dao.UserDao import ru.alexskvortsov.policlinic.data.storage.database.entities.PatientEntity import ru.alexskvortsov.policlinic.data.storage.database.entities.UserEntity import ru.alexskvortsov.policlinic.data.storage.prefs.AppPrefs import ru.alexskvortsov.policlinic.data.system.schedulers.Scheduler import ru.alexskvortsov.policlinic.domain.repository.PatientProfileRepository import ru.alexskvortsov.policlinic.domain.states.patient.PatientPerson import ru.alexskvortsov.policlinic.formatterDBDate import javax.inject.Inject class PatientProfileService @Inject constructor( private val scheduler: Scheduler, private val userDao: UserDao, private val patientDao: PatientDao, private val prefs: AppPrefs ) : PatientProfileRepository { override fun isLoginUnique(login: String): Observable<Boolean> = userDao.countSameLogins(login, prefs.currentUser.userId) .map { it > 0 } .map { !it } .toObservable() .subscribeOn(scheduler.io()) .observeOn(scheduler.ui()) override fun getPatient(): Observable<PatientPerson> = Single.zip(userDao.getById(prefs.currentUser.userId), patientDao.getByUserId(prefs.currentUser.userId), BiFunction<UserEntity, PatientEntity, PatientPerson> { user, patient -> PatientPerson( name = patient.name, surname = patient.surname, fathersName = patient.fathersName, login = user.login, userId = user.id, gender = patient.gender, berthDate = patient.berthDate.format(formatterDBDate), snilsNumber = patient.snilsNumber, height = patient.height.toString(), weight = patient.weight.toString(), omsPoliceNumber = patient.omsPoliceNumber, passportNumber = patient.passportNumber, patientId = patient.id, phone = patient.phoneNumber ) }) .toObservable() .subscribeOn(scheduler.io()) .observeOn(scheduler.ui()) override fun savePatient(person: PatientPerson): Completable = Completable.defer { userDao.updateLogin(person.login, prefs.currentUser.userId) } .andThen( patientDao.updatePatient( person.patientId, person.surname, person.name, person.fathersName, person.passportNumber, person.omsPoliceNumber, person.weight.toInt(), person.height.toInt(), person.phone ) ).subscribeOn(scheduler.io()) .observeOn(scheduler.ui()) }
0
Kotlin
0
0
5cc6a10a1399ee08643e69308afd4626938882b0
2,934
polyclinic
Apache License 2.0
app/src/main/java/com/zjh/ktwanandroid/presentation/mine/mycollect/MyCollectUrlListFragment.kt
aii1991
521,137,839
false
{"Kotlin": 508643, "Java": 46216}
package com.zjh.ktwanandroid.presentation.mine.mycollect import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import com.blankj.utilcode.util.ConvertUtils import com.kingja.loadsir.core.LoadService import com.zjh.ktwanandroid.R import com.zjh.ktwanandroid.app.base.BaseMVIFragment import com.zjh.ktwanandroid.app.widget.itemdecoration.SpaceItemDecoration import com.zjh.ktwanandroid.databinding.FragmentMyCollectListUrlBinding import com.zjh.ktwanandroid.domain.model.Article import com.zjh.ktwanandroid.presentation.ArticleListIntent import com.zjh.ktwanandroid.presentation.adapter.MyCollectUrlAdapter import com.zjh.ktwanandroid.presentation.webview.WebFragment.ParamKey.COLLECT_KEY import dagger.hilt.android.AndroidEntryPoint import init import initFloatBtn import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.collectLatest import loadServiceInit import me.hgj.jetpackmvvm.ext.nav import me.hgj.jetpackmvvm.ext.navigateAction import showEmpty import showLoading @AndroidEntryPoint class MyCollectUrlListFragment : BaseMVIFragment<MyCollectVM,FragmentMyCollectListUrlBinding>() { private val mAdapter: MyCollectUrlAdapter = MyCollectUrlAdapter(arrayListOf()) private lateinit var loadsir: LoadService<Any> override fun setupView(savedInstanceState: Bundle?) { mDatabind.includeRecyclerview.apply { swipeRefresh.init { mViewModel.dispatchIntent(ArticleListIntent.LoadData) } recyclerView.init(LinearLayoutManager(context),mAdapter).apply { addItemDecoration(SpaceItemDecoration(0, ConvertUtils.dp2px(8f))) initFloatBtn(mDatabind.floatbtn) } loadsir = loadServiceInit(swipeRefresh) { //็‚นๅ‡ป้‡่ฏ•ๆ—ถ่งฆๅ‘็š„ๆ“ไฝœ loadsir.showLoading() mViewModel.dispatchIntent(ArticleListIntent.LoadData) } } mAdapter.run { setCollectClick { item, _, position -> mViewModel.dispatchIntent(ArticleListIntent.UnCollectArticle(Article(id=item.id),position)) } setOnItemClickListener { _, _, position -> nav().navigateAction(R.id.action_main_fragment_to_webFragment, Bundle().apply { putParcelable(COLLECT_KEY, mAdapter.data[position]) }) } } } override fun getArguments(args: Bundle?) { mViewModel.isCollectUrl = true } override fun lazyLoadData() { mViewModel.dispatchIntent(ArticleListIntent.LoadData) } override suspend fun observeUiState(coroutineScope: CoroutineScope) { mViewModel.mUiState.collectLatest { if(!it.isLoading){ if(mAdapter.itemCount == 0){ loadsir.showEmpty() }else{ loadsir.showSuccess() } mAdapter.setList(it.collectUrlList) mDatabind.includeRecyclerview.swipeRefresh.isRefreshing = false }else{ if(mAdapter.itemCount > 0){ mDatabind.includeRecyclerview.swipeRefresh.isRefreshing = true }else{ loadsir.showLoading() } } } } }
0
Kotlin
0
0
49d8c85b5ed3fb4fe067c2cce589242324bd15d0
3,275
kt-wanandroid
MIT License
samples/starter-mobile-app/src/main/kotlin/researchstack/presentation/component/KitTimePickerDialog.kt
S-ResearchStack
520,365,275
false
{"Kotlin": 178868, "AIDL": 4785}
package researchstack.presentation.component import android.app.TimePickerDialog import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @Composable fun KitTimePickerDialog( context: Context, initialHour: Int = 12, initialMinute: Int = 0, changeValue: (Int, Int) -> Unit, ): TimePickerDialog { val mHour: Int = initialHour val mMinute: Int = initialMinute val currentValue = remember { mutableStateOf("") } return TimePickerDialog( context, { _, hour, minute -> currentValue.value = formatTime(hour, minute) changeValue(hour, minute) }, mHour, mMinute, false ) } @Suppress("MagicNumber") private fun formatTime(hour: Int, minute: Int): String = if (hour == 0) "%02d:%02d AM".format(12, minute) else if (hour < 12) "%02d:%02d AM".format(hour, minute) else if (hour == 12) "%02d:%02d PM".format(hour, minute) else "%02d:%02d PM".format(hour - 12, minute)
5
Kotlin
20
26
e31e8055f96fa226745750b5a653e341cf5f2e6c
1,088
app-sdk
Apache License 2.0