path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/nims/fruitful/app/ui/TagChip.kt
nimaiwalsh
445,716,589
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nims.fruitful.app.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.nims.fruitful.app.data.SeedData import com.nims.fruitful.app.data.Tag @Composable fun TagChip( tag: Tag, modifier: Modifier = Modifier ) { Text( text = tag.label, color = FruitfulTheme.colors.tagText(tag.color), modifier = modifier .background( color = FruitfulTheme.colors.tagBackground(tag.color), shape = MaterialTheme.shapes.small ) .padding(horizontal = 6.dp), ) } @Preview(showBackground = true) @Composable private fun PreviewTagChip() { FruitfulTheme { Column { for (tag in SeedData.Tags) { TagChip(tag = tag) Spacer(modifier = Modifier.height(4.dp)) } } } }
0
Kotlin
0
0
2ccd75e7959e20332b082b0583a9bda0e0aec999
1,916
fruitful
Apache License 2.0
feature/calendar/calendarEndless/src/main/kotlin/com/ngapps/phototime/feature/calendar/calendarEndless/model/CalendarEvents.kt
ngapp-dev
752,386,763
false
{"Kotlin": 1833486, "Shell": 10136}
/* * Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ngapps.phototime.feature.calendar.calendarEndless.model import androidx.compose.runtime.Immutable import kotlinx.datetime.LocalDate /** * Represents a calendar event. * * @param date The date of the event. * @param eventName The name or title of the event. * @param eventDescription The description or additional details of the event (optional). */ @Immutable data class CalendarEvent( val date: LocalDate, val eventName: String, val eventDescription: String? = null ) /** * Represents a collection of calendar events. * * @param events The list of calendar events. */ @Immutable data class CalendarEvents( val events: List<CalendarEvent> = emptyList() )
0
Kotlin
0
3
bc1990bccd9674c6ac210fa72a56ef5318bf7241
1,340
phototime
Apache License 2.0
core/database/src/test/java/com/z1/comparaprecos/core/database/repository/produto/ProdutoRepositoryImplTest.kt
zero1code
748,829,698
false
{"Kotlin": 441569}
package com.z1.comparaprecos.core.database.repository.produto import com.z1.comparaprecos.core.database.dao.ProdutoDao import com.z1.comparaprecos.core.database.mapper.ListaCompraMapper import com.z1.comparaprecos.core.database.mapper.ListaCompraWithProdutosMapper import com.z1.comparaprecos.core.database.mapper.ProdutoMapper import com.z1.comparaprecos.testing.BaseTest import com.z1.comparaprecos.testing.data.listaCompraTestData import com.z1.comparaprecos.testing.data.listaCompraWithProductTestData import com.z1.comparaprecos.testing.data.listaProdutoDataTest import io.mockk.clearAllMocks import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.last import kotlinx.coroutines.test.runTest import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class ProdutoRepositoryImplTest: BaseTest() { private lateinit var repository: ProdutoRepository private val produtoDao: ProdutoDao = mockk() private val listaCompraMapper = ListaCompraMapper() private val produtoMapper = ProdutoMapper() private val listaCompraWithProdutosMapper = ListaCompraWithProdutosMapper(listaCompraMapper, produtoMapper) override fun beforeEach() { super.beforeEach() repository = ProdutoRepositoryImpl( produtoDao, listaCompraMapper, produtoMapper, listaCompraWithProdutosMapper ) } override fun afterEach() { super.afterEach() clearAllMocks() } @Test fun `should return listaCompra`() = runTest { //Given - Dado val listaCompraEntity = listaCompraMapper.mapModelToEntity(listaCompraTestData[0]) coEvery { produtoDao.getListaCompra(any()) } returns listaCompraEntity //When - Quando val result = repository.getListaCompra(0) //Then - Entao assertEquals(result.titulo, listaCompraEntity.titulo) } @Test fun `should return a list of listaCompra`() = runTest { //Given - Dado val listaCompraEntity = listaCompraMapper.mapModelListToEntityList(listaCompraTestData) coEvery { produtoDao.getAllListaCompra() } returns listaCompraEntity //When - Quando val result = repository.getAllListaCompra() //Then - Entao assertTrue(result.size == 3) } @Test fun `should return listaCompra to comparar`() = runTest { //Given - Dado val listaCompraEntity = listaCompraWithProdutosMapper.mapModelToEntity( listaCompraWithProductTestData[0]) coEvery { produtoDao.getListaCompraComparada(any(), any()) } returns listaCompraEntity //When - Quando val result = repository.getListaCompraComparada(0, "") //Then - Entao assertEquals(result.detalhes.titulo, listaCompraEntity.detalhes.titulo) } @Test fun `should return a list of Produto ordered by A to Z`() = runTest { //Given - Dado val listaProdutoEntity = produtoMapper.mapModelListToEntityList(listaProdutoDataTest) coEvery { produtoDao.getListaProduto(any()) } returns flowOf(listaProdutoEntity.sortedBy { it.nomeProduto }) //When - Quando val currentList = repository.getListaProduto(0, "").first() val firstItem = currentList.first() val lastItem = currentList.last() //Then - Entao assertTrue(currentList.size == 3) assertTrue(firstItem.nomeProduto == "Arroz") assertTrue(lastItem.nomeProduto == "Feijao") } @Test fun `should return a list of Produto ordered by Z to A`() = runTest { //Given - Dado val listaProdutoEntity = produtoMapper.mapModelListToEntityList(listaProdutoDataTest) coEvery { produtoDao.getListaProduto(any()) } returns flowOf(listaProdutoEntity.sortedByDescending { it.nomeProduto }) //When - Quando val currentList = repository.getListaProduto(0, "").first() val firstItem = currentList.first() val lastItem = currentList.last() //Then - Entao assertTrue(currentList.size == 3) assertTrue(firstItem.nomeProduto == "Feijao") assertTrue(lastItem.nomeProduto == "Arroz") } @Test fun `should return a list of Produto ordered by ADICIONADO PRIMEIRO`() = runTest { //Given - Dado val listaProdutoEntity = produtoMapper.mapModelListToEntityList(listaProdutoDataTest) coEvery { produtoDao.getListaProduto(any()) } returns flowOf(listaProdutoEntity.sortedByDescending { it.id }) //When - Quando val currentList = repository.getListaProduto(0, "").first() val firstItem = currentList.first() val lastItem = currentList.last() //Then - Entao assertTrue(currentList.size == 3) assertTrue(firstItem.nomeProduto == "Banana") assertTrue(lastItem.nomeProduto == "Arroz") } @Test fun `should return a list of Produto oredered by ADICIONADO ULTIMO`() = runTest { //Given - Dado val listaProdutoEntity = produtoMapper.mapModelListToEntityList(listaProdutoDataTest) coEvery { produtoDao.getListaProduto(any()) } returns flowOf(listaProdutoEntity.sortedBy { it.id }) //When - Quando val currentList = repository.getListaProduto(0, "").first() val firstItem = currentList.first() val lastItem = currentList.last() //Then - Entao assertTrue(currentList.size == 3) assertTrue(firstItem.nomeProduto == "Arroz") assertTrue(lastItem.nomeProduto == "Banana") } @Test fun `should insert a new Produto`() = runTest { //Given - Dado val produto = listaProdutoDataTest[0] coEvery { produtoDao.insertProduto(any()) } returns 1 //When - Quando val result = repository.insertProduto(produto) >= 0 //Then - Entao assertTrue(result) } @Test fun `should update a Produto`() = runTest { //Given - Dado val produto = listaProdutoDataTest[0] coEvery { produtoDao.updateProduto(any()) } returns 1 //When - Quando val result = repository.updateProduto(produto) >= 0 //Then - Entao assertTrue(result) } @Test fun `should delete a Produto`() = runTest { //Given - Dado val produto = listaProdutoDataTest[0] coEvery { produtoDao.deleteProduto(any()) } returns 1 //When - Quando val result = repository.deleteProduto(produto) >= 0 //Then - Entao assertTrue(result) } }
0
Kotlin
0
0
2ada1d386ea6e42b37a6c86b145d3c35883d3856
6,721
Compara-precos
Apache License 2.0
cutlass-analyzers/src/main/kotlin/io/strlght/cutlass/analyzers/ext/DexlibExt.kt
strlght
365,810,651
false
null
package io.strlght.cutlass.analyzers.ext import org.jf.dexlib2.AccessFlags import org.jf.dexlib2.iface.ClassDef import org.jf.dexlib2.iface.Member import org.jf.dexlib2.iface.Method import org.jf.dexlib2.iface.reference.MethodReference private val ENCLOSING_ANNOTATIONS = setOf( "Ldalvik/annotation/EnclosingMethod;", "Ldalvik/annotation/EnclosingClass;" ) internal fun ClassDef.hasEnclosing(): Boolean = annotations.any { it.type in ENCLOSING_ANNOTATIONS } internal fun MethodReference.isConstructor(): Boolean = name == "<init>" internal fun Method.isStaticConstructor(): Boolean = accessAll(AccessFlags.CONSTRUCTOR, AccessFlags.STATIC) internal fun Method.isConstructor(withStatic: Boolean = true): Boolean = accessAll(AccessFlags.CONSTRUCTOR) && (withStatic || accessNone(AccessFlags.STATIC)) internal fun Method.isNotConstructor(withStatic: Boolean = true): Boolean = !isConstructor(withStatic = withStatic) private fun Int.matchesAll(vararg values: AccessFlags): Boolean = values.all { this and it.value != 0 } private fun Int.matchesNone(vararg values: AccessFlags): Boolean = values.all { this and it.value == 0 } internal fun Member.accessAll(vararg values: AccessFlags): Boolean = accessFlags.matchesAll(*values) internal fun Member.accessNone(vararg values: AccessFlags): Boolean = accessFlags.matchesNone(*values) internal fun ClassDef.accessAll(vararg values: AccessFlags): Boolean = accessFlags.matchesAll(*values) internal fun ClassDef.accessNone(vararg values: AccessFlags): Boolean = accessFlags.matchesNone(*values)
1
Kotlin
0
4
7658df7b6cb659a760be6883fbf87c531e500627
1,607
cutlass
Apache License 2.0
owntracks-android-2.4/project/app/src/gms/java/org/owntracks/android/gms/location/geofencing/GeofencingRequest.kt
wir3z
737,346,188
false
{"Kotlin": 577231, "Groovy": 303581, "Java": 233010, "Python": 1535, "Shell": 959}
package org.owntracks.android.gms.location.geofencing import org.owntracks.android.location.geofencing.Geofence import org.owntracks.android.location.geofencing.GeofencingRequest fun GeofencingRequest.toGMSGeofencingRequest(): com.google.android.gms.location.GeofencingRequest { val builder = com.google.android.gms.location.GeofencingRequest.Builder() this.geofences?.run { builder.addGeofences(this.toMutableList().map { it.toGMSGeofence() }) } this.initialTrigger?.run { builder.setInitialTrigger(this) } return builder.build() } fun Geofence.toGMSGeofence(): com.google.android.gms.location.Geofence { val builder = com.google.android.gms.location.Geofence.Builder() this.requestId?.run { builder.setRequestId(this) } this.circularLatitude?.also { this.circularLongitude?.also { this.circularRadius?.also { builder.setCircularRegion( this.circularLatitude, this.circularLongitude, this.circularRadius ) } } } this.expirationDuration?.run { builder.setExpirationDuration(this) } this.transitionTypes?.run { builder.setTransitionTypes(this) } this.notificationResponsiveness?.run { builder.setNotificationResponsiveness(this) } this.loiteringDelay?.run { builder.setLoiteringDelay(this) } return builder.build() }
0
Kotlin
3
4
a515ba358d3467267e9d662564152f5d7613991a
1,403
hubitat
Apache License 2.0
app/src/main/java/com/quizapp/ConstantsHard.kt
yasser-acc
734,065,865
false
{"Kotlin": 36685}
package com.quizapp import com.quizapp.R import com.quizapp.Question object ConstantsHard { // TODO (STEP 1: Create a constant variables which we required in the result screen.) // START const val USER_NAME: String = "user_name" const val TOTAL_QUESTIONS: String = "total_questions" const val CORRECT_ANSWERS: String = "correct_answers" // END fun getQuestions(): ArrayList<QuestionHard> { val questionsList = ArrayList<QuestionHard>() // 1 val que1 = QuestionHard( 1, "What country does this flag belong to?", R.drawable.flag_of_bhutan, "Ljubljana", "Bhutan", 2 ) questionsList.add(que1) // 2 val que2 = QuestionHard( 2, "What country does this flag belong to?", R.drawable.flag_of_comoros, "Comoros", "Rwanda", 1 ) questionsList.add(que2) // 3 val que3 = QuestionHard( 3, "What country does this flag belong to?", R.drawable.flag_of_vanuatu, "Vanuatu", "Vanuata", 1 ) questionsList.add(que3) // 4 val que4 = QuestionHard( 4, "What country does this flag belong to?", R.drawable.flag_of_kiribati, "Kiribati", "Mauritius", 1 ) questionsList.add(que4) // 5 val que5 = QuestionHard( 5, "What country does this flag belong to?", R.drawable.flag_of_tuvalu, "the Cook Islands", "Tuvalu", 2 ) questionsList.add(que5) // 6 val que6 = QuestionHard( 6, "What country does this flag belong to?", R.drawable.flag_of_sao_tome_and_principe, "Liberia", "Sao Tome and Principe", 2 ) questionsList.add(que6) // 7 val que7 = QuestionHard( 7, "What country does this flag belong to?", R.drawable.flag_of_solomon_islands, "Solomon Islands", "New Guinea",1 ) questionsList.add(que7) // 8 val que8 = QuestionHard( 8, "What country does this flag belong to?", R.drawable.flag_of_nauru, "Nauru", "Butania", 1 ) questionsList.add(que8) // 9 val que9 = QuestionHard( 9, "What country does this flag belong to?", R.drawable.flag_of_tonga, "olivia", "Tonga", 2 ) questionsList.add(que9) // 10 val que10 = QuestionHard( 10, "What country does this flag belong to?", R.drawable.flag_of_palau, "Micronesia", "Palau", 2 ) questionsList.add(que10) return questionsList } }
0
Kotlin
0
0
99bb7268a0a599689b1786d1fe9145bf7fede3ac
2,793
flag-names
MIT License
app/src/main/java/com/william/toolkit/demo/vm/MainViewModel.kt
WeiLianYang
376,190,355
false
null
/* * Copyright WeiLianYang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.william.toolkit.demo.vm import androidx.lifecycle.MutableLiveData import com.william.toolkit.base.BaseViewModel import com.william.toolkit.demo.service.Api import com.william.toolkit.ext.request /** * @author William * @date 2021/6/13 18:36 * Class Comment: */ class MainViewModel : BaseViewModel() { val bannerMsg = MutableLiveData<String>() fun testApi() { request({ Api.apiService.getBanners() }, { bannerMsg.value = if (it.data.isNullOrEmpty()) "获取网络数据失败,请重试" else "成功获取网络数据,请前往Toolkit面板查看" }) } }
0
Kotlin
0
6
feb589b75fc285ad444ecba99c958a26c02984ea
1,190
AndroidToolkit
Apache License 2.0
app/src/main/java/com/davipviana/usingroom/fragments/StudentListFragment.kt
davipviana
156,989,601
false
null
package com.davipviana.usingroom.fragments import android.content.Context import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ListView import com.davipviana.usingroom.R import com.davipviana.usingroom.database.DatabaseFactory import com.davipviana.usingroom.delegates.StudentsDelegate import com.davipviana.usingroom.entities.Student /** * A simple [Fragment] subclass. * */ class StudentListFragment : Fragment() { private lateinit var delegate: StudentsDelegate private lateinit var studentListFab: FloatingActionButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) delegate = activity as StudentsDelegate } override fun onResume() { super.onResume() delegate.setActivityTitle("Lista de Alunos") } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_student_list, container, false) initializeWidgets(view) return view } private fun initializeWidgets(view: View) { initializeStudentList(view) initializeFab(view) } private fun initializeFab(view: View) { studentListFab = view.findViewById<FloatingActionButton>(R.id.student_list_fab) studentListFab.setOnClickListener { delegate.handleAddButtonClick() } } private fun initializeStudentList(view: View) { val studentList = view.findViewById<ListView>(R.id.student_list) val studentDao = DatabaseFactory().getDatabase(context as Context).studentDao() val students = studentDao.getAll() studentList.adapter = ArrayAdapter<Student>(context, android.R.layout.simple_list_item_1, students) studentList.setOnItemClickListener { adapterView, view, position, id -> val student = studentList.getItemAtPosition(position) as Student delegate.handleStudentSelected(student) } studentList.setOnItemLongClickListener { adapterView, view, position, id -> val student = studentList.getItemAtPosition(position) as Student val deleteMessage = "Remover aluno " + student.name + " ?" Snackbar .make(studentListFab, deleteMessage, Snackbar.LENGTH_SHORT) .setAction("Sim" ) { studentDao.delete(student) (studentList.adapter as ArrayAdapter<Student>).remove(student) }.show() true } } }
0
Kotlin
0
0
d5515f46191ec8f20e5c64ec5015ce330880102c
2,878
using-room
Apache License 2.0
server/ns-market/user-service/src/main/kotlin/com/market/userservice/config/R2DBCConfig.kt
JungBakTest
670,271,502
false
null
package com.market.userservice.config import io.r2dbc.spi.ConnectionFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.io.ClassPathResource import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator //@Configuration //class R2DBCConfig { // // @Bean // fun init(connectionFactory: ConnectionFactory) = // ConnectionFactoryInitializer().apply { // setConnectionFactory(connectionFactory) // setDatabasePopulator( // ResourceDatabasePopulator( // ClassPathResource("scripts/scheme.sql") // ) // ) // } // //}
0
Kotlin
0
0
2b51f9a2101709261617f8f7b74bc73419b4df17
804
susan-server
MIT License
time/src/commonMain/kotlin/com/merseyside/merseyLib/time/ext/MonthRangeExt.kt
Merseyside
396,607,192
false
null
package com.merseyside.merseyLib.time.ext import com.merseyside.merseyLib.time.Days import com.merseyside.merseyLib.time.TimeUnit import com.merseyside.merseyLib.time.minus import com.merseyside.merseyLib.time.plus import com.merseyside.merseyLib.time.ranges.MonthRange import com.merseyside.merseyLib.time.ranges.TimeRange fun MonthRange.getNextMonth(): MonthRange { return end.toMonthRange() } fun MonthRange.getPrevMonth(): MonthRange { return (start - Days(1)).toMonthRange() } fun MonthRange.getFirstDay(): TimeRange { return start.toDayTimeRange() } fun MonthRange.getLastDay(): TimeRange { return (end - Days(1)).toDayTimeRange() } fun MonthRange.getDay(number: Int): TimeRange { val timeUnit = start + Days(number - 1) return if (contains(timeUnit)) timeUnit.toDayTimeRange() else throw IllegalArgumentException("Month has only ${getMonth().days} days.") } fun MonthRange.isIntersect(other: TimeRange, includeLastMilli: Boolean = false): Boolean { return (this as TimeRange).isIntersect(other, includeLastMilli) } fun MonthRange.contains(other: TimeRange, includeLastMilli: Boolean = false): Boolean { return (this as TimeRange).contains(other, includeLastMilli) } fun MonthRange.contains(timeUnit: TimeUnit, includeLastMilli: Boolean = false): Boolean { return (this as TimeRange).contains(timeUnit, includeLastMilli) }
0
Kotlin
0
0
7d8d4fd65081422ac87a0d7799ec6ff379b23e57
1,377
mersey-kmp-time
Apache License 2.0
typescript-kotlin/src/main/kotlin/typescript/isTypeAssertionExpression.fun.kt
turansky
393,199,102
false
null
// Automatically generated - do not modify! @file:JsModule("typescript") @file:JsNonModule package typescript external fun isTypeAssertionExpression(node: Node): Boolean /* node is TypeAssertion */
0
Kotlin
1
10
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
201
react-types-kotlin
Apache License 2.0
droid-app/CoffeeDose/app/src/main/java/com/office14/coffeedose/database/OrderDao.kt
office-14
241,098,657
false
null
package com.office14.coffeedose.database import androidx.lifecycle.LiveData import androidx.room.* import kotlinx.coroutines.Deferred @Dao interface OrderDao{ @Query("select * from orders") fun getAll() : LiveData<List<OrderDbo>> @Query("select * from orders where finished = 'false'") fun getAllNotFinished() : LiveData<List<OrderDbo>> @Query("select * from orders where owner = :email") fun getAllForUser(email:String) : LiveData<List<OrderDbo>> @Query("select * from orders where owner = :email and finished = 'false'") fun getAllForUserNotFinishedStraight(email:String) : List<OrderDbo> @Query("select * from orders where id = :orderId") fun getById(orderId:Int) : LiveData<List<OrderDbo>> @Query("select * from orders where id = :orderId") fun getByIdStraight(orderId:Int) : List<OrderDbo> @Query("select * from orders where id = :orderId and owner = :email") fun getByIdAndOwner(orderId:Int, email:String) : LiveData<List<OrderDbo>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAllOrders(vararg orders: OrderDbo) @Delete fun delete(order:OrderDbo) @Query("delete from orders where owner = :email") fun deleteByUser(email: String) @Query("update orders set finished = 'true' where owner = :email") fun markAsFinishedForUser(email: String) @Query("delete from orders") fun clear() @Query("update orders set status_code = :statusCode, status_name = :statusName where id = :id") fun updateStatusCodeAndNameById(id:Int, statusCode:String, statusName:String) }
14
Kotlin
2
1
621e2cb2dc378b5cb447c3369abeb34a36d28572
1,593
Drinks
MIT License
droid-app/CoffeeDose/app/src/main/java/com/office14/coffeedose/database/OrderDao.kt
office-14
241,098,657
false
null
package com.office14.coffeedose.database import androidx.lifecycle.LiveData import androidx.room.* import kotlinx.coroutines.Deferred @Dao interface OrderDao{ @Query("select * from orders") fun getAll() : LiveData<List<OrderDbo>> @Query("select * from orders where finished = 'false'") fun getAllNotFinished() : LiveData<List<OrderDbo>> @Query("select * from orders where owner = :email") fun getAllForUser(email:String) : LiveData<List<OrderDbo>> @Query("select * from orders where owner = :email and finished = 'false'") fun getAllForUserNotFinishedStraight(email:String) : List<OrderDbo> @Query("select * from orders where id = :orderId") fun getById(orderId:Int) : LiveData<List<OrderDbo>> @Query("select * from orders where id = :orderId") fun getByIdStraight(orderId:Int) : List<OrderDbo> @Query("select * from orders where id = :orderId and owner = :email") fun getByIdAndOwner(orderId:Int, email:String) : LiveData<List<OrderDbo>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAllOrders(vararg orders: OrderDbo) @Delete fun delete(order:OrderDbo) @Query("delete from orders where owner = :email") fun deleteByUser(email: String) @Query("update orders set finished = 'true' where owner = :email") fun markAsFinishedForUser(email: String) @Query("delete from orders") fun clear() @Query("update orders set status_code = :statusCode, status_name = :statusName where id = :id") fun updateStatusCodeAndNameById(id:Int, statusCode:String, statusName:String) }
14
Kotlin
2
1
621e2cb2dc378b5cb447c3369abeb34a36d28572
1,593
Drinks
MIT License
demo/gdml/src/commonTest/kotlin/space/kscience/visionforge/gdml/GDMLVisionTest.kt
SciProgCentre
174,502,624
false
{"Kotlin": 856546, "CSS": 913}
package space.kscience.visionforge.gdml import space.kscience.dataforge.names.Name import space.kscience.dataforge.values.asValue import space.kscience.dataforge.values.string import space.kscience.gdml.GdmlShowCase import space.kscience.visionforge.Vision import space.kscience.visionforge.computeProperties import space.kscience.visionforge.get import space.kscience.visionforge.setProperty import space.kscience.visionforge.solid.Solid import space.kscience.visionforge.solid.SolidMaterial import space.kscience.visionforge.solid.material import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull class GDMLVisionTest { private val cubes = GdmlShowCase.cubes().toVision() @Test fun testCubesStyles(){ val segment = cubes["composite-000.segment-0"] as Solid println(segment.computeProperties().getValue(Vision.STYLE_KEY)) // println(segment.computePropertyNode(SolidMaterial.MATERIAL_KEY)) // println(segment.computeProperty(SolidMaterial.MATERIAL_COLOR_KEY)) println(segment.material?.meta) //println(Solids.encodeToString(cubes)) } @Test fun testPrototypeProperty() { val child = cubes[Name.of("composite-000","segment-0")] assertNotNull(child) child.setProperty(SolidMaterial.MATERIAL_COLOR_KEY, "red".asValue()) assertEquals("red", child.getPropertyValue(SolidMaterial.MATERIAL_COLOR_KEY)?.string) } }
15
Kotlin
6
34
fb12ca8902509914910e8a39c4e525bee5e3fd46
1,451
visionforge
Apache License 2.0
app/src/main/java/com/pengxh/autodingding/ui/QuestionAndAnswerActivity.kt
AndroidCoderPeng
230,078,640
false
{"Kotlin": 67687, "Java": 24520}
package com.pengxh.autodingding.ui import android.graphics.Color import android.os.Bundle import android.widget.TextView import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.pengxh.autodingding.R import com.pengxh.autodingding.databinding.ActivityQuestionAndAnswerBinding import com.pengxh.autodingding.extensions.initImmersionBar import com.pengxh.autodingding.model.QuestionAnAnswerModel import com.pengxh.kt.lite.adapter.NormalRecyclerAdapter import com.pengxh.kt.lite.adapter.ViewHolder import com.pengxh.kt.lite.base.KotlinBaseActivity import com.pengxh.kt.lite.divider.RecyclerViewItemDivider import com.pengxh.kt.lite.extensions.readAssetsFile import com.pengxh.kt.lite.utils.ActivityStackManager import com.pengxh.kt.lite.utils.HtmlRenderEngine import com.pengxh.kt.lite.widget.TitleBarView class QuestionAndAnswerActivity : KotlinBaseActivity<ActivityQuestionAndAnswerBinding>() { private val context = this private val gson by lazy { Gson() } override fun initEvent() { } override fun initOnCreate(savedInstanceState: Bundle?) { ActivityStackManager.addActivity(this) binding.marqueeView.requestFocus() val assetsFile = readAssetsFile("QuestionAndAnswer.json") val dataRows = gson.fromJson<MutableList<QuestionAnAnswerModel>>( assetsFile, object : TypeToken<MutableList<QuestionAnAnswerModel>>() {}.type ) binding.recyclerView.addItemDecoration(RecyclerViewItemDivider(1, Color.LTGRAY)) binding.recyclerView.adapter = object : NormalRecyclerAdapter<QuestionAnAnswerModel>(R.layout.item_q_a_rv_l, dataRows) { override fun convertView( viewHolder: ViewHolder, position: Int, item: QuestionAnAnswerModel ) { viewHolder.setText(R.id.questionView, item.question) val textView = viewHolder.getView<TextView>(R.id.answerView) HtmlRenderEngine.Builder() .setContext(context) .setHtmlContent(item.answer) .setTargetView(textView) .setOnGetImageSourceListener(object : HtmlRenderEngine.OnGetImageSourceListener { override fun imageSource(url: String) { } }).build().load() } } } override fun initViewBinding(): ActivityQuestionAndAnswerBinding { return ActivityQuestionAndAnswerBinding.inflate(layoutInflater) } override fun observeRequestState() { } override fun setupTopBarLayout() { binding.rootView.initImmersionBar(this, true, R.color.white) binding.titleView.setOnClickListener(object : TitleBarView.OnClickListener { override fun onLeftClick() { finish() } override fun onRightClick() { } }) } }
25
Kotlin
92
502
ab96e5782191745a6217200ed8db8f317cc979b2
2,948
AutoDingding
Apache License 2.0
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ResizeLayer.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: ResizeLayer * * Full name: System`ResizeLayer * * ResizeLayer[{n}] resizes a matrix of size c × n to be size c × n. * 0 0 0 * ResizeLayer[{h, w}] resizes an array of dimensions c × h × w to be size c × h × w. * Usage: 0 0 0 0 * * Input -> Automatic * Output -> Automatic * Options: Resampling -> Linear * * Protected * Attributes: ReadProtected * * local: paclet:ref/ResizeLayer * Documentation: web: http://reference.wolfram.com/language/ref/ResizeLayer.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun resizeLayer(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("ResizeLayer", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,381
mathemagika
Apache License 2.0
app/src/main/java/github/sachin2dehury/nitrresources/fragment/PageFragment.kt
sachin2dehury
296,853,144
false
null
package github.sachin2dehury.nitrresources.fragment import android.annotation.SuppressLint import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.View import androidx.appcompat.widget.SearchView import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.gms.ads.AdRequest import github.sachin2dehury.nitrresources.R import github.sachin2dehury.nitrresources.adapter.ListPageAdapter import github.sachin2dehury.nitrresources.component.AppCore import github.sachin2dehury.nitrresources.component.AppJobs import github.sachin2dehury.nitrresources.dialog.ActionDialog import kotlinx.android.synthetic.main.fragment_page.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class PageFragment(private val position: Int) : Fragment(R.layout.fragment_page) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (AppCore.firebaseAuth.currentUser != null) { progressBar.visibility = View.VISIBLE CoroutineScope(Dispatchers.IO).launch { AppJobs.getList(position).invokeOnCompletion { jobValidator(it) } AppJobs.updateDocList(position, listView.adapter!!) } } else { val error = "Please Log in!" ActionDialog(requireContext(), error).show() // Toast.makeText(context, error, Toast.LENGTH_SHORT).show() } listView.apply { adapter = ListPageAdapter(position, parentFragmentManager) layoutManager = LinearLayoutManager(context) } val adRequest = AdRequest.Builder().build()!! adView.loadAd(adRequest) } private fun jobValidator(throwable: Throwable?) = CoroutineScope(Dispatchers.Main).launch { progressBar.visibility = View.GONE when (throwable) { null -> isEmpty() else -> { val error = throwable.toString() ActionDialog(requireContext(), error).show() // Toast.makeText(context, error, Toast.LENGTH_SHORT).show() } } } private fun isEmpty() { if (listView.adapter!!.itemCount == 0) { val error = AppCore.noList.first() ActionDialog(requireContext(), error).show() // Toast.makeText(context, error, Toast.LENGTH_LONG).show() } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.removeItem(R.id.searchBar) menu.removeItem(R.id.user) inflater.inflate(R.menu.search_menu, menu) val search = menu.findItem(R.id.searchBar).actionView as SearchView search.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { val adapter = listView.adapter as ListPageAdapter adapter.filter.filter(newText) return false } }) super.onCreateOptionsMenu(menu, inflater) } }
0
Kotlin
0
1
91029b96c273c534469ce133ae2c32114cc36437
3,510
NITR_Resources
Apache License 2.0
lang/src/main/kotlin/org/toptobes/lang/preprocessor/LabelFinder.kt
toptobes
627,149,279
false
null
package org.toptobes.lang.preprocessor import org.toptobes.lang.ast.Label import org.toptobes.lang.parsing.identifierRegex import org.toptobes.parsercombinator.SymbolMap /** * Something is a label if it matches the format `<name>:` * and doesn't have a comma, {, or ( right before it. * It also requires some amount of whitespace before it, or * the start of the file. */ fun findLabels(str: String): Set<Label> = Regex("(^|[^({,]\\s+)($identifierRegex):") .findAll(str) .map { Label(it.groupValues[2], false) } .toSet()
0
Kotlin
0
0
18bf958736390415374d7bb553f0317a5640a0bd
556
BadVm
MIT License
sample/src/androidMain/kotlin/MainActivity.kt
InsanusMokrassar
535,572,808
false
{"Kotlin": 145028, "Shell": 387}
package dev.inmo.navigation.sample import android.app.Application import android.content.Context import android.content.res.Resources import androidx.fragment.app.Fragment import dev.inmo.micro_utils.startup.launcher.Config import dev.inmo.micro_utils.startup.launcher.StartLauncherPlugin import dev.inmo.micro_utils.startup.plugin.StartPlugin import dev.inmo.navigation.compose.NavigationComposeSingleActivity import dev.inmo.navigation.core.NavigationChain import dev.inmo.navigation.core.configs.NavigationNodeDefaultConfig import dev.inmo.navigation.core.fragments.transactions.FragmentTransactionConfigurator import dev.inmo.navigation.core.repo.ConfigHolder import dev.inmo.navigation.mvvm.NavigationMVVMSingleActivity import dev.inmo.navigation.sample.ui.LoadingFragment import dev.inmo.navigation.sample.ui.NavigationViewConfig import kotlinx.coroutines.CoroutineScope import kotlinx.serialization.json.JsonObject import org.koin.core.context.stopKoin import org.koin.core.module.Module import kotlin.reflect.KClass class MainActivity : NavigationComposeSingleActivity<NavigationNodeDefaultConfig>() { private class Plugin(private val mainActivity: MainActivity) : StartPlugin { override fun Module.setupDI(config: JsonObject) { single { mainActivity } single<Context> { mainActivity } single<Resources> { mainActivity.resources } single<Application> { mainActivity.application } } } // override val fragmentTransactionConfigurator: FragmentTransactionConfigurator<NavigationNodeDefaultConfig>? = FragmentTransactionConfigurator.Default { // setCustomAnimations( // /* enter = */ R.anim.slide_in, // /* exit = */ R.anim.fade_out, // /* popEnter = */ R.anim.fade_in, // /* popExit = */ R.anim.slide_out, // ) // } private val plugins: List<StartPlugin> by lazy { listOf( Plugin(this), AndroidPlugin ) } override val baseClassName: KClass<NavigationNodeDefaultConfig> get() = NavigationNodeDefaultConfig::class override fun createInitialConfigChain(): ConfigHolder.Chain<NavigationNodeDefaultConfig> { return ConfigHolder.Chain( ConfigHolder.Node( NavigationViewConfig("", "Node"), null, emptyList() ) ) } override suspend fun onBeforeStartNavigation() { stopKoin() StartLauncherPlugin.start( Config( plugins ) ) super.onBeforeStartNavigation() } }
1
Kotlin
0
2
79c057c4612319c3b8a1b88a053db777737143b9
2,633
navigation
MIT License
app/src/main/java/com/Constants.kt
SohailAhmed145
805,666,706
false
{"Kotlin": 9762}
package com const val BASE_URL= "https://newsapi.org/v2/"
0
Kotlin
0
0
fdd2759299fd7fb3d942254c38f31f34f705ceaa
58
NewsApp
MIT License
app/src/main/java/com/example/billbuddy/data/local/repository/PaymentHistoryRepositoryImpl.kt
arfinhosainn
607,740,170
false
null
package com.example.billbuddy.data.local.repository import com.example.billbuddy.data.local.PaymentHistoryDao import com.example.billbuddy.data.local.model.PaymentHistory import com.example.billbuddy.data.local.model.relation.PaymentAndPaymentHistory import com.example.billbuddy.domain.repository.PaymentHistoryRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class PaymentHistoryRepositoryImpl @Inject constructor( private val paymentHistoryDao: PaymentHistoryDao ) : PaymentHistoryRepository { override suspend fun insertPaymentHistory(paymentHistory: PaymentHistory) { paymentHistoryDao.insertPaymentHistory(paymentHistory) } override fun getPaymentHistory(): Flow<List<PaymentAndPaymentHistory>> { return paymentHistoryDao.getPaymentHistory() } }
0
Kotlin
0
0
27467f0bb092c708542d3f7f4ff7229a9516a66d
815
BillBuddy
Apache License 2.0
src/test/kotlin/hackerrank/CountingValleysTest.kt
simao-ferreira
423,600,181
false
null
package hackerrank import hackerrank.CountingValleys import org.junit.Assert import org.junit.Test class CountingValleysTest { private val valleys = CountingValleys() @Test fun `count 1 valleys`() { //when: val st = valleys.countingValleys(8, "UDDDUDUU") //then: Assert.assertEquals(st, 1) } @Test fun `count 6 valleys`() { //when: val st = valleys.countingValleys(18, "DDUUUDDUDUDUDUDDUU") //then: Assert.assertEquals(st, 6) } @Test fun `count 2 valleys`() { //when: val st = valleys.countingValleys(12, "DDUUDDUDUUUD") //then: Assert.assertEquals(st, 2) } @Test fun `count 8 valleys`() { //when: val st = valleys.countingValleysBruteForce(22, "DDUUUDDUDUDUDUDDUUDUDU") //then: Assert.assertEquals(st, 8) } }
0
Kotlin
0
0
76b4b278e016bf4d806bfac01b1b691da25d596d
898
code-katas
MIT License
datasources/src/main/java/com/santukis/datasources/mappers/DeckMappers.kt
santukis
504,046,648
false
{"Kotlin": 206975}
package com.santukis.datasources.mappers import com.santukis.datasources.entities.dto.requests.DeckRequestDTO import com.santukis.entities.hearthstone.DeckRequest import com.santukis.entities.core.takeIfNotEmpty fun DeckRequest.toDeckRequestDTO(): DeckRequestDTO = DeckRequestDTO( locale = regionality.locale.value, deckCode = deckCode.takeIfNotEmpty(), cardIds = cardIds.joinToString(","), heroId = heroId.takeIfNotEmpty() )
0
Kotlin
0
3
7baff042a3bf97fc82eb5e7a73669cad9820ed39
467
HearthStone
Apache License 2.0
app/src/main/java/io/github/lee0701/lboard/hardkeyboard/CommonKeyboardLayout.kt
Lee0701
177,382,784
false
null
package io.github.lee0701.lboard.hardkeyboard data class CommonKeyboardLayout( val layers: Map<Int, LayoutLayer> = mapOf(0 to LayoutLayer()), val strokes: List<StrokeTable> = listOf(), val cycle: Boolean = false, val timeout: Boolean = false, val spaceForSeparation: Boolean = false ) { constructor(layerId: Int, main: LayoutLayer, strokes: List<StrokeTable> = listOf(), cycle: Boolean = true, timeout: Boolean = false, spaceForSeparation: Boolean = false): this(mapOf(layerId to main), strokes, cycle, timeout, spaceForSeparation) constructor(main: LayoutLayer, strokes: List<StrokeTable> = listOf(), cycle: Boolean = true, timeout: Boolean = false, spaceForSeparation: Boolean = false): this(0, main, strokes, cycle, timeout, spaceForSeparation) operator fun get(i: Int): LayoutLayer? = layers[i] operator fun plus(other: CommonKeyboardLayout): CommonKeyboardLayout { return CommonKeyboardLayout( (this.layers + other.layers).map { it.key to (this[it.key] ?: LayoutLayer(mapOf())) + (other[it.key] ?: LayoutLayer(mapOf())) }.toMap(), other.strokes, other.cycle, other.timeout, other.spaceForSeparation ) } operator fun times(other: CommonKeyboardLayout): CommonKeyboardLayout { return CommonKeyboardLayout( (this.layers + other.layers).map { it.key to (this[it.key] ?: this[0] ?: LayoutLayer(mapOf())) + (other[it.key] ?: LayoutLayer(mapOf())) }.toMap(), other.strokes, other.cycle, other.timeout, other.spaceForSeparation ) } data class LayoutLayer( val layout: Map<Int, LayoutItem> = mapOf(), val labels: Map<Int, Pair<String, String>> = mapOf() ) { operator fun get(i: Int): LayoutItem? = layout[i] operator fun plus(other: LayoutLayer): LayoutLayer { return LayoutLayer(this.layout + other.layout, this.labels + other.labels) } } data class LayoutItem( val normal: List<Int>, val shift: List<Int>, val caps: List<Int> ) { constructor(normal: List<Int>, shift: List<Int>): this(normal, shift, normal) constructor(normal: List<Int>): this(normal, normal, normal) constructor(normal: Int, shift: Int, caps: Int): this(listOf(normal), listOf(shift), listOf(caps)) constructor(normal: Int, shift: Int): this(normal, shift, normal) constructor(normal: Int): this(normal, normal, normal) } data class StrokeTable( val table: Map<Int, Int> ) { operator fun get(key: Int): Int? = table[key] } companion object { const val LAYER_ALT = 10 const val LAYER_MORE_KEYS_KEYCODE = 20 const val LAYER_MORE_KEYS_CHARCODE = 21 } }
5
Kotlin
1
1
2befd2f2b1941dd6e02336a468e4f824c6617974
2,937
LBoard
Apache License 2.0
data/src/main/kotlin/com/sbgapps/scoreit/data/model/SavedGameInfo.kt
StephaneBg
16,022,770
false
null
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sbgapps.scoreit.data.model data class SavedGameInfo( val fileName: String, val date: Long, val players: String )
1
null
11
37
7684d40c56c3293b1e9b06158efcbefa51693f7a
724
ScoreIt
Apache License 2.0
app/src/main/java/com/awanama/aleinfo/ui/navbar/NavBar.kt
awan-ama
817,752,259
false
{"Kotlin": 36980}
package com.awanama.aleinfo.ui.navbar import com.awanama.aleinfo.R import com.awanama.aleinfo.navigation.TopLevelDestination sealed class NavBar( var title: String, var icon: Int, var route: String ) { object Home : NavBar( "Home", R.drawable.ale_home, TopLevelDestination.Home.route ) object Favs : NavBar( "Favs", R.drawable.ale_favs, TopLevelDestination.Favs.route ) object Profile : NavBar( "Profile", R.drawable.ale_profile, TopLevelDestination.Profile.route ) }
0
Kotlin
0
0
c8ed634c6c38a89540df80c23fb0eecca8981e72
651
aleinfo
MIT License
app/src/main/java/seigneur/gauvain/mycourt/ui/about/AboutFragmentModule.kt
GauvainSeigneur
141,754,998
false
null
package seigneur.gauvain.mycourt.ui.about import androidx.fragment.app.Fragment import dagger.Binds import dagger.Module import seigneur.gauvain.mycourt.di.scope.PerFragment /** * Provides activity dependencies. */ @Module abstract class AboutFragmentModule { /** * provide a concrete implementation of [Fragment] * * @param userFragment is the UserFragment * @return the fragment */ @Binds @PerFragment internal abstract fun fragment(aboutFragment: AboutFragment): androidx.fragment.app.Fragment }
9
Kotlin
0
2
5aa6d3c26103311497a0b89628099beb2da8047c
548
MyCourt
Apache License 2.0
protocol/osrs-225/osrs-225-desktop/src/main/kotlin/net/rsprot/protocol/game/outgoing/codec/logout/LogoutTransferEncoder.kt
blurite
771,753,685
false
{"Kotlin": 9348194}
package net.rsprot.protocol.game.outgoing.codec.logout import net.rsprot.buffer.JagByteBuf import net.rsprot.crypto.cipher.StreamCipher import net.rsprot.protocol.ServerProt import net.rsprot.protocol.game.outgoing.logout.LogoutTransfer import net.rsprot.protocol.game.outgoing.prot.GameServerProt import net.rsprot.protocol.message.codec.MessageEncoder import net.rsprot.protocol.metadata.Consistent @Consistent public class LogoutTransferEncoder : MessageEncoder<LogoutTransfer> { override val prot: ServerProt = GameServerProt.LOGOUT_TRANSFER override fun encode( streamCipher: StreamCipher, buffer: JagByteBuf, message: LogoutTransfer, ) { buffer.pjstr(message.host) buffer.p2(message.id) buffer.p4(message.properties) } }
4
Kotlin
6
27
349184703744ee53a0c260c2aad88846b95dcb93
794
rsprot
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/SettingsPower.kt
karakum-team
387,062,541
false
{"Kotlin": 2961484, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/SettingsPower") package mui.icons.material @JsName("default") external val SettingsPower: SvgIconComponent
0
Kotlin
5
35
d12f6b1ad1b215ad7d3d9f27e24d48ada9b7fe2d
190
mui-kotlin
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/cloudwatch/MetricWidgetProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 149148378}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.cloudwatch import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Number import kotlin.String import kotlin.Unit /** * Basic properties for widgets that display metrics. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.cloudwatch.*; * MetricWidgetProps metricWidgetProps = MetricWidgetProps.builder() * .height(123) * .region("region") * .title("title") * .width(123) * .build(); * ``` */ public interface MetricWidgetProps { /** * Height of the widget. * * Default: - 6 for Alarm and Graph widgets. * 3 for single value widgets where most recent value of a metric is displayed. */ public fun height(): Number? = unwrap(this).getHeight() /** * The region the metrics of this graph should be taken from. * * Default: - Current region */ public fun region(): String? = unwrap(this).getRegion() /** * Title for the graph. * * Default: - None */ public fun title(): String? = unwrap(this).getTitle() /** * Width of the widget, in a grid of 24 units wide. * * Default: 6 */ public fun width(): Number? = unwrap(this).getWidth() /** * A builder for [MetricWidgetProps] */ @CdkDslMarker public interface Builder { /** * @param height Height of the widget. */ public fun height(height: Number) /** * @param region The region the metrics of this graph should be taken from. */ public fun region(region: String) /** * @param title Title for the graph. */ public fun title(title: String) /** * @param width Width of the widget, in a grid of 24 units wide. */ public fun width(width: Number) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.cloudwatch.MetricWidgetProps.Builder = software.amazon.awscdk.services.cloudwatch.MetricWidgetProps.builder() /** * @param height Height of the widget. */ override fun height(height: Number) { cdkBuilder.height(height) } /** * @param region The region the metrics of this graph should be taken from. */ override fun region(region: String) { cdkBuilder.region(region) } /** * @param title Title for the graph. */ override fun title(title: String) { cdkBuilder.title(title) } /** * @param width Width of the widget, in a grid of 24 units wide. */ override fun width(width: Number) { cdkBuilder.width(width) } public fun build(): software.amazon.awscdk.services.cloudwatch.MetricWidgetProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.cloudwatch.MetricWidgetProps, ) : CdkObject(cdkObject), MetricWidgetProps { /** * Height of the widget. * * Default: - 6 for Alarm and Graph widgets. * 3 for single value widgets where most recent value of a metric is displayed. */ override fun height(): Number? = unwrap(this).getHeight() /** * The region the metrics of this graph should be taken from. * * Default: - Current region */ override fun region(): String? = unwrap(this).getRegion() /** * Title for the graph. * * Default: - None */ override fun title(): String? = unwrap(this).getTitle() /** * Width of the widget, in a grid of 24 units wide. * * Default: 6 */ override fun width(): Number? = unwrap(this).getWidth() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): MetricWidgetProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.cloudwatch.MetricWidgetProps): MetricWidgetProps = CdkObjectWrappers.wrap(cdkObject) as? MetricWidgetProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: MetricWidgetProps): software.amazon.awscdk.services.cloudwatch.MetricWidgetProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.cloudwatch.MetricWidgetProps } }
1
Kotlin
0
4
a18731816a3ec710bc89fb8767d2ab71cec558a6
4,618
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/example/todolist_mvvm/ui/tasks/TasksFragment.kt
Kirill-Pg4
642,853,703
false
null
package com.example.todolist_mvvm.ui.tasks import android.os.Bundle import androidx.fragment.app.Fragment import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.SearchView import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.todolist_mvvm.R import com.example.todolist_mvvm.data.SortOrder import com.example.todolist_mvvm.data.Task import com.example.todolist_mvvm.databinding.FragmentTasksBinding import com.example.todolist_mvvm.util.exhaustive import com.example.todolist_mvvm.util.onQueryTextChanged import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch @AndroidEntryPoint class TasksFragment : Fragment(R.layout.fragment_tasks), TasksAdapter.OnItemClickListener { private val viewModel: TasksViewModel by viewModels() private lateinit var searchView: SearchView override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentTasksBinding.bind(view) val taskAdapter = TasksAdapter(this) binding.apply { recyclerViewTasks.apply { adapter = taskAdapter layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) } ItemTouchHelper(object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val task = taskAdapter.currentList[viewHolder.adapterPosition] viewModel.onTaskSwiped(task) } }).attachToRecyclerView(recyclerViewTasks) fabAddTask.setOnClickListener { viewModel.onAddNewTaskClick() } } setFragmentResultListener("add_edit_request") { _, bundle -> val result = bundle.getInt("add_edit_result") viewModel.onAddEditResult(result) } viewModel.tasks.observe(viewLifecycleOwner) { taskAdapter.submitList(it) } viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.tasksEvent.collect { event -> when (event) { is TasksViewModel.TasksEvent.ShowUndoDeleteTaskMessage -> { Snackbar.make(requireView(), "Task deleted", Snackbar.LENGTH_LONG) .setAction("UNDO") { viewModel.onUndoDeleteClick(event.task) }.show() } is TasksViewModel.TasksEvent.NavigateToAddTaskScreen -> { val action = TasksFragmentDirections.actionTasksFragmentToAddEditTaskFragment( "New Task", null ) findNavController().navigate(action) } is TasksViewModel.TasksEvent.NavigateToEditTaskScreen -> { val action = TasksFragmentDirections.actionTasksFragmentToAddEditTaskFragment( "Edit Task", event.task ) findNavController().navigate(action) } is TasksViewModel.TasksEvent.ShowTaskSavedConfirmationMessage -> { Snackbar.make(requireView(), event.msg, Snackbar.LENGTH_SHORT).show() } is TasksViewModel.TasksEvent.NavigateToDeleteAllCompletedScreen -> { val action = TasksFragmentDirections.actionGlobalDeleteAllCompletedDialogFragment() findNavController().navigate(action) } }.exhaustive } } setHasOptionsMenu(true) } override fun onItemClick(task: Task) { viewModel.onTaskSelected(task) } override fun onCheckBoxClick(task: Task, isChecked: Boolean) { viewModel.onTaskCheckedChanged(task, isChecked) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_fragment_tasks, menu) val searchItem = menu.findItem(R.id.action_search) searchView = searchItem.actionView as SearchView val pendingQuery = viewModel.searchQuery.value if (pendingQuery != null && pendingQuery.isNotEmpty()) { searchItem.expandActionView() searchView.setQuery(pendingQuery, false) } searchView.onQueryTextChanged { viewModel.searchQuery.value = it } viewLifecycleOwner.lifecycleScope.launch { menu.findItem(R.id.action_hide_completed_tasks).isChecked = viewModel.preferencesFlow.first().hideCompleted } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_sort_by_name -> { viewModel.onSortOrderSelected(SortOrder.BY_NAME) true } R.id.action_sort_by_created -> { viewModel.onSortOrderSelected(SortOrder.BY_DATE) true } R.id.action_hide_completed_tasks -> { item.isChecked = !item.isChecked viewModel.onHideCompletedClick(item.isChecked) true } R.id.action_delete_completed_tasks -> { viewModel.onDeleteAllCompletedClick() true } else -> super.onOptionsItemSelected(item) } } override fun onDestroyView() { super.onDestroyView() searchView.setOnQueryTextListener(null) } }
0
Kotlin
0
0
90d51a4618c6ad641386b074adfd937316a7b7f4
6,805
ToDoList_MVVM
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/CheckBoxDsl.kt
Hexworks
94,116,947
false
null
package org.hexworks.zircon.api.dsl.component import org.hexworks.zircon.api.builder.component.CheckBoxBuilder import org.hexworks.zircon.api.component.CheckBox import org.hexworks.zircon.api.component.Container import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder /** * Creates a new [CheckBox] using the component builder DSL and returns it. */ fun buildCheckBox(init: CheckBoxBuilder.() -> Unit): CheckBox = CheckBoxBuilder().apply(init).build() /** * Creates a new [CheckBox] using the component builder DSL, adds it to the * receiver [BaseContainerBuilder] it and returns the [CheckBox]. */ fun <T : BaseContainerBuilder<*, *>> T.checkBox( init: CheckBoxBuilder.() -> Unit ): CheckBox = buildChildFor(this, CheckBoxBuilder(), init)
42
null
138
735
9eeabb2b30e493189c9931f40d48bae877cf3554
774
zircon
Apache License 2.0
feature/profile/src/main/java/com/ilinskiy/profile/domain/repository/ProfileAuthenticationRepository.kt
ILINSK
812,367,447
false
{"Gradle": 19, "Java Properties": 18, "Shell": 1, "Text": 83, "Ignore List": 3, "Batchfile": 1, "INI": 32, "Proguard": 17, "XML": 138, "Kotlin": 166, "Java": 195, "JSON": 48, "SQL": 26, "TOML": 1, "Gradle Kotlin DSL": 1, "JAR Manifest": 1, "PureBasic": 2}
package com.ilinskiy.profile.domain.repository interface ProfileAuthenticationRepository { suspend fun signOut() }
0
Java
0
0
dd44b688eff235bfeadff2d2c8115b6c64b3b6c7
119
Movie
Apache License 2.0
src/main/kotlin/com/dmitrenko/dbuploadservice/service/datasource/impl/DataSourceServiceImpl.kt
NikolayNS
312,267,933
false
null
package com.dmitrenko.dbuploadservice.service.datasource.impl import com.dmitrenko.dbuploadservice.domain.datasourse.DataSource import com.dmitrenko.dbuploadservice.dto.datasource.DataSourceAddRequest import com.dmitrenko.dbuploadservice.dto.datasource.DataSourceRequest import com.dmitrenko.dbuploadservice.dto.datasource.DataSourceUpdateRequest import org.springframework.stereotype.Service import reactor.core.publisher.Flux import reactor.core.publisher.Mono import com.dmitrenko.dbuploadservice.service.datasource.DataSourceService import com.dmitrenko.dbuploadservice.service.datasource.domain.DataSourceDomainService @Service class DataSourceServiceImpl( private val domainService: DataSourceDomainService ) : DataSourceService { override fun add(request: DataSourceAddRequest): Mono<DataSource> = domainService.add(request) override fun get(request: DataSourceRequest): Mono<DataSource> = domainService.get(request) override fun getAll(): Flux<DataSource> = domainService.getAll() override fun update(request: DataSourceUpdateRequest): Mono<DataSource> = domainService.update(request) override fun delete(request: DataSourceRequest): Mono<Void> = domainService.delete(request) }
0
Kotlin
0
0
f57fc19c90a22fc5849c83ddbe81c8b9b1eea6d4
1,281
DBUploadService
MIT License
app/src/main/java/ch/abwesend/privatecontacts/infrastructure/room/contactdata/ContactDataEntityExtensions.kt
fgubler
462,182,037
false
{"Kotlin": 1123936, "Java": 369326}
/* * Private Contacts * Copyright (c) 2022. * Florian Gubler */ package ch.abwesend.privatecontacts.infrastructure.room.contactdata import ch.abwesend.privatecontacts.domain.lib.logging.logger import ch.abwesend.privatecontacts.domain.model.contact.IContactIdInternal import ch.abwesend.privatecontacts.domain.model.contactdata.ContactData import ch.abwesend.privatecontacts.domain.model.contactdata.ContactDataIdInternal import ch.abwesend.privatecontacts.domain.model.contactdata.GenericContactData import ch.abwesend.privatecontacts.domain.model.contactdata.IContactDataIdExternal import ch.abwesend.privatecontacts.domain.model.contactdata.IContactDataIdInternal import ch.abwesend.privatecontacts.domain.model.contactdata.StringBasedContactData import ch.abwesend.privatecontacts.domain.util.simpleClassName /** * If this produces a build-error "when needs to be exhaustive", although it is exhaustive, * just run "clean", then it should work */ fun ContactData.toEntity(contactId: IContactIdInternal): ContactDataEntity = when (this) { is StringBasedContactData -> stringBasedToEntity(contactId) is GenericContactData<*, *> -> toEntity(contactId) } private fun StringBasedContactData.stringBasedToEntity(contactId: IContactIdInternal): ContactDataEntity { val internalId: IContactDataIdInternal = when (val fixedId = id) { is IContactDataIdInternal -> fixedId is IContactDataIdExternal -> ContactDataIdInternal.randomId().also { logger.warning("Replaced external ID of $simpleClassName with an internal one") } } return ContactDataEntity( id = internalId.uuid, contactId = contactId.uuid, category = category, type = type.toEntity(), sortOrder = sortOrder, isMain = isMain, valueRaw = value, valueFormatted = formattedValue, valueForMatching = valueForMatching, ) } private fun <TValue, TThis : GenericContactData<TValue, TThis>> GenericContactData<TValue, TThis>.toEntity(contactId: IContactIdInternal): ContactDataEntity { val internalId: IContactDataIdInternal = when (val fixedId = id) { is IContactDataIdInternal -> fixedId is IContactDataIdExternal -> ContactDataIdInternal.randomId().also { logger.warning("Replaced external ID of $simpleClassName with an internal one") } } return ContactDataEntity( id = internalId.uuid, contactId = contactId.uuid, category = category, type = type.toEntity(), sortOrder = sortOrder, isMain = isMain, valueRaw = serializedValue(), valueFormatted = displayValue, valueForMatching = displayValue, ) }
2
Kotlin
1
9
fe855a8b3154186f255435f7f6847b00014bf101
2,789
PrivateContacts
Apache License 2.0
varp-cli/src/main/kotlin/net/voxelpi/varp/cli/command/parser/tree/WarpParser.kt
VoxelPi
869,165,536
false
{"Kotlin": 178363, "Java": 2122}
package net.voxelpi.varp.cli.command.parser.tree import net.voxelpi.varp.exception.tree.WarpNotFoundException import net.voxelpi.varp.warp.Tree import net.voxelpi.varp.warp.Warp import net.voxelpi.varp.warp.path.WarpPath import org.incendo.cloud.context.CommandContext import org.incendo.cloud.context.CommandInput import org.incendo.cloud.parser.ArgumentParseResult import org.incendo.cloud.parser.ArgumentParser import org.incendo.cloud.parser.ParserDescriptor import org.incendo.cloud.suggestion.BlockingSuggestionProvider import kotlin.collections.map import kotlin.getOrElse import kotlin.jvm.java class WarpParser<C : Any>( val treeSource: () -> Tree, ) : ArgumentParser<C, Warp>, BlockingSuggestionProvider.Strings<C> { override fun parse( commandContext: CommandContext<C>, commandInput: CommandInput, ): ArgumentParseResult<Warp> { val input = commandInput.peekString() val path = WarpPath.Companion.parse(input).getOrElse { return ArgumentParseResult.failure(it) } val tree = treeSource() val warp = tree.resolve(path) ?: return ArgumentParseResult.failure(WarpNotFoundException(path)) commandInput.readString() return ArgumentParseResult.success(warp) } override fun stringSuggestions(commandContext: CommandContext<C>, input: CommandInput): List<String> { val tree = treeSource() return tree.warps().map { it.path.toString() } } } fun <C : Any> warpParser(treeSource: () -> Tree): ParserDescriptor<C, Warp> { return ParserDescriptor.of( WarpParser<C>(treeSource), Warp::class.java, ) }
0
Kotlin
0
0
f9c616f84996d87363d37ba64eac4f89b9a32bd6
1,645
Varp
MIT License
src/test/kotlin/com/aeolus/core/usecase/comparator/server/ServerOfferParserTest.kt
team-aeolus
668,382,094
false
null
package com.aeolus.core.usecase.comparator.server import com.aeolus.core.domain.comparison.ComparisonOfferType import com.aeolus.core.domain.comparison.Offer import com.aeolus.core.domain.comparison.Resource import com.aeolus.core.domain.server.Location import com.aeolus.core.domain.server.OfferType import com.aeolus.core.domain.server.OperatingSystem import com.aeolus.core.domain.server.Provider import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test class ServerOfferParserTest { @Test fun `Given server When parse Then return offer with resources`() { var servers = listOf( FlattenedServer( sku = "SKU", offerType = OfferType.ONDEMAND, location = Location.US, cpuCount = 2, memory = 14, operatingSystem = OperatingSystem.LINUX, instanceType = "TEST", price = 140.45, pricePerHour = 14.45, provider = Provider.AWS, ), FlattenedServer( sku = "SKU", offerType = OfferType.ONDEMAND, location = Location.US, cpuCount = 2, memory = 14, operatingSystem = OperatingSystem.LINUX, instanceType = "TEST", price = 144.45, pricePerHour = 14.47, provider = Provider.AWS, ) ) val bestServer = FlattenedServer( sku = "SKU", offerType = OfferType.RESERVED, location = Location.US, cpuCount = 2, memory = 14, operatingSystem = OperatingSystem.LINUX, instanceType = "TEST", price = 140.45, pricePerHour = 14.45, provider = Provider.AWS, ) val result = ServerOfferParser().parse( servers = servers, bestServer = bestServer) val expectedOffer = Offer( type = ComparisonOfferType.SERVER, best = Provider.AWS, resources = listOf( Resource( sku = "SKU", offerType = OfferType.ONDEMAND, location = Location.US, cpuCount = 2, memory = 14, operatingSystem = OperatingSystem.LINUX, instanceType = "TEST", price = 140.45, pricePerHour = 14.45, provider = Provider.AWS, ), Resource( sku = "SKU", offerType = OfferType.ONDEMAND, location = Location.US, cpuCount = 2, memory = 14, operatingSystem = OperatingSystem.LINUX, instanceType = "TEST", price = 144.45, pricePerHour = 14.47, provider = Provider.AWS, ) ) ) Assertions.assertThat(result) .usingRecursiveComparison() .isEqualTo(expectedOffer) } }
0
Kotlin
0
0
be9bca77f166baa339962c6f3264beb164f91dfb
3,222
aeolus-service
MIT License
buildSrc/src/main/kotlin/org/saigon/striker/gradle/GithubTools.kt
kupcimat
146,526,527
false
null
package org.saigon.striker.gradle import io.ktor.client.request.* import io.ktor.http.ContentType import io.ktor.http.contentType import kotlinx.serialization.* @Serializable data class PullRequestCreate( val title: String, val head: String, val base: String ) @Serializable data class PullRequest( val number: Int, val title: String, val url: String ) suspend fun existsPullRequest(githubToken: String, pullRequest: PullRequestCreate): Boolean { val pullRequests = withHttpClient { get<List<PullRequest>> { pullRequestUrl(pullRequest.head, pullRequest.base) authorization(githubToken) } } return pullRequests.isNotEmpty() } suspend fun createPullRequest(githubToken: String, pullRequest: PullRequestCreate) { if (existsPullRequest(githubToken, pullRequest)) { return } withHttpClient { post<PullRequest> { pullRequestUrl() authorization(githubToken) contentType(ContentType.Application.Json) body = pullRequest } } } private fun HttpRequestBuilder.pullRequestUrl(head: String? = null, base: String? = null) { url("https://api.github.com/repos/kupcimat/striker/pulls") parameter("head", head) parameter("base", base) } private fun HttpRequestBuilder.authorization(githubToken: String) { header("Authorization", "token $githubToken") }
6
Kotlin
0
0
fb29449914968d7d0b88180377d6d259becc35c5
1,422
striker
MIT License
newm-chain/src/main/kotlin/io/newm/chain/grpc/StateQueryClientPool.kt
projectNEWM
447,979,150
false
{"Kotlin": 2264693, "HTML": 154009, "Shell": 2775, "Dockerfile": 2535, "Procfile": 60}
package io.newm.chain.grpc import io.ktor.server.application.ApplicationEnvironment import io.newm.kogmios.StateQueryClient import io.newm.kogmios.createStateQueryClient import io.newm.objectpool.DefaultPool import io.newm.shared.koin.inject import org.koin.core.parameter.parametersOf import org.slf4j.Logger class StateQueryClientPool( capacity: Int ) : DefaultPool<StateQueryClient>(capacity) { private val log: Logger by inject { parametersOf("StateQueryClientPool") } private val environment: ApplicationEnvironment by inject() private val ogmiosConfig by lazy { environment.config.config("ogmios") } private val websocketHost: String by lazy { ogmiosConfig.property("server").getString() } private val websocketPort: Int by lazy { ogmiosConfig.property("port").getString().toInt() } private val secure: Boolean by lazy { ogmiosConfig.property("secure").getString().toBoolean() } override suspend fun produceInstance(): StateQueryClient { return try { val client = createStateQueryClient(websocketHost, websocketPort, secure) val connectResult = client.connect() require(connectResult) { "Could not connect to ogmios!" } require(client.isConnected) { "Ogmios not connected!" } client } catch (e: Throwable) { log.error("Could not produceInstance()!", e) throw e } } override suspend fun validateInstance(instance: StateQueryClient) { try { require(instance.isConnected) { "Ogmios not connected!" } // Query the SystemStart value to validate the instance instance.networkStartTime() } catch (e: Throwable) { log.error("Could not validateInstance()!", e) throw e } super.validateInstance(instance) } override fun disposeInstance(instance: StateQueryClient) { try { instance.shutdown() } catch (e: Throwable) { log.error("Could not disposeInstance()!", e) throw e } super.disposeInstance(instance) } }
1
Kotlin
5
10
83abe43e0dd7c8dc7888b4ddbe7bbecaa709b986
2,167
newm-server
Apache License 2.0
cinescout/utils/android/src/main/kotlin/cinescout/utils/android/CineScoutViewModel.kt
fardavide
280,630,732
false
null
package cinescout.utils.android import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch abstract class CineScoutViewModel<Action, State>(initialState: State) : ViewModel() { @PublishedApi internal val mutableState = MutableStateFlow(initialState) val state: StateFlow<State> = mutableState.asStateFlow() abstract fun submit(action: Action) protected inline fun updateState(crossinline block: suspend (currentState: State) -> State) { viewModelScope.launch { mutableState.value = block(mutableState.value) } } }
10
Kotlin
2
6
7a875cd67a3df0ab98af520485122652bd5de560
754
CineScout
Apache License 2.0
app/src/main/java/com/minapp/android/example/base/BaseDialog.kt
ifanrx
178,979,868
false
{"Java": 270447, "Kotlin": 266477}
package com.minapp.android.example.base import android.content.Context import android.content.DialogInterface import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.view.Gravity import android.view.ViewGroup import android.view.Window import android.view.WindowManager import androidx.appcompat.app.AppCompatDialog import com.minapp.android.example.util.Util abstract class BaseDialog: AppCompatDialog { constructor(context: Context?) : super(context) constructor(context: Context?, theme: Int) : super(context, theme) constructor(context: Context?, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super( context, cancelable, cancelListener ) override fun show() { super.show() window?.attributes?.apply { width = context.resources.displayMetrics.widthPixels - Util.dp2px(context, 24) height = WindowManager.LayoutParams.WRAP_CONTENT gravity = Gravity.CENTER } window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) } }
2
null
1
1
6e4a222ae69e2e26e981f1a4345c20caece49520
1,111
hydrogen-android-sdk
Apache License 2.0
eux-nav-rinasak-webapp/src/main/kotlin/no/nav/eux/rinasak/DataSourceProperties.kt
navikt
663,010,258
false
{"Kotlin": 73262, "HTML": 2030, "Makefile": 122, "Dockerfile": 110}
package no.nav.eux.rinasak import com.zaxxer.hikari.HikariConfig import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties(prefix = "spring.datasource") data class DataSourceProperties( var hikari: HikariConfig )
2
Kotlin
0
0
79b896b54831a5ea5c6d17a6a28a6d2db636f882
261
eux-nav-rinasak
MIT License
example-06/src/main/java/com/itdog/example_06/MyAppComponent.kt
frannnnnk
745,865,818
false
{"Kotlin": 63298}
package com.itdog.example_06 import android.content.Context import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.support.AndroidSupportInjectionModule @Component(modules = [ AndroidInjectionModule::class, AndroidSupportInjectionModule::class, ActivityModule::class]) abstract class MyAppComponent { @Component.Builder interface Builder { @BindsInstance fun context(context: Context) : Builder fun build() : MyAppComponent } abstract fun inject(app: MyApplication) }
0
Kotlin
0
0
e4c76a3f6ab10b58af1de7dfb012f780afce0a4a
587
android-dagger-examples
Apache License 2.0
app/src/main/java/com/aidaraly/letschat/core/GroupQuery.kt
Aidaraly
445,244,722
false
{"Kotlin": 427187}
package com.aidaraly.letschat.core import com.google.firebase.firestore.CollectionReference import com.aidaraly.letschat.db.DbRepository import com.aidaraly.letschat.db.data.ChatUser import com.aidaraly.letschat.db.data.Group import com.aidaraly.letschat.utils.MPreference import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import timber.log.Timber class GroupQuery(private val groupId: String,private val dbRepository: DbRepository,private val preference: MPreference) { private val myUserId=preference.getUid()!! fun getGroupData(groupCollection: CollectionReference){ val userId=preference.getUid() groupCollection.document(groupId).get().addOnSuccessListener { snapshot-> snapshot?.let { data -> if (!data.exists()) return@addOnSuccessListener val group=data.toObject(Group::class.java) val profiles=group?.profiles val index=profiles!!.indexOfFirst { it.uId==userId } profiles.removeAt(index) profiles.add(0,preference.getUserProfile()!!) //moving localuser to 0 th index group.profiles=profiles CoroutineScope(Dispatchers.IO).launch { checkAlreadySavedMember(group, dbRepository.getChatUserList()) } } }.addOnFailureListener { Timber.v("GroupDataGrtting failed ${it.message}") } } private fun checkAlreadySavedMember(group: Group, list: List<ChatUser>){ val chatUsers= ArrayList<ChatUser>() for (profile in group.profiles!!){ if (profile.uId==myUserId) { chatUsers.add(ChatUser(myUserId, "You", profile)) continue } val chatUser=list.firstOrNull { it.id==profile.uId } if (chatUser==null){ val localName="${profile.mobile?.country} ${profile.mobile?.number}" val user=ChatUser(profile.uId.toString(),localName,profile) chatUsers.add(user) }else chatUsers.add(chatUser) } group.members=chatUsers group.profiles= ArrayList() dbRepository.insertMultipleUser(chatUsers) dbRepository.insertGroup(group) } }
0
Kotlin
0
0
2f4fb858fe8cec51a9bcacab600b7c4a292cef75
2,341
LetsChatFinal
MIT License
data/src/main/java/com/udacity/political/preparedness/data/response/geocode/GeocodeResponse.kt
RicardoBravoA
321,486,289
false
null
package com.udacity.political.preparedness.data.response.geocode import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class GeocodeResponse( val status: String, val results: List<ResultResponse> ) : Parcelable
0
Kotlin
0
1
7b04440ba25aa12ada732603283ea06e35fb4e54
251
PoliticalPreparedness
Apache License 2.0
brd-android/app/src/main/java/com/breadwallet/ui/verifyaccount/VerifyController.kt
fabriik
489,117,365
false
null
package com.breadwallet.ui.verifyaccount import android.os.Bundle import com.breadwallet.databinding.ControllerVerifyAccountBinding import com.breadwallet.ui.BaseMobiusController import com.breadwallet.ui.flowbind.clicks import com.breadwallet.ui.verifyaccount.VerifyScreen.E import com.breadwallet.ui.verifyaccount.VerifyScreen.F import com.breadwallet.ui.verifyaccount.VerifyScreen.M import com.spotify.mobius.Connectable import com.spotify.mobius.Init import drewcarlson.mobius.flow.first import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge class VerifyController( args: Bundle? = null ) : BaseMobiusController<M, E, F>(args) { override val defaultModel = M override val update = VerifyUpdate override val init: Init<M, F> = Init<M, F> { model -> first(model) } override val effectHandler = Connectable<F, E> { VerifyScreenHandler() } private val binding by viewBinding(ControllerVerifyAccountBinding::inflate) override fun bindView(modelFlow: Flow<M>): Flow<E> { return with(binding) { merge( btnVerifyAccount.clicks().map { E.OnVerifyClicked }, btnDismiss.clicks().map { E.OnDismissClicked } ) } } }
2
Kotlin
1
1
8894f5c38203c64e48242dae9ae9344ed4b2a61f
1,293
wallet-android
MIT License
src/test/java/com/github/ai/kpdiff/domain/diff/formatter/DiffDecoratorTest.kt
aivanovski
607,687,384
false
{"Kotlin": 246920, "Ruby": 3377}
package com.github.ai.kpdiff.domain.diff.formatter import com.github.ai.kpdiff.TestEntityFactory.newEntry import com.github.ai.kpdiff.TestEntityFactory.newField import com.github.ai.kpdiff.TestEntityFactory.newGroup import com.github.ai.kpdiff.domain.diff.differ.PathDatabaseDiffer import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.ENTRY1 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.ENTRY2 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.ENTRY3 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.ENTRY4 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.GROUP1 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.GROUP2 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.GROUP3 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.GROUP4 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.GROUP5 import com.github.ai.kpdiff.domain.diff.formatter.DiffDecoratorTest.Ids.ROOT import com.github.ai.kpdiff.entity.DatabaseEntity import com.github.ai.kpdiff.entity.DiffResult import com.github.ai.kpdiff.entity.KeepassDatabase import com.github.ai.kpdiff.testUtils.AssertionDsl.shouldBe import com.github.ai.kpdiff.testUtils.NodeTreeDsl.dbTree import com.github.ai.kpdiff.testUtils.createUuidFrom import com.github.aivanovski.keepasstreediff.PathDiffer import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class DiffDecoratorTest { @Test fun `aggregate should group events by type`() { // arrange val lhs = dbTree(newGroup(ROOT)) { entry( newEntry( id = ENTRY1, custom = mapOf( "A" to "A", "C" to "C" ) ) ) } val rhs = dbTree(newGroup(ROOT)) { entry( newEntry( id = ENTRY1, custom = mapOf( "B" to "B", "C" to "C1" ) ) ) } // act val events = newDecorator().decorate(lhs.diffWith(rhs)) // assert events.size shouldBe 1 events[0].first shouldBe createUuidFrom(ENTRY1) events[0].second.shouldBe { size(3) update( oldParent = createUuidFrom(ENTRY1), newParent = createUuidFrom(ENTRY1), oldEntity = newField("C", "C"), newEntity = newField("C", "C1") ) delete(createUuidFrom(ENTRY1), newField("A", "A")) insert(createUuidFrom(ENTRY1), newField("B", "B")) } } @Test fun `aggregate should sort events by entity type`() { // arrange val lhs = dbTree(newGroup(ROOT)) { group(newGroup(GROUP1)) } val rhs = dbTree(newGroup(ROOT)) { } // act val events = newDecorator().decorate(lhs.diffWith(rhs)) // assert events.size shouldBe 1 } @Test fun `aggregate should sort events by name`() { // arrange val lhs = dbTree(newGroup(ROOT)) { entry(newEntry(ENTRY1)) } val rhs = dbTree(newGroup(ROOT)) { entry( newEntry( id = ENTRY1, custom = mapOf( "C" to "C", "A" to "A", "B" to "B" ) ) ) } // act val events = newDecorator().decorate(lhs.diffWith(rhs)) // assert events.size shouldBe 1 events.first().first shouldBe createUuidFrom(ENTRY1) events.first().second.shouldBe { size(3) insert(createUuidFrom(ENTRY1), newField("A", "A")) insert(createUuidFrom(ENTRY1), newField("B", "B")) insert(createUuidFrom(ENTRY1), newField("C", "C")) } } @Test fun `aggregate should group events by depth`() { // arrange val lhs = dbTree(newGroup(ROOT)) { entry(newEntry(ENTRY1)) group(newGroup(GROUP1)) group(newGroup(GROUP3)) { entry(newEntry(ENTRY3)) group(newGroup(GROUP4)) } } val rhs = dbTree(newGroup(ROOT)) { entry(newEntry(ENTRY2)) group(newGroup(GROUP2)) group(newGroup(GROUP3)) { entry(newEntry(ENTRY4)) group(newGroup(GROUP5)) } } // act val events = newDecorator().decorate(lhs.diffWith(rhs)) // assert events.size shouldBe 2 events[0].first shouldBe createUuidFrom(ROOT) events[0].second.shouldBe { size(4) delete(createUuidFrom(ROOT), newGroup(GROUP1)) delete(createUuidFrom(ROOT), newEntry(ENTRY1)) insert(createUuidFrom(ROOT), newGroup(GROUP2)) insert(createUuidFrom(ROOT), newEntry(ENTRY2)) } events[1].first shouldBe createUuidFrom(GROUP3) events[1].second.shouldBe { size(4) delete(createUuidFrom(GROUP3), newGroup(GROUP4)) delete(createUuidFrom(GROUP3), newEntry(ENTRY3)) insert(createUuidFrom(GROUP3), newGroup(GROUP5)) insert(createUuidFrom(GROUP3), newEntry(ENTRY4)) } } private fun KeepassDatabase.diffWith( another: KeepassDatabase ): DiffResult<KeepassDatabase, DatabaseEntity> { return PathDatabaseDiffer(PathDiffer()).getDiff(this, another) } private fun newDecorator(): DiffDecorator = DiffDecorator() private object Ids { const val ROOT = 0 const val GROUP1 = 1 const val GROUP2 = 2 const val GROUP3 = 3 const val GROUP4 = 4 const val GROUP5 = 5 const val ENTRY1 = 11 const val ENTRY2 = 12 const val ENTRY3 = 13 const val ENTRY4 = 14 } }
0
Kotlin
1
4
5b4d6ca77629cb63190679b12038c8f8e8a121aa
6,221
kp-diff
Apache License 2.0
app/src/main/java/com/mplr/hackernews/api/CoreHomeApi.kt
mleyvar
376,436,739
false
null
package com.mplr.hackernews.api import com.mplr.hackernews.models.ApiNewsHitsModel import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query interface CoreHomeApi { @GET("/api/v1/search_by_date") @Headers("Content-Type: application/json ") fun getHits( @Query("query") query: String = QUERY_HITS, @Query("page") page: Int = 0 ): Observable<ApiNewsHitsModel> }
0
Kotlin
0
0
1c8efbfccd958fbb76b3cdea2de5a25bc2806854
453
HackerNews
Apache License 2.0
android/testSrc/com/android/tools/idea/run/deployment/liveedit/ComposeRuntimeTestUtil.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.run.deployment.liveedit import com.android.testutils.TestUtils import com.android.tools.compose.ComposePluginIrGenerationExtension import com.android.tools.idea.testing.AndroidProjectRule import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.testFramework.PsiTestUtil import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension /** * Path to the compose-runtime jar. Note that unlike all other dependencies, we * don't need to load that into the test's runtime classpath. Instead, we just * need to make sure it is in the classpath input of the compiler invocation * Live Edit uses. Aside from things like references to the @Composable * annotation, we actually don't need anything from that runtime during the compiler. * The main reason to include that is because the compose compiler plugin expects * the runtime to be path of the classpath or else it'll throw an error. */ internal val composeRuntimePath = TestUtils.resolveWorkspacePath( "tools/adt/idea/compose-ide-plugin/testData/lib/compose-runtime-1.4.0-SNAPSHOT.jar").toString() fun setUpComposeInProjectFixture(projectRule: AndroidProjectRule) { projectRule.module.loadComposeRuntimeInClassPath() // Register the compose compiler plugin much like what Intellij would normally do. if (IrGenerationExtension.getInstances(projectRule.project).find { it is ComposePluginIrGenerationExtension } == null) { IrGenerationExtension.registerExtension(projectRule.project, ComposePluginIrGenerationExtension()) } } /** * Loads the Compose runtime into the project class path. This allows for tests using the compiler (Live Edit/FastPreview) * to correctly invoke the compiler as they would do in prod. */ fun com.intellij.openapi.module.Module.loadComposeRuntimeInClassPath() { // Load the compose runtime into the main module's library dependency. LocalFileSystem.getInstance().refreshAndFindFileByPath(composeRuntimePath) PsiTestUtil.addLibrary(this, composeRuntimePath) }
3
null
230
912
d88742a5542b0852e7cb2dd6571e01576cb52841
2,640
android
Apache License 2.0
base/src/main/java/com/zhangteng/base/recyclerview/widget/ItemMoveTouchHelper.kt
DL-ZhangTeng
269,325,054
false
null
package com.zhangteng.base.widget import android.graphics.Color import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.zhangteng.base.adapter.HeaderOrFooterAdapter import com.zhangteng.base.base.BaseAdapter import java.util.* /** * Created by swing on 2018/5/7. * Creates an ItemTouchHelper that will work with the given Callback. * * * You can attach ItemTouchHelper to a RecyclerView via * [.attachToRecyclerView]. Upon attaching, it will add an item decoration, * an onItemTouchListener and a Child attach / detach listener to the RecyclerView. * * @param callback The Callback which controls the behavior of this touch helper. */ open class ItemMoveTouchHelper(callback: Callback) : ItemTouchHelper(callback) { override fun attachToRecyclerView(recyclerView: RecyclerView?) { super.attachToRecyclerView(recyclerView) } open class MoveTouchCallback : Callback() { /** * 如果是列表布局的话则拖拽方向为DOWN和UP,如果是网格布局的话则是DOWN和UP和LEFT和RIGHT */ override fun getMovementFlags( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ): Int { return if (recyclerView.getLayoutManager() is GridLayoutManager) { val dragFlags = UP or DOWN or LEFT or RIGHT val swipeFlags = 0 makeMovementFlags(dragFlags, swipeFlags) } else { val dragFlags = UP or DOWN val swipeFlags = 0 makeMovementFlags(dragFlags, swipeFlags) } } /** * 将正在拖拽的item和集合的item进行交换元素 */ override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val baseAdapter = recyclerView.adapter as BaseAdapter<*, *>? ?: return true val data = baseAdapter.data //得到当拖拽的viewHolder的Position val fromPosition = viewHolder.adapterPosition //拿到当前拖拽到的item的viewHolder val toPosition = target.adapterPosition val headerCount = if (baseAdapter.hasHeaderOrFooter) (baseAdapter as HeaderOrFooterAdapter<*>?)!!.getHeadersCount() else 0 if (fromPosition < toPosition) { for (i in fromPosition - headerCount until toPosition - headerCount) { Collections.swap(data, i, i + 1) } } else { for (i in fromPosition - headerCount downTo toPosition - headerCount + 1) { Collections.swap(data, i, i - 1) } } baseAdapter.notifyItemMoved(fromPosition, toPosition) return true } /** * 拖曳处理后的回调 */ override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} /** * 长按选中Item的时候开始调用 * * @param viewHolder * @param actionState */ override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { if (actionState != ACTION_STATE_IDLE) { viewHolder?.itemView?.setBackgroundColor(Color.LTGRAY) } super.onSelectedChanged(viewHolder, actionState) } /** * 手指松开的时候还原 * * @param recyclerView * @param viewHolder */ override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { super.clearView(recyclerView, viewHolder) viewHolder.itemView.setBackgroundColor(0) } } }
0
Kotlin
0
8
f0c379af5f248d8be94488d0049cbc4ecf5882fc
3,788
BaseLibrary
The Unlicense
app/src/main/java/com/example/dotoring_neoul/network/DotoringAPIService.kt
Team-Neoul
678,390,604
false
{"Kotlin": 315932}
package com.example.dotoring_neoul.network import com.example.dotoring_neoul.MyApplication import com.example.dotoring_neoul.dto.CommonResponse import com.example.dotoring_neoul.dto.login.FindIdRequest import com.example.dotoring_neoul.dto.login.FindPwdRequest import com.example.dotoring_neoul.dto.login.LoginRequest import com.example.dotoring_neoul.dto.message.MessageRequest import com.example.dotoring_neoul.dto.register.EmailCertificationRequest import com.example.dotoring_neoul.dto.register.EmailCodeRequest import com.example.dotoring_neoul.dto.register.IdValidationRequest import com.example.dotoring_neoul.dto.register.NicknameValidationRequest import com.google.gson.Gson import com.google.gson.GsonBuilder import okhttp3.Interceptor import okhttp3.JavaNetCookieJar import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path import retrofit2.http.Query import java.io.IOException import java.net.CookieManager private const val BASE_URL = "http://192.168.0.60:8080/" /** * Interceptor에 AppInterceptor를 적용하여 토큰 적용 * */ val client: OkHttpClient = OkHttpClient.Builder() .addInterceptor(AppInterceptor()) .cookieJar(JavaNetCookieJar(CookieManager())) .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build() val registerClient: OkHttpClient = OkHttpClient.Builder() .cookieJar(JavaNetCookieJar(CookieManager())) .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build() /** * Gson을 사용하기 위한 설정 * */ val gson : Gson = GsonBuilder() .setLenient() .create() /** * 요청에 BASE_URL 삽입하여 통신하기 위한 retrofit 설정 * */ val retrofit: Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build() /** * 요청에 BASE_URL 삽입하여 통신하기 위한 retrofit 설정 * */ val registerRetrofit: Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(registerClient) .build() /** * 토큰을 저장하기 위한 Interceptor * accesToken에는 헤더의 Authorization에서 받아온 accessToken 토큰을 String값으로 저장 * refreshToken에는 헤더의 Cookie에서 받아온 refreshToken 토큰을 String값으로 저장 * Request를 보낼 때에는 Header에 이전 요청에서 저장되었던 토큰 값들을 넣어서 요청하는 builder 이용 * */ class AppInterceptor : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain) : Response = with(chain) { val accessToken = MyApplication.prefs.getString("Authorization", "") // ViewModel에서 지정한 key로 JWT 토큰을 가져온다. val refreshToken = MyApplication.prefs.getRefresh("Cookie", "") val newRequest = request().newBuilder() .addHeader("Authorization", accessToken) // 헤더에 authorization라는 key로 JWT 를 넣어준다. .addHeader("Cookie", refreshToken) .build() proceed(newRequest) } } interface DotoringAPIService { /** * nicknameValidation: 닉네임 중복확인을 위한 api * */ @POST("api/mento/valid-nickname") fun mentoNicknameValidation( @Body nicknameValidationRequest: NicknameValidationRequest ): Call<CommonResponse> @POST("api/menti/valid-nickname") fun menteeNicknameValidation( @Body nicknameValidationRequest: NicknameValidationRequest ): Call<CommonResponse> /** * loginIdValidation: 아이디 중복확인을 위한 api * */ @POST("api/member/valid-loginId") fun loginIdValidation( @Body loginValidationRequest: IdValidationRequest ): Call<CommonResponse> /** * sendAuthenticationCode: 이메일 확인 코드를 위한 api * */ @GET("api/member/signup/code") fun sendAuthenticationCode( @Query("email", encoded = true) email: String ): Call<CommonResponse> /** * emailCertification: 이메일 확인을 위한 api * */ @POST("api/member/signup/valid-code") fun emailCertification( @Body emailCertificationRequest: EmailCertificationRequest ): Call<CommonResponse> /* 희망 직무와 학과 리스트 불러오기 */ @GET("api/member/job-major") fun getJobAndMajorList(): Call<CommonResponse> /* 희망 멘토링 분야 리스트 불러오기 */ @GET("api/fields") fun getFieldList(): Call<CommonResponse> /* 학과 리스트 불러오기 */ @GET("api/majors") fun getMajorList(): Call<CommonResponse> @Multipart @POST("api/signup-mento") fun signUpAsMentor( @Part("password") password: RequestBody, @Part("majors") majors: RequestBody, @Part("loginId") loginId: RequestBody, @Part("school") school: RequestBody, @Part("grade") grade: Int, @Part("nickname") nickname: RequestBody, @Part certifications: List<MultipartBody.Part>, @Part("fields") fields: RequestBody, @Part("email") email: RequestBody, @Part("introduction") introduction: RequestBody, ):Call<CommonResponse> @Multipart @POST("api/signup-menti") fun signUpAsMentee( @Part("password") password: RequestBody, @Part("majors") majors: RequestBody, @Part("loginId") loginId: RequestBody, @Part("school") school: RequestBody, @Part("grade") grade: Int, @Part("nickname") nickname: RequestBody, @Part certifications: List<MultipartBody.Part>, @Part("fields") fields: RequestBody, @Part("email") email: RequestBody, @Part("introduction") introduction: RequestBody, ):Call<CommonResponse> /* *//** * searchMentee: 홈에서 menti를 받아오는 api * *//* @GET("api/menti/expenses") fun searchMentee( @Query("page") page: Int, @Query("size") size: Int ): Call<CommonResponse>*/ /** * 홈화면에서 멘토를 받아오는 API */ @GET("api/mento") fun getMentor(): Call<CommonResponse> /** * 홈화면에서 멘티를 받아오는 API */ @GET("api/menti") fun getMentee(): Call<CommonResponse> @GET("api/menti") fun searchMenteeWithMajors( @Query("majors") majors: String ): Call<CommonResponse> @GET("api/menti") fun searchMenteeWithJobs( @Query("jobs") jobs: String ): Call<CommonResponse> @GET("api/menti") fun searchMenteeWithAllFilter( @Query("majors") majors: String, @Query("jobs") jobs: String ): Call<CommonResponse> @GET("api/menti/{id}") fun loadMenteeDetailedInfo( @Path("id") id: Int ): Call<CommonResponse> @GET("api/mento/{id}") fun loadMentorDetailedInfo( @Path("id") id: Int ): Call<CommonResponse> /** * doLogin: 로그인을 진행하는 api * */ @POST("member/login") fun doLogin( @Body loginRequest: LoginRequest ): Call<CommonResponse> @POST("api/auth/reissue") fun reissue( ): Call<CommonResponse> /** * inSendMessage: 쪽지함에서 쪽지를 보내는 api * */ @POST("api/mento/letter/in/1") fun inSendMessage( @Body MessageRequest: MessageRequest ): Call<CommonResponse> @POST("api/mento/letter/out/{mentiid}") fun outSendMessage( @Body MessageRequest: MessageRequest ): Call<CommonResponse> /** * loadMessageBox: 쪽지함 리스트를 받아오는 api * */ @GET("api/mento/room") fun loadMessageBox( ): Call<CommonResponse> /** * loadDetailedMessage: 쪽지함 상세 리스트를 받아오는 api * */ @GET("api/mento/letter/{roomPk}") fun loadDetailedMessage( @Path("roomPk") roomPk: Long, @Query("page") page: Int, @Query("size") size: Int ): Call<CommonResponse> /** * getCode: 이메일로 코드를 보내는 api * */ @POST("api/member/code") fun getCode( @Body EmailCodeRequest: EmailCodeRequest ): Call<CommonResponse> /** * findId: 아이디를 받아오는 api * */ @POST("api/member/loginId") fun findId( @Body FindIdRequest: FindIdRequest ): Call<CommonResponse> @POST("api/member/password") fun findPwd( @Body FindPwdRequest: FindPwdRequest ): Call<CommonResponse> } object DotoringAPI { val retrofitService: DotoringAPIService by lazy { retrofit.create(DotoringAPIService::class.java) } } object DotoringRegisterAPI { val retrofitService: DotoringAPIService by lazy { registerRetrofit.create(DotoringAPIService::class.java) } }
5
Kotlin
3
0
a5e380e2ccec0766ae0e04b62e868fcafb82e7e0
8,590
Neoul_Dotoring-AOS
MIT License
domain/src/test/java/com/jlmari/android/basepokedex/domain/usecases/GetPokemonsUseCaseTest.kt
jlmari
561,303,847
false
{"Kotlin": 127493}
package com.jlmari.android.basepokedex.domain.usecases import com.jlmari.android.basepokedex.domain.models.PokemonModel import com.jlmari.android.basepokedex.domain.repositories.PokeRepository import com.jlmari.android.basepokedex.domain.utils.Success import com.jlmari.android.basepokedex.domain.utils.getOrThrow import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerify import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test internal class GetPokemonsUseCaseTest { @MockK private lateinit var pokeRepository: PokeRepository @MockK private lateinit var pokemonList: List<PokemonModel> @InjectMockKs private lateinit var getPokemonsUseCase: GetPokemonsUseCase @Before fun setup() { MockKAnnotations.init(this, relaxUnitFun = true) } private fun mockGetPokemonsSuccessResponse() { coEvery { pokeRepository.getPokemons(any(), any()) } returns Success(pokemonList) } @Test fun `Call PokeRepository to get pokemons with correct parameters when invoked`() { val inputOffset = 60 val inputLimit = 20 mockGetPokemonsSuccessResponse() runBlocking { getPokemonsUseCase.invoke(inputOffset, inputLimit) } coVerify(exactly = 1) { pokeRepository.getPokemons(inputOffset, inputLimit) } } @Test fun `Return the expected List of PokemonModel by PokeRepository when invoked`() { mockGetPokemonsSuccessResponse() val obtainedPokemonList = runBlocking { getPokemonsUseCase.invoke(0, 0) }.getOrThrow() assertEquals(pokemonList, obtainedPokemonList) } }
0
Kotlin
0
0
3dcb577c0bf011e30c5769c21202aa6d98e94f8f
1,769
BasePokedex
Apache License 2.0
app/src/main/java/me/tabraiz/learn/kotlin/flow/data/local/AppDatabase.kt
tabraizjawed
690,481,627
false
{"Kotlin": 99450}
package me.tabraiz.learn.kotlin.flow.data.local import androidx.room.Database import androidx.room.RoomDatabase import me.tabraiz.learn.kotlin.flow.data.local.dao.UserDao import me.tabraiz.learn.kotlin.flow.data.local.entity.User @Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao }
0
Kotlin
0
0
6ac2e31124fa024c244a83bd72f73d74ff7a52f9
366
android-kotlin-flows
Apache License 2.0
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/common/util/JpaUtilities.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2020 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.common.util import jakarta.persistence.EntityManager import org.hibernate.ReplicationMode.OVERWRITE import org.hibernate.engine.spi.SessionImplementor object JpaUtilities { fun <T> replicate(entityManager: EntityManager, entity: T) = entityManager.unwrap(SessionImplementor::class.java).replicate(entity, OVERWRITE) }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
587
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/p1neapplexpress/telegrec/Launcher.kt
p1neappleXpress
763,640,975
false
{"Kotlin": 63624, "Java": 4783, "AIDL": 353}
package com.p1neapplexpress.telegrec import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.p1neapplexpress.telegrec.ui.compose.main.MainScreenView import com.p1neapplexpress.telegrec.ui.compose.recordings.RecordingsScreenView import com.p1neapplexpress.telegrec.ui.theme.TRecorderTheme class Launcher : ComponentActivity() { @OptIn(ExperimentalFoundationApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() setContent { TRecorderTheme { val pagerState = rememberPagerState(pageCount = { 2 }) HorizontalPager(state = pagerState) { page -> when (page) { 0 -> MainScreenView() 1 -> RecordingsScreenView() } } } } } }
0
Kotlin
0
1
e009d7c7f115f6168566bc97c61ea6274978055f
1,215
Telegram-recorder
Apache License 2.0
app/src/main/java/rikka/safetynetchecker/icon/Cancel.kt
RikkaW
409,638,182
false
{"Kotlin": 33513, "Java": 8123}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rikka.safetynetchecker.icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.materialIcon import androidx.compose.material.icons.materialPath import androidx.compose.ui.graphics.vector.ImageVector public val Icons.Outlined.Cancel: ImageVector get() { if (_cancel != null) { return _cancel!! } _cancel = materialIcon(name = "Outlined.Cancel") { materialPath { moveTo(12.0f, 2.0f) curveTo(6.47f, 2.0f, 2.0f, 6.47f, 2.0f, 12.0f) reflectiveCurveToRelative(4.47f, 10.0f, 10.0f, 10.0f) reflectiveCurveToRelative(10.0f, -4.47f, 10.0f, -10.0f) reflectiveCurveTo(17.53f, 2.0f, 12.0f, 2.0f) close() moveTo(12.0f, 20.0f) curveToRelative(-4.41f, 0.0f, -8.0f, -3.59f, -8.0f, -8.0f) reflectiveCurveToRelative(3.59f, -8.0f, 8.0f, -8.0f) reflectiveCurveToRelative(8.0f, 3.59f, 8.0f, 8.0f) reflectiveCurveToRelative(-3.59f, 8.0f, -8.0f, 8.0f) close() moveTo(15.59f, 7.0f) lineTo(12.0f, 10.59f) lineTo(8.41f, 7.0f) lineTo(7.0f, 8.41f) lineTo(10.59f, 12.0f) lineTo(7.0f, 15.59f) lineTo(8.41f, 17.0f) lineTo(12.0f, 13.41f) lineTo(15.59f, 17.0f) lineTo(17.0f, 15.59f) lineTo(13.41f, 12.0f) lineTo(17.0f, 8.41f) close() } } return _cancel!! } private var _cancel: ImageVector? = null
4
Kotlin
34
563
a9c9787509e3a7ef1e609427e52877b8775fcc79
2,309
YASNAC
MIT License
app/src/main/java/com/germanautolabs/acaraus/screens/articles/list/ArticleFilterStateHolder.kt
alexandrucaraus
836,093,916
false
{"Kotlin": 84463}
package com.germanautolabs.acaraus.screens.articles.list import com.germanautolabs.acaraus.models.ArticleFilter import com.germanautolabs.acaraus.models.ArticleSource import com.germanautolabs.acaraus.models.Error import com.germanautolabs.acaraus.models.Result import com.germanautolabs.acaraus.models.SortBy import com.germanautolabs.acaraus.screens.articles.list.components.ArticleFilterState import com.germanautolabs.acaraus.usecase.GetArticlesLanguages import com.germanautolabs.acaraus.usecase.GetArticlesSources import com.germanautolabs.acaraus.usecase.GetLocale import com.germanautolabs.acaraus.usecase.SetLocale import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import java.time.LocalDate class ArticleFilterStateHolder( getArticlesSources: GetArticlesSources, private val setLocale: SetLocale, private val getLocale: GetLocale, private val newsLanguage: GetArticlesLanguages, currentScope: CoroutineScope, ) { private val defaultFilterState = ArticleFilterState( show = ::showFilter, hide = ::hideFilter, setQuery = ::setFilterQuery, setSortBy = ::setFilterSortBy, sortByOptions = SortBy.entries.map { it.name }.toSet(), setSource = ::setFilterSource, setLanguage = ::setFilterLanguage, languageOptions = newsLanguage.options(), setFromDate = ::setFilterFromDate, setToDate = ::setFilterToDate, reset = ::resetFilter, apply = ::applyFilter, ) val filterEditorState = MutableStateFlow(defaultFilterState) val currentFilter = MutableStateFlow(ArticleFilter()) private val articleSources = MutableStateFlow(emptyList<ArticleSource>()) init { // TODO relaunch on error getArticlesSources.stream().onEach { updateArticleSources(it) }.launchIn(currentScope) } private fun updateArticleSources(result: Result<List<ArticleSource>, Error>) { println("Update article sources") when { result.isSuccess -> { articleSources.update { result.success.orEmpty() } filterEditorState.update { it.copy(sourceOptions = buildSourceOptions()) } } result.isError -> { /* todo handle error */ } } } private fun showFilter() { filterEditorState.update { it.copy(isVisible = true) } } private fun hideFilter() { filterEditorState.update { it.copy(isVisible = false) } } private fun setFilterQuery(query: String) { filterEditorState.update { it.copy(query = query) } } private fun setFilterSortBy(sortBy: String) { val sortOrder = SortBy.entries.find { it.name == sortBy } ?: SortBy.MostRecent filterEditorState.update { it.copy(sortBy = sortOrder.name) } } private fun setFilterSource(source: String) { val articleSource = articleSources.value.find { it.name == source } ?: return filterEditorState.update { it.copy(source = articleSource.name) } } private fun setFilterLanguage(language: String) { val languageCode = newsLanguage.getLanguageCodeByName(language) val source = if (getLocale.languageCode() !== languageCode) "All" else filterEditorState.value.source filterEditorState.update { it.copy( language = language, source = source, sourceOptions = buildSourceOptions(languageCode), ) } setLocale.languageCode(languageCode) } private fun setFilterFromDate(date: LocalDate) { filterEditorState.update { it.copy(fromOldestDate = date) } } private fun setFilterToDate(date: LocalDate) { filterEditorState.update { it.copy(toNewestDate = date) } } private fun resetFilter() { currentFilter.update { ArticleFilter() } filterEditorState.update { defaultFilterState.copy( language = newsLanguage.getLanguageCodeByName(getLocale.languageCode()), sourceOptions = buildSourceOptions(), ) } } private fun applyFilter() { currentFilter.update { filterEditorState.value.toArticleFilter() } filterEditorState.update { it.copy(isVisible = false) } } private fun buildSourceOptions( languageCode: String = getLocale.languageCode(), ): Set<String> = setOf("All") + articleSources.value.filter { it.language == languageCode }.map { it.name } private fun ArticleFilterState.toArticleFilter(): ArticleFilter = ArticleFilter( query = query, sortedBy = sortBy.let { SortBy.valueOf(it) }, language = getLocale.languageCode(), sources = articleSources.value.filter { it.name == source }, fromDate = fromOldestDate, toDate = toNewestDate, ) }
0
Kotlin
0
0
bc717901f00417aea53f7230b13f2cc9f21933be
5,016
germanautolabs
MIT License
FlowStateFlowPoc/app/src/main/java/com/example/flowstateflowpoc/mvvmrx/domain/MVVMRxPhotoContract.kt
brunogabriel
335,454,794
false
null
package com.example.flowstateflowpoc.mvvmrx.domain import com.example.flowstateflowpoc.network.models.PhotoResponse import com.example.flowstateflowpoc.shared.adapter.models.Photo import io.reactivex.rxjava3.core.Single interface MVVMRxPhotoContract { interface UseCase { fun getPhotos(): Single<List<Photo>> } interface Repository { fun getPhotos(): Single<List<PhotoResponse>> } }
0
Kotlin
0
2
f7853a80ce9465552beec2395037f25bfb8bc817
417
android-flow-stateflow-poc
MIT License
validate-mapper/src/main/kotlin/ru/ztrap/tools/validate/mapper/FailedValidationException.kt
zTrap
229,632,474
false
null
package ru.ztrap.tools.validate.mapper import ru.ztrap.tools.validate.checks.ValidateChecker private val LINE_SPACING_START = " ".repeat(10) private val LINE_SEPARATOR = ",\n\t$LINE_SPACING_START" class FailedValidationException internal constructor( val failedParams: Map<String, List<ValidateChecker.Result.Error>>, val rawObject: Any, ) : RuntimeException() { override val message: String by lazy { val sortedParams = failedParams.entries.sortedBy { it.key } val maxParamNameLength = sortedParams.maxOf { it.key.length } val paramsString = sortedParams.joinToString(LINE_SEPARATOR) { "${adaptParamName(it.key, maxParamNameLength)}- Reasons -> ${it.value}" } "Failed validation of received object.\n" + "\tObject -> $rawObject\n" + "\tParams -> $paramsString" } private fun adaptParamName(paramName: String, maxLength: Int): String { return if (paramName.length == maxLength) { "$paramName " } else { "$paramName ${"-".repeat(maxLength - paramName.length)}" } } }
0
Kotlin
0
0
fb268af8146383dfa4257fac78e573b025c81ef0
1,118
validate-mapper
Apache License 2.0
sample/src/main/java/com/pineapplepie/sample/xml/adapter/SampleViewHolder.kt
PineapplePie
520,413,052
false
null
package com.pineapplepie.sample.xml.adapter import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding import com.pineapplepie.sample.SampleModel import com.pineapplepie.sample.TitleModel import com.pineapplepie.sample.databinding.ItemSampleBinding import com.pineapplepie.sample.databinding.ItemTitleBinding open class BaseViewHolder<T : ViewBinding>(binding: T) : RecyclerView.ViewHolder(binding.root) { } class SampleViewHolder(private val binding: ItemSampleBinding) : BaseViewHolder<ItemSampleBinding>(binding) { fun bind(model: SampleModel) = with(binding) { cardView.setCardBackgroundColor(ContextCompat.getColor(cardView.context, model.colorRes)) } } class TitleViewHolder(private val binding: ItemTitleBinding) : BaseViewHolder<ItemTitleBinding>(binding) { fun bind(model: TitleModel) = with(binding) { headerText.text = root.context.getString(model.text) } }
0
Kotlin
0
9
462615dc92a732f4d97c679129b75d7ae9c55eef
981
FadingToolbar
Apache License 2.0
work/work-runtime/src/androidTest/java/androidx/work/StopReasonTest.kt
androidx
256,589,781
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work import android.app.job.JobParameters.STOP_REASON_CANCELLED_BY_APP import android.app.job.JobParameters.STOP_REASON_CONSTRAINT_CHARGING import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SdkSuppress import androidx.test.filters.SmallTest import androidx.work.impl.WorkManagerImpl import androidx.work.impl.constraints.trackers.Trackers import androidx.work.impl.testutils.TestConstraintTracker import androidx.work.impl.testutils.TrackingWorkerFactory import androidx.work.testutils.GreedyScheduler import androidx.work.testutils.TestEnv import androidx.work.testutils.WorkManager import androidx.work.worker.InfiniteTestWorker import com.google.common.truth.Truth.assertThat import java.util.concurrent.Executors import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @SmallTest @SdkSuppress(minSdkVersion = 31) class StopReasonTest { val workerFactory = TrackingWorkerFactory() val configuration = Configuration.Builder().setWorkerFactory(workerFactory) .setTaskExecutor(Executors.newSingleThreadExecutor()).build() val env = TestEnv(configuration) val fakeChargingTracker = TestConstraintTracker(false, env.context, env.taskExecutor) val trackers = Trackers( context = env.context, taskExecutor = env.taskExecutor, batteryChargingTracker = fakeChargingTracker ) val workManager = WorkManager(env, listOf(GreedyScheduler(env, trackers)), trackers) init { WorkManagerImpl.setDelegate(workManager) } @Test fun testStopReasonPropagated() = runBlocking { fakeChargingTracker.constraintState = true val request = OneTimeWorkRequest.Builder(InfiniteTestWorker::class.java) .setConstraints(Constraints(requiresCharging = true)) .build() workManager.enqueue(request).await() val worker = workerFactory.await(request.id) fakeChargingTracker.constraintState = false workManager.getWorkInfoByIdFlow(request.id).first { it.state == WorkInfo.State.ENQUEUED } assertThat(worker.isStopped).isTrue() assertThat(worker.stopReason).isEqualTo(STOP_REASON_CONSTRAINT_CHARGING) } @Test fun testGetStopReasonThrowsWhileRunning() = runBlocking { val request = OneTimeWorkRequest.Builder(InfiniteTestWorker::class.java).build() workManager.enqueue(request) val worker = workerFactory.await(request.id) workManager.getWorkInfoByIdFlow(request.id).first { it.state == WorkInfo.State.RUNNING } try { worker.stopReason throw AssertionError() } catch (e: IllegalStateException) { // it is expected to happen } } @Test fun testStopReasonWhenCancelled() = runBlocking { val request = OneTimeWorkRequest.Builder(InfiniteTestWorker::class.java).build() workManager.enqueue(request) val worker = workerFactory.await(request.id) workManager.getWorkInfoByIdFlow(request.id).first { it.state == WorkInfo.State.RUNNING } workManager.cancelWorkById(request.id) workManager.getWorkInfoByIdFlow(request.id).first { it.state == WorkInfo.State.CANCELLED } assertThat(worker.isStopped).isTrue() assertThat(worker.stopReason).isEqualTo(STOP_REASON_CANCELLED_BY_APP) } }
23
Kotlin
782
4,525
006680832f0d7fc8d31a05ab20ab217cc29101d1
4,062
androidx
Apache License 2.0
reaktive/src/commonMain/kotlin/com/badoo/reaktive/plugin/ReaktivePlugins.kt
badoo
174,194,386
false
{"Kotlin": 1507792, "Swift": 2268, "HTML": 956}
@file:JvmName("ReaktivePluginsJvm") package com.badoo.reaktive.plugin import com.badoo.reaktive.completable.Completable import com.badoo.reaktive.maybe.Maybe import com.badoo.reaktive.observable.Observable import com.badoo.reaktive.single.Single import kotlin.jvm.JvmName internal var plugins: ArrayList<ReaktivePlugin>? = null fun registerReaktivePlugin(plugin: ReaktivePlugin) { var list = plugins if (list == null) { list = ArrayList() plugins = list } list.add(plugin) } fun unregisterReaktivePlugin(plugin: ReaktivePlugin) { plugins?.also { it.remove(plugin) if (it.isEmpty()) { plugins = null } } } fun <T> onAssembleObservable(observable: Observable<T>): Observable<T> = plugins ?.fold(observable) { source, plugin -> plugin.onAssembleObservable(source) } ?: observable fun <T> onAssembleSingle(single: Single<T>): Single<T> = plugins ?.fold(single) { src, plugin -> plugin.onAssembleSingle(src) } ?: single fun <T> onAssembleMaybe(maybe: Maybe<T>): Maybe<T> = plugins ?.fold(maybe) { src, plugin -> plugin.onAssembleMaybe(src) } ?: maybe fun onAssembleCompletable(completable: Completable): Completable = plugins ?.fold(completable) { src, plugin -> plugin.onAssembleCompletable(src) } ?: completable
2
Kotlin
57
1,171
26788ab67ef85e2e3971e5bc79cce4ed9e3b5636
1,374
Reaktive
Apache License 2.0
src/main/kotlin/io/lsdconsulting/lsd/distributed/http/repository/InterceptedDocumentHttpRepository.kt
lsd-consulting
483,584,777
false
null
package io.lsdconsulting.lsd.distributed.http.repository import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import io.lsdconsulting.lsd.distributed.access.model.InterceptedInteraction import io.lsdconsulting.lsd.distributed.access.repository.InterceptedDocumentRepository import io.lsdconsulting.lsd.distributed.http.config.log import org.apache.http.HttpResponse import org.apache.http.HttpStatus.SC_OK import org.apache.http.client.fluent.Request import org.apache.http.entity.ContentType.APPLICATION_JSON import java.io.BufferedReader import java.net.SocketTimeoutException class InterceptedDocumentHttpRepository( connectionString: String, private val connectionTimeout: Int, private val objectMapper: ObjectMapper ) : InterceptedDocumentRepository { private val uri = "$connectionString/lsds" override fun save(interceptedInteraction: InterceptedInteraction) { val response: HttpResponse try { response = Request.Post(uri) .connectTimeout(connectionTimeout) .socketTimeout(connectionTimeout) .bodyString(objectMapper.writeValueAsString(interceptedInteraction), APPLICATION_JSON) .execute() .returnResponse() } catch (e: SocketTimeoutException) { log().warn("Connection to $uri timed out. Dropping interceptedInteraction: $interceptedInteraction") return } val statusCode = response.statusLine.statusCode if (statusCode != SC_OK) { log().warn("Unable to call $uri - received: $statusCode. Lost interceptedInteraction: $interceptedInteraction") } } override fun findByTraceIds(vararg traceId: String): List<InterceptedInteraction> { val response: HttpResponse try { response = Request.Get(uri + "?traceIds=" + traceId.joinToString(separator = "&traceIds=")) .connectTimeout(connectionTimeout) .socketTimeout(connectionTimeout) .execute() .returnResponse() } catch (e: SocketTimeoutException) { log().warn("Connection to $uri timed out.") throw e } val statusCode = response.statusLine.statusCode if (statusCode != SC_OK) { log().warn("Unable to call $uri - received: $statusCode.") } val use = response.entity.content.bufferedReader().use(BufferedReader::readText) return objectMapper.readValue(use, object: TypeReference<List<InterceptedInteraction>>(){}) } override fun isActive() = true }
0
Kotlin
0
0
64e6ff38073300d450d47b7458b8bd671ef0caf9
2,664
lsd-distributed-http-connector
Apache License 2.0
app/src/main/java/jp/cordea/tw/ui/login/LoginActivity.kt
CORDEA
223,513,866
false
null
package jp.cordea.tw.ui.login import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import jp.cordea.tw.* import jp.cordea.tw.ui.main.MainActivity import kotlinx.android.synthetic.main.activity_login.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.MainScope import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch import javax.inject.Inject @ExperimentalCoroutinesApi class LoginActivity : AppCompatActivity(), ViewModelInjectable<LoginViewModel>, CoroutineScope by MainScope() { @Inject override lateinit var viewModelFactory: ViewModelFactory<LoginViewModel> private val viewModel by lazy { viewModel() } override fun onCreate(savedInstanceState: Bundle?) { (application as App) .appComponent .loginActivitySubcomponentFactory() .create() .inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) setSupportActionBar(toolbar) val intent = Intent(this, MainActivity::class.java) launch { viewModel.onLoggedIn .consumeEach { startActivity(intent) } } loginButton.callback = viewModel.loginCallback } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) loginButton.onActivityResult(requestCode, resultCode, data) } }
0
Kotlin
0
0
5a928d0de6e095d629ca51f49617f9cde27923f6
1,576
tw
Apache License 2.0
app/src/test/java/fr/jorisfavier/youshallnotpass/ItemEditViewModelTest.kt
jorisfavier
259,359,448
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 115, "XML": 65, "Java": 1}
package fr.jorisfavier.youshallnotpass import android.content.ClipboardManager import androidx.arch.core.executor.testing.InstantTaskExecutorRule import fr.jorisfavier.youshallnotpass.manager.CryptoManager import fr.jorisfavier.youshallnotpass.manager.model.EncryptedData import fr.jorisfavier.youshallnotpass.model.Item import fr.jorisfavier.youshallnotpass.model.exception.YsnpException import fr.jorisfavier.youshallnotpass.repository.ItemRepository import fr.jorisfavier.youshallnotpass.ui.item.ItemEditViewModel import fr.jorisfavier.youshallnotpass.utils.PasswordUtil import fr.jorisfavier.youshallnotpass.utils.getOrAwaitValue import io.mockk.* import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertTrue import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Rule import org.junit.Test class ItemEditViewModelTest { @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @get:Rule var mainCoroutineRule = MainCoroutineRule() private val fakeItem = Item( id = 1, title = "Test title", login = "test login", password = ByteArray(0), initializationVector = ByteArray(0) ) private val fakeDecryptedPassword = "<PASSWORD>" private val fakeEncryptedData get() = EncryptedData(fakeItem.password, fakeItem.initializationVector) private val newFakeTitle = "new fake title" private val cryptoManager: CryptoManager = mockk() private val itemRepo: ItemRepository = mockk() private val clipManager: ClipboardManager = mockk() private val viewModel = ItemEditViewModel( cryptoManager = cryptoManager, itemRepository = itemRepo, clipboardManager = clipManager ) @Test fun `on initData ItemEditViewModel should have numbers, symbol, uppercase, a password default size and 'create' button text`() { //given //when viewModel.initData(0) //then assertEquals(true, viewModel.hasNumber.getOrAwaitValue()) assertEquals(true, viewModel.hasSymbol.getOrAwaitValue()) assertEquals(true, viewModel.hasUppercase.getOrAwaitValue()) assertEquals(R.string.item_create, viewModel.createOrUpdateText.getOrAwaitValue()) assertEquals( PasswordUtil.MINIMUM_SECURE_SIZE, viewModel.passwordLengthValue.getOrAwaitValue() ) } @Test fun `on initData with a valid item id ItemEditViewModel should emit an 'update' button text, an item login and an item password`() { //given coEvery { itemRepo.getItemById(1) } returns fakeItem every { cryptoManager.decryptData( fakeItem.password, fakeItem.initializationVector ) } returns fakeDecryptedPassword val viewModel = ItemEditViewModel( cryptoManager = cryptoManager, itemRepository = itemRepo, clipboardManager = clipManager ) //when viewModel.initData(1) //then assertEquals(R.string.item_update, viewModel.createOrUpdateText.getOrAwaitValue()) assertEquals(fakeItem.login, viewModel.login.getOrAwaitValue()) assertEquals(fakeDecryptedPassword, viewModel.password.getOrAwaitValue()) } @Test fun `on initData should init as a normal item creation when an exception is raised by the itemRepository`() = runBlocking { //given coEvery { itemRepo.getItemById(1) } throws Exception() every { cryptoManager.decryptData( fakeItem.password, fakeItem.initializationVector ) } returns fakeDecryptedPassword val viewModel = ItemEditViewModel( cryptoManager = cryptoManager, itemRepository = itemRepo, clipboardManager = clipManager ) //when viewModel.initData(1) //then assertEquals(R.string.item_create, viewModel.createOrUpdateText.getOrAwaitValue()) } @Test fun `generateSecurePassword with symbol disabled should emit a password without symbols`() { //given viewModel.hasSymbol.value = false //when //force passwordLengthValue to emit values viewModel.passwordLengthValue.observeForever {} viewModel.generateSecurePassword() //then val password = viewModel.password.getOrAwaitValue() assertTrue(password.filter { PasswordUtil.SYMBOLS.contains(it) }.toList().isEmpty()) assertTrue(password.filter { PasswordUtil.UPPERCASE.contains(it) }.toList().isNotEmpty()) assertTrue(password.filter { PasswordUtil.NUMBERS.contains(it) }.toList().isNotEmpty()) assertTrue(password.length == PasswordUtil.MINIMUM_SECURE_SIZE) } @Test fun `generateSecurePassword with number disabled should emit a password without numbers`() { //given viewModel.hasNumber.value = false //when //force passwordLengthValue to emit values viewModel.passwordLengthValue.observeForever {} viewModel.generateSecurePassword() //then val password = viewModel.password.getOrAwaitValue() assertTrue(password.filter { PasswordUtil.NUMBERS.contains(it) }.toList().isEmpty()) assertTrue(password.filter { PasswordUtil.UPPERCASE.contains(it) }.toList().isNotEmpty()) assertTrue(password.filter { PasswordUtil.SYMBOLS.contains(it) }.toList().isNotEmpty()) assertTrue(password.length == PasswordUtil.MINIMUM_SECURE_SIZE) } @Test fun `generateSecurePassword with uppercase disabled should emit a password without uppercase`() { //given viewModel.hasUppercase.value = false //when //force passwordLengthValue to emit values viewModel.passwordLengthValue.observeForever {} viewModel.generateSecurePassword() //then val password = viewModel.password.getOrAwaitValue() assertTrue(password.filter { PasswordUtil.UPPERCASE.contains(it) }.toList().isEmpty()) assertTrue(password.filter { PasswordUtil.SYMBOLS.contains(it) }.toList().isNotEmpty()) assertTrue(password.filter { PasswordUtil.NUMBERS.contains(it) }.toList().isNotEmpty()) assertTrue(password.length == PasswordUtil.MINIMUM_SECURE_SIZE) } @Test fun `generateSecurePassword with passwordLength changed should emit a password with the correct size`() { //given val passwordLength = 3 viewModel.passwordLength.value = passwordLength //when //force passwordLengthValue to emit values viewModel.passwordLengthValue.observeForever {} viewModel.generateSecurePassword() //then val password = viewModel.password.getOrAwaitValue() assertTrue(password.length == (passwordLength + PasswordUtil.MINIMUM_SECURE_SIZE)) assertTrue(password.filter { PasswordUtil.UPPERCASE.contains(it) }.toList().isNotEmpty()) assertTrue(password.filter { PasswordUtil.NUMBERS.contains(it) }.toList().isNotEmpty()) assertTrue(password.filter { PasswordUtil.SYMBOLS.contains(it) }.toList().isNotEmpty()) } @Test fun `updateOrCreateItem should return a success when password and name are provided`() = runBlocking { //given every { cryptoManager.encryptData(fakeDecryptedPassword) } returns fakeEncryptedData coEvery { itemRepo.searchItem(fakeItem.title) } returns listOf() coEvery { itemRepo.updateOrCreateItem(any()) } just runs every { clipManager.setPrimaryClip(any()) } just runs //when viewModel.initData(0) viewModel.password.value = <PASSWORD> viewModel.name.value = fakeItem.title val result = viewModel.updateOrCreateItem().first() //then assertTrue(result.isSuccess) verify { clipManager.setPrimaryClip(any()) } assertEquals(R.string.item_creation_success, result.getOrNull()) } @Test fun `updateOrCreateItem should return an error when password and name are not provided`() = runBlocking { //given every { cryptoManager.encryptData(fakeDecryptedPassword) } returns fakeEncryptedData coEvery { itemRepo.searchItem(fakeItem.title) } returns listOf() coEvery { itemRepo.updateOrCreateItem(any()) } just runs //when viewModel.initData(0) val result = viewModel.updateOrCreateItem().first() //then assertTrue(result.isFailure) assertEquals( R.string.item_name_or_password_missing, (result.exceptionOrNull() as? YsnpException)?.messageResId ) } @Test fun `updateOrCreateItem should return an error when trying to add an item with a same name`() = runBlocking { //given every { cryptoManager.encryptData(fakeDecryptedPassword) } returns fakeEncryptedData coEvery { itemRepo.searchItem(fakeItem.title) } returns listOf(fakeItem) coEvery { itemRepo.updateOrCreateItem(any()) } just runs //when viewModel.initData(0) viewModel.password.value = <PASSWORD> viewModel.name.value = fakeItem.title val result = viewModel.updateOrCreateItem().first() //then assertTrue(result.isFailure) assertEquals( R.string.item_already_exist, (result.exceptionOrNull() as? YsnpException)?.messageResId ) } @Test fun `updateOrCreateItem should return an error when an exception is raised`() = runBlocking { //given every { cryptoManager.encryptData(fakeDecryptedPassword) } returns fakeEncryptedData coEvery { itemRepo.searchItem(fakeItem.title) } returns listOf() coEvery { itemRepo.updateOrCreateItem(any()) } throws Exception() //when viewModel.initData(0) viewModel.password.value = <PASSWORD> viewModel.name.value = fakeItem.title val result = viewModel.updateOrCreateItem().first() //then assertTrue(result.isFailure) assertEquals( R.string.error_occurred, (result.exceptionOrNull() as? YsnpException)?.messageResId ) } @Test fun `updateOrCreateItem should return a success when updating an Item`() = runBlocking { //given val slot = slot<Item>() coEvery { itemRepo.getItemById(1) } returns fakeItem every { cryptoManager.encryptData(fakeDecryptedPassword) } returns fakeEncryptedData coEvery { itemRepo.updateOrCreateItem(capture(slot)) } just runs every { cryptoManager.decryptData( fakeItem.password, fakeItem.initializationVector ) } returns fakeDecryptedPassword //when viewModel.initData(1) viewModel.name.value = newFakeTitle val result = viewModel.updateOrCreateItem().first() //then assertTrue(result.isSuccess) assertEquals(R.string.item_update_success, result.getOrNull()) assertEquals(newFakeTitle.capitalize(), slot.captured.title) } }
0
Kotlin
0
0
a583cd9c3d44a234969c088b28b7b4eae37feaff
11,503
YouShallNotPass-android
MIT License
sample_buxiuse/src/main/java/com/picture/main/list/ListUiFragment.kt
7449
69,446,568
false
null
package com.picture.main.list import android.common.ViewStatus import android.common.loadNoMore import android.common.ui.ListFragment import android.os.Bundle import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.kotlin.x.currentActivity import com.kotlin.x.glide import com.kotlin.x.startActivity import com.picture.main.R import com.picture.main.detail.DetailUiActivity import com.picture.main.net.PictureEntity import com.xadapter.addAll import com.xadapter.getImageView import com.xadapter.setItemLayoutId import com.xadapter.setLoadMoreListener import com.xadapter.setOnBind import com.xadapter.setOnItemClickListener import com.xadapter.setRefreshListener import com.xadapter.setText class ListUiFragment : ListFragment<ListPresenter, List<PictureEntity>, PictureEntity>(R.layout.ui_fragment_list) { companion object { private const val INDEX = "INDEX" fun newInstance(position: Int): ListUiFragment { return ListUiFragment().apply { arguments = Bundle().apply { putInt(INDEX, position) } } } } private var tabPosition = 0 private val swipeRefreshLayout by lazy { requireView().findViewById<SwipeRefreshLayout>(R.id.swipeRefreshLayout) } private val recyclerView by lazy { requireView().findViewById<RecyclerView>(R.id.recyclerView) } override fun initPresenter(): ListPresenter = ListPresenterImpl(this) override fun swipeRefreshLayout(): SwipeRefreshLayout = swipeRefreshLayout override fun recyclerView(): RecyclerView = recyclerView override fun initBundle(bundle: Bundle) { tabPosition = bundle.getInt(INDEX, 0) } override fun initActivityCreated() { mAdapter .setItemLayoutId(R.layout.ui_item_list) .setLoadMoreListener { net(page, tabPosition, ViewStatus.LOAD_MORE) } .setRefreshListener { page = 1 net(page, tabPosition, ViewStatus.REFRESH) } .setOnBind { holder, _, entity -> holder.getImageView(R.id.image).glide(entity.url) holder.setText(R.id.text, entity.title) } .setOnItemClickListener { _, _, entity -> currentActivity().startActivity(DetailUiActivity::class.java, Bundle().apply { putString(DetailUiActivity.TYPE_URL, entity.detailUrl) }) } onStatusRetry() } override fun onStatusRetry() { page += 1 net(page, tabPosition, ViewStatus.STATUS) } override fun onNetSuccess(entity: List<PictureEntity>) { if (mAdapter.dataContainer.containsAll(entity)) { mAdapter.loadNoMore() return } mAdapter.addAll(entity) onPagePlus() } private fun net(page: Int, tabPosition: Int, viewStatus: ViewStatus) { mPresenter.onNetWork(page, tabPosition, viewStatus) } }
1
Java
34
31
b3a66d61111dc344adb6ec0c065606bfcaac3164
2,978
AndroidDevelop
Apache License 2.0
app/src/main/java/com/cjmobileapps/quidditchplayersandroid/ui/QuidditchPlayersNavHost.kt
CJMobileApps
750,394,460
false
{"Kotlin": 195996}
package com.cjmobileapps.quidditchplayersandroid.ui import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NamedNavArgument import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.cjmobileapps.quidditchplayersandroid.ui.houses.HousesUi import com.cjmobileapps.quidditchplayersandroid.ui.houses.viewmodel.HousesViewModel import com.cjmobileapps.quidditchplayersandroid.ui.houses.viewmodel.HousesViewModelImpl import com.cjmobileapps.quidditchplayersandroid.ui.playerdetail.PlayerDetailUi import com.cjmobileapps.quidditchplayersandroid.ui.playerdetail.viewmodel.PlayerDetailViewModel import com.cjmobileapps.quidditchplayersandroid.ui.playerdetail.viewmodel.PlayerDetailViewModelImpl import com.cjmobileapps.quidditchplayersandroid.ui.playerslist.PlayersListUi import com.cjmobileapps.quidditchplayersandroid.ui.playerslist.viewmodel.PlayersListViewModel import com.cjmobileapps.quidditchplayersandroid.ui.playerslist.viewmodel.PlayersListViewModelImpl import kotlinx.coroutines.CoroutineScope @Composable fun NavigationGraph( navController: NavHostController, coroutineScope: CoroutineScope, snackbarHostState: SnackbarHostState, ) { NavHost(navController = navController, startDestination = NavItem.Houses.navRoute) { composable(NavItem.Houses.navRoute) { val housesViewModel: HousesViewModel = hiltViewModel<HousesViewModelImpl>() HousesUi( navController = navController, housesViewModel = housesViewModel, coroutineScope = coroutineScope, snackbarHostState = snackbarHostState, ) } composable( NavItem.PlayersList.navRoute, arguments = NavItem.PlayersList.arguments, ) { val playersListViewModel: PlayersListViewModel = hiltViewModel<PlayersListViewModelImpl>() PlayersListUi( navController = navController, playersListViewModel = playersListViewModel, coroutineScope = coroutineScope, snackbarHostState = snackbarHostState, ) } composable(NavItem.PlayerDetail.navRoute) { val playerDetailViewModel: PlayerDetailViewModel = hiltViewModel<PlayerDetailViewModelImpl>() PlayerDetailUi( navController = navController, coroutineScope = coroutineScope, playerDetailViewModel = playerDetailViewModel, snackbarHostState = snackbarHostState, ) } } } sealed class NavItem( val navRoute: String, val arguments: List<NamedNavArgument> = emptyList(), ) { data object Houses : NavItem(navRoute = "nav_houses") data object PlayersList : NavItem( navRoute = "nav_players_list/{houseName}", arguments = listOf( navArgument("houseName") { type = NavType.StringType }, ), ) { fun getNavRouteWithArguments(houseName: String): String { return "nav_players_list/$houseName" } } data object PlayerDetail : NavItem( navRoute = "nav_player_detail/{playerId}", arguments = listOf( navArgument("playerId") { type = NavType.StringType }, ), ) { fun getNavRouteWithArguments(playerId: String): String { return "nav_player_detail/$playerId" } } }
0
Kotlin
0
0
ce235c3b16e0cd9d37c98894f921db822883adb9
3,748
quidditch-players-android-2023
MIT License
PluginsAndFeatures/azure-toolkit-for-intellij/rider/src/com/microsoft/intellij/helpers/defaults/AzureDefaults.kt
JetBrains
137,064,201
true
{"Java": 6822615, "Kotlin": 2384238, "C#": 198892, "Scala": 151332, "Gherkin": 108427, "JavaScript": 98350, "HTML": 23518, "CSS": 21770, "Groovy": 21447, "Shell": 21354, "XSLT": 7141, "Dockerfile": 3518, "Batchfile": 2155}
/** * Copyright (c) 2018-2023 JetBrains s.r.o. * * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.microsoft.intellij.helpers.defaults import com.microsoft.azure.management.appservice.PricingTier import com.microsoft.azure.management.resources.fluentcore.arm.Region import com.microsoft.azure.management.sql.DatabaseEdition import com.microsoft.azure.management.sql.ServiceObjectiveName object AzureDefaults { const val SQL_DATABASE_COLLATION = "SQL_Latin1_General_CP1_CI_AS" val databaseEdition: DatabaseEdition = DatabaseEdition.BASIC val databaseComputeSize: ServiceObjectiveName = ServiceObjectiveName.BASIC val location: Region = Region.US_EAST val pricingTier: PricingTier = PricingTier.STANDARD_S1 object SupportedRegions { // Regions where app services are supported // https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/?products=app-service val AppServices = hashSetOf( // South Africa "southafricanorth", "southafricawest", // Asia "eastasia", "southeastasia", // Australia "australiacentral", "australiacentral2", "australiaeast", "australiasoutheast", // Brazil "brazilsouth", "brazilsoutheast", // Canada "canadacentral", "canadaeast", // China "chinaeast", "chinaeast2", "chinaeast3", "chinanorth", "chinanorth2", "chinanorth3", // Europe "northeurope", "westeurope", // France "francecentral", "francesouth", // Germany //"germanynorth", "germanywestcentral", // India "centralindia", "southindia", "westindia", "jioindiacentral", "jioindiawest", // Japan "japaneast", "japanwest", // Korea "koreacentral", "koreasouth", // Norway "norwayeast", "norwaywest", // Poland //"polandcentral", // Qatar "qatarcentral", // Sweden "swedencentral", "swedensouth", // Switzerland "switzerlandnorth", "switzerlandwest", // UAE "uaecentral", "uaenorth", // UK "uksouth", "ukwest", // USA "centralus", "eastus", "eastus2", "northcentralus", "southcentralus", "westcentralus", "westus", "westus2", "westus3" ) // Regions where SQL Databasde is supported // https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/?products=azure-sql-database val SqlDatabase = hashSetOf( // South Africa "southafricanorth", "southafricawest", // Asia "eastasia", "southeastasia", // Australia "australiacentral", "australiacentral2", "australiaeast", "australiasoutheast", // Brazil "brazilsouth", "brazilsoutheast", // Canada "canadacentral", "canadaeast", // China "chinaeast", "chinaeast2", "chinaeast3", "chinanorth", "chinanorth2", "chinanorth3", // Europe "northeurope", "westeurope", // France "francecentral", "francesouth", // Germany "germanynorth", "germanywestcentral", // India "centralindia", "southindia", "westindia", "jioindiacentral", "jioindiawest", // Japan "japaneast", "japanwest", // Korea "koreacentral", "koreasouth", // Norway "norwayeast", "norwaywest", // Poland "polandcentral", // Qatar "qatarcentral", // Sweden "swedencentral", "swedensouth", // Switzerland "switzerlandnorth", "switzerlandwest", // UAE "uaecentral", "uaenorth", // UK "uksouth", "ukwest", // USA "centralus", "eastus", "eastus2", "northcentralus", "southcentralus", "westcentralus", "westus", "westus2", "westus3" ) } }
70
Java
10
41
5ffb7e600c2bdac8762461921c6255106b376a5d
6,745
azure-tools-for-intellij
MIT License
android/app/src/main/kotlin/com/daniel7byte/speed_alert_flutter_app/MainActivity.kt
daniel7byte
350,141,026
false
{"Makefile": 54479, "Dart": 3944, "Swift": 404, "Kotlin": 144, "Objective-C": 38}
package com.daniel7byte.speed_alert_flutter_app import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Makefile
0
0
1fed90603a8c2e115de0f923892be269d62124a3
144
speed_alert_flutter_app
MIT License
stripe/src/test/java/com/stripe/android/paymentsheet/AddButtonTest.kt
Adonais0
317,126,835
true
{"Kotlin": 2519194, "Java": 63560, "Ruby": 6208, "Shell": 321}
package com.stripe.android.paymentsheet import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class AddButtonTest { private val addButton = AddButton(ApplicationProvider.getApplicationContext()) @Test fun `disabling button should update label alpha`() { addButton.isEnabled = false assertThat(addButton.viewBinding.label.alpha) .isEqualTo(0.5f) } @Test fun `onReadyState() should update label`() { addButton.onReadyState() assertThat( addButton.viewBinding.label.text.toString() ).isEqualTo( "Add" ) } @Test fun `onProcessingState() should update label`() { addButton.onProcessingState() assertThat( addButton.viewBinding.label.text.toString() ).isEqualTo( "Processing…" ) } }
0
null
0
0
39eeb7eac1c9210dac8224d2c8f7ee4b9c1ff5bd
1,044
stripe-android
MIT License
backend/src/main/kotlin/com/parkq/backend/api/park/ParkMapper.kt
Mathwus
130,278,335
false
{"TypeScript": 41582, "Kotlin": 33227, "HTML": 15129, "CSS": 6888, "JavaScript": 1482}
package com.parkq.backend.api.park import com.parkq.backend.entity.Park import org.springframework.stereotype.Component @Component class ParkMapper { fun toDTO(entity: Park) = ParkDTO( id = entity.id, image = entity.image, company = entity.company, name = entity.name, description = entity.description, location = entity.location ) fun toEntity(dto: ParkDTO) = if(dto.id.isEmpty()) Park( image = dto.image, company = dto.company, name = dto.name, description = dto.description, location = dto.location ) else Park( id = dto.id, image = dto.image, company = dto.company, name = dto.name, description = dto.description, location = dto.location ) }
0
TypeScript
0
3
3afc29d95e0a4c3152ecf27b4a095a8e01ad95b3
1,153
Parkq
MIT License
app/src/main/java/com/example/connectionsmanagement/Tools/Tools.kt
toyyx
674,488,487
false
{"Kotlin": 240299}
package com.example.connectionsmanagement.Tools import android.content.ContentResolver import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import androidx.appcompat.app.AlertDialog import com.example.connectionsmanagement.Communications.Communication import com.example.connectionsmanagement.MysqlServer.MySQLConnection import com.example.connectionsmanagement.RegisterAndLogin.User import com.example.connectionsmanagement.Relations.Relation import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import okhttp3.Callback import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import org.json.JSONArray import org.json.JSONObject import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.net.URL //通用工具类 object Tools { val baseUrl="http://172.16.17.32:8080/connection_server-1.0-SNAPSHOT" // 下载图片(根据图片在服务器的存储路径,并保存至本地缓存) fun downloadImage(context: Context, serverImagePath: String?) { try { //获取图片名 val imageFileName= serverImagePath?.let { getSpecialFromString(it,"data_image/") } val downloadUrl= "$baseUrl/data_image/$imageFileName" val localImagePath:String = context.externalCacheDir.toString()+imageFileName // 创建URL对象 val imageUrl = URL(downloadUrl) // 打开连接 val inputStream: InputStream = imageUrl.openStream() val outputStream = FileOutputStream(localImagePath) // 从输入流读取数据并写入输出流 val buffer = ByteArray(2048) var length: Int while (inputStream.read(buffer).also { length = it } != -1) { outputStream.write(buffer, 0, length) } // 关闭流 inputStream.close() outputStream.close() println("图片下载成功!") println(context.externalCacheDir.toString()) } catch (e: Exception) { e.printStackTrace() println("图片下载失败!") } } //从本地路径获取Bitmap fun getBitmapFromLocalPath(localPath :String): Bitmap { println("本地地址:"+ ConnectionsManagementApplication.context.externalCacheDir.toString()+ getSpecialFromString(localPath, "data_image/")) return BitmapFactory.decodeFile( ConnectionsManagementApplication.context.externalCacheDir.toString() + getSpecialFromString( localPath, "data_image/" ) ) } //从本地路径获取Uri fun getUriFromLocalPath(localPath :String): Uri { val imagePath = ConnectionsManagementApplication.context.externalCacheDir.toString()+ getSpecialFromString(localPath, "data_image/") return Uri.fromFile(File(imagePath)) } //从字符串中获取特定字符串的后面部分 fun getSpecialFromString(string: String,character: String):String{ return string.substring(string.indexOf(character) + character.length) } //从uri中获取File fun getFileFromUri(uri: Uri): File? { // Toast.makeText(ConnectionsManagementApplication.context, "开始转换uri", Toast.LENGTH_SHORT).show()//调试使用 val contentResolver: ContentResolver = ConnectionsManagementApplication.context.contentResolver var inputStream = contentResolver.openInputStream(uri)//输入流 var outputFile: File?=null//输出流 try { val cacheDir = ConnectionsManagementApplication.context.cacheDir outputFile = File(cacheDir, "temp_file_" + System.currentTimeMillis()) val outputStream = FileOutputStream(outputFile) inputStream.use { input -> outputStream.use { output -> val bytesCopied =input?.copyTo(output)//复制数据量 // //调试使用 // if(bytesCopied==null){ // Toast.makeText(ConnectionsManagementApplication.context, "返回的字节数为 null", Toast.LENGTH_SHORT).show() // }else{ // Toast.makeText(ConnectionsManagementApplication.context, "返回的字节数为 $bytesCopied", Toast.LENGTH_SHORT).show() // } } } } catch (e: IOException) { e.printStackTrace() } finally { inputStream?.close() } return outputFile } //更新本地人脉数据 suspend fun RefreshRelations(){ runBlocking { val job1 = async {MySQLConnection.fetchWebpageContent("SearchRelations", ConnectionsManagementApplication.NowUser.userId.toString(), "")} // 等待所有协程执行完毕,并获取结果 val jsonString: String = job1.await() println("Server Response_RefreshRelations: $jsonString") //将 JSON 字符串 jsonString 解析为 ArrayList<Relation> val listType = object : TypeToken<ArrayList<Relation>>() {}.type ConnectionsManagementApplication.NowRelations = Gson().fromJson(jsonString, listType) ConnectionsManagementApplication.NowRelations.forEach { val job2 = async {downloadImage(ConnectionsManagementApplication.context, it.image_path)} // 等待所有协程执行完毕,并获取结果 job2.await() } } } //更新本地交际数据 suspend fun RefreshCommunications(){ //将 JSON 字符串 jsonString 解析为 ArrayList<Relation> val jsonString = MySQLConnection.fetchWebpageContent( "SearchCommunications", ConnectionsManagementApplication.NowUser.userId.toString(), "" ) println("Server Response: $jsonString") val listType = object : TypeToken<ArrayList<Communication>>() {}.type ConnectionsManagementApplication.Communications = Gson().fromJson(jsonString, listType) } //更新本地用户数据 suspend fun RefreshUser(){ //将 JSON 字符串 jsonString 解析为 User val jsonString = MySQLConnection.fetchWebpageContent( "Login", ConnectionsManagementApplication.NowUser.userName!!, ConnectionsManagementApplication.NowUser.password!! ) println("Server Response: $jsonString") val jsonObject = JSONObject(jsonString) ConnectionsManagementApplication.NowUser = User( jsonObject.getString("userId").toInt(), jsonObject.getString("userName"), jsonObject.getString("password"), jsonObject.getString("name"), jsonObject.getString("gender"), jsonObject.getString("image_path"), jsonObject.getString("phone_number"), jsonObject.getString("email") ) downloadImage( ConnectionsManagementApplication.context, ConnectionsManagementApplication.NowUser.image_path) } //将Base64转化为Bitmap fun getBitmapFromBase64(image_base64: String): Bitmap { //将 base64 编码的字符串解码为字节数组 val decodedBytes = android.util.Base64.decode(image_base64, android.util.Base64.DEFAULT) //将字节数组转换为 Bitmap 对象 return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size) } //获取人脸检测的Base64结果(主要为了Base64,顺带传递人脸检测的其它数据) fun GetFaceDetectBase64(selectedImageFile: File, callback: (responseData: JSONArray?) -> Unit){ // 创建OkHttpClient实例 val client = OkHttpClient() // 构建MultipartBody,用于上传图片 val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "image", "avatar.jpg", selectedImageFile!!.asRequestBody("image/*".toMediaTypeOrNull()) ) .build() // 创建POST请求 val request = Request.Builder() .url("$baseUrl/FaceDetectServlet") .post(requestBody) .build() // 发送请求并处理响应 client.newCall(request).enqueue(object : Callback { override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) { // 处理服务器响应,根据需要更新UI或执行其他操作 val responseBody = response.body?.string()//JsonString if (responseBody != null) { // 处理服务器响应内容,这里的 responseBody 就是网页内容 // 可以在这里对网页内容进行解析、处理等操作 println("Server Response: $responseBody") // 将JSON字符串解析为JsonObject val jsonObject = JSONObject(responseBody) // 读取特定键的值 val result = jsonObject.get("result").toString() if (result == "success") { val detect_result_full_jsonObject=jsonObject.getJSONObject("detect_result") if(!detect_result_full_jsonObject.has("face_num")){ callback(null) } else if(detect_result_full_jsonObject.getInt("face_num")!=0){ callback(detect_result_full_jsonObject.getJSONArray("face_list")) }else{ callback(null) } }else{ callback(null) } } } override fun onFailure(call: okhttp3.Call, e: IOException) { callback(null) } }) } fun dpToPx(dp: Int): Float { return dp * ConnectionsManagementApplication.context.resources.displayMetrics.density } fun showUserAgreement(context:Context){ val instructions = """ 欢迎使用《脉络森林》!在使用之前,请仔细阅读并同意本用户协议及隐私政策。 1.使用规则 用户应遵守国家相关法律法规,不得利用本应用程序进行违法活动。 用户不得利用本应用程序从事侵犯他人权益的行为,包括但不限于侵犯知识产权、侵犯个人隐私等。 2.隐私政策 我们尊重并保护用户的个人隐私。在用户使用《脉络森林》时,我们可能会收集、存储和使用用户提供的个人信息,包括但不限于姓名、电话号码、电子邮件地址等。 我们收集用户个人信息的目的是为了向用户提供更好的服务体验,如记录人脉信息、进行人脸识别等。 我们承诺对用户的个人信息进行严格保密,并采取合理的安全措施保护用户的个人信息安全。 用户可以随时查看、修改、删除自己的个人信息,并有权选择是否同意提供个人信息。但是,拒绝提供个人信息可能导致无法使用部分功能或服务。 3.知识产权保护 应用程序中的所有内容(包括但不限于文字、图片、音频、视频等)的知识产权归本应用程序所有。 用户不得未经授权复制、传播、修改或者利用应用程序中的任何内容。 4.免责声明 用户在使用本应用程序时应自行承担风险,我们不对因使用本应用程序而导致的任何损失负责。 本应用程序可能因系统维护、升级等原因而中断服务,对此我们不承担任何责任。 5.服务终止 用户违反本用户协议的规定,我们有权立即终止对用户的服务。 6.争议解决 本用户协议及隐私政策适用于中华人民共和国的法律。因本用户协议及隐私政策引起的任何争议,双方应协商解决。协商不成的,应提交至有管辖权的法院解决。 用户在使用本应用程序时即视为已阅读、理解并同意本用户协议及隐私政策的所有内容。如果用户不同意本用户协议及隐私政策的任何内容,应立即停止使用本应用程序。 """.trimIndent() // 创建一个对话框,并将滚动视图设置为其内容 val builder = AlertDialog.Builder(context) builder.setTitle("用户协议及隐私政策") builder.setMessage(instructions) builder.setPositiveButton("已阅读") { dialog, which -> dialog.dismiss() } // 显示对话框 val dialog = builder.create() dialog.show() } }
0
Kotlin
1
0
dadff6498e75a714245296fd26fdf269cdbd9213
11,529
ConnectionsManagement
Apache License 2.0
app/src/main/java/dev/rdnt/m8face/data/watchface/WatchFaceColorPalette.kt
rdnt
585,996,555
false
{"Kotlin": 136605}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.rdnt.m8face.data.watchface import android.content.Context import androidx.annotation.DrawableRes import androidx.wear.watchface.complications.rendering.ComplicationDrawable /** * Color resources and drawable id needed to render the watch face. Translated from * [ColorStyle] constant ids to actual resources with context at run time. * * This is only needed when the watch face is active. * * Note: We do not use the context to generate a [ComplicationDrawable] from the * complicationStyleDrawableId (representing the style), because a new, separate * [ComplicationDrawable] is needed for each complication. Because the renderer will loop through * all the complications and there can be more than one, this also allows the renderer to create * as many [ComplicationDrawable]s as needed. */ data class WatchFaceColorPalette( val primaryColor: Int, val secondaryColor: Int, val tertiaryColor: Int, ) { companion object { /** * Converts [ColorStyle] to [WatchFaceColorPalette]. */ fun convertToWatchFaceColorPalette( context: Context, colorStyle: ColorStyle, ): WatchFaceColorPalette { return WatchFaceColorPalette( primaryColor = context.getColor(colorStyle.primaryColorId), secondaryColor = context.getColor(colorStyle.secondaryColorId), tertiaryColor = context.getColor(colorStyle.tertiaryColorId), ) } } }
8
Kotlin
1
9
fc5629da88acb66a90af7224f2c5dfc93f22d665
2,034
m8
MIT License
gradm-runtime/src/main/kotlin/me/omico/gradm/GradmConfiguration.kt
Omico
464,079,553
false
{"Kotlin": 175015}
/* * Copyright 2022-2023 Omico * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.omico.gradm object GradmConfiguration { var debug: Boolean = false var offline: Boolean = false var requireRefresh: Boolean = false } object GradmFormatConfiguration { var enabled: Boolean = true var indent: Int = 2 } object GradmExperimentalConfiguration { var kotlinMultiplatformSupport: Boolean = false var kotlinMultiplatformIgnoredExtensions: List<String> = emptyList() }
3
Kotlin
2
36
ecccebe79610be8e66a5f9944dff9e3dc8c12368
1,014
Gradm
Apache License 2.0
j2k/tests/testData/ast/function/method/main.kt
chirino
3,596,099
true
null
class object { public fun main(args : Array<String?>?) : Unit { } }
0
Java
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
67
kotlin
Apache License 2.0
idl/idl-parser/src/org/jetbrains/dukat/idlParser/visitors/ArgumentVisitor.kt
Kotlin
159,510,660
false
{"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
package org.jetbrains.dukat.idlParser.visitors import org.antlr.webidl.WebIDLBaseVisitor import org.antlr.webidl.WebIDLParser import org.jetbrains.dukat.idlDeclarations.IDLArgumentDeclaration import org.jetbrains.dukat.idlDeclarations.IDLSingleTypeDeclaration import org.jetbrains.dukat.idlDeclarations.IDLTypeDeclaration import org.jetbrains.dukat.idlParser.getFirstValueOrNull internal class ArgumentVisitor: WebIDLBaseVisitor<IDLArgumentDeclaration>() { private var name: String = "" private var type: IDLTypeDeclaration = IDLSingleTypeDeclaration("", null, false) private var optional: Boolean = false private var variadic: Boolean = false private var defaultValue: String? = null override fun defaultResult() = IDLArgumentDeclaration(name, type, defaultValue, optional, variadic) override fun visitArgumentRest(ctx: WebIDLParser.ArgumentRestContext): IDLArgumentDeclaration { if (ctx.getFirstValueOrNull() == "optional") { optional = true } visitChildren(ctx) return defaultResult() } override fun visitType(ctx: WebIDLParser.TypeContext): IDLArgumentDeclaration { type = TypeVisitor().visit(ctx) return defaultResult() } override fun visitArgumentName(ctx: WebIDLParser.ArgumentNameContext): IDLArgumentDeclaration { name = ctx.text return defaultResult() } override fun visitDefaultValue(ctx: WebIDLParser.DefaultValueContext): IDLArgumentDeclaration { defaultValue = ctx.text return defaultResult() } override fun visitEllipsis(ctx: WebIDLParser.EllipsisContext): IDLArgumentDeclaration { if (ctx.text == "...") { variadic = true } return defaultResult() } }
244
Kotlin
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
1,767
dukat
Apache License 2.0
data/src/main/java/com/example/data/mappers/DeveloperMapper.kt
IlyaBorisovDly
447,408,801
false
{"Kotlin": 81181}
package com.example.data.mappers import com.example.data.entities.DeveloperResponse import com.example.domain.entities.Developer fun DeveloperResponse.toDomain(): Developer { return Developer(id = id, name = name, image = image_background) } fun List<DeveloperResponse>.toDomain(): List<Developer> { val developers = mutableListOf<Developer>() forEach { developerResponse -> developers.add(developerResponse.toDomain()) } return developers }
0
Kotlin
0
0
1e08c0d35e9779d67e1b046892a99532a4a936be
474
GamePicker
MIT License
src/main/kotlin/kotcity/ui/LaunchScreen.kt
kotcity
123,993,966
false
null
package kotcity.ui import com.natpryce.konfig.ConfigurationProperties import javafx.application.Application import javafx.application.Platform import javafx.scene.control.Alert import javafx.scene.control.ButtonBar import javafx.scene.control.ButtonType import javafx.scene.control.Label import javafx.scene.layout.VBox import javafx.stage.Stage import javafx.util.Duration import kotcity.util.Game import tornadofx.App import tornadofx.View import tornadofx.runLater val config = ConfigurationProperties.fromResource("config/defaults.properties") var GAME_TITLE = "${config[Game.Name]} ${config[Game.Version]}" class LaunchScreen : View() { override val root: VBox by fxml("/LaunchScreen.fxml") private val titleLabel: Label by fxid() init { title = GAME_TITLE titleLabel.text = GAME_TITLE currentStage?.toFront() } override fun onDock() { super.onDock() currentWindow?.sizeToScene() currentWindow?.centerOnScreen() } fun newCityPressed() { replaceWith<MapGeneratorScreen>() } fun loadCityPressed() { val launchScreen = this runLater { CityLoader.loadCity(launchScreen) } } fun quitPressed() { System.exit(0) } } class LaunchScreenApp : App(LaunchScreen::class, KotcityStyles::class) { override fun start(stage: Stage) { stage.isResizable = true stage.toFront() stage.isAlwaysOnTop = true runLater(Duration(5000.0)) { stage.isAlwaysOnTop = false } super.start(stage) stage.setOnCloseRequest { Alert(Alert.AlertType.CONFIRMATION).apply { title = "Quitting KotCity" headerText = "Are you ready to leave?" contentText = "Please confirm..." val buttonTypeOne = ButtonType("Yes, please quit.") val buttonTypeTwo = ButtonType("No, I want to keep playing.") val buttonTypeCancel = ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE) buttonTypes.setAll(buttonTypeOne, buttonTypeTwo, buttonTypeCancel) val result = showAndWait() when (result.get()) { buttonTypeOne -> { Platform.exit() System.exit(0) } else -> { // don't do anything ... } } } it.consume() } } } fun main(args: Array<String>) { Application.launch(LaunchScreenApp::class.java, *args) }
0
Kotlin
23
480
0ee1cbf4ad345c956f4f2bcfc65bb0b2b423eb3b
2,648
kotcity
Apache License 2.0
MomoPlantsUser/app/src/main/java/com/johndev/momoplants/di/MomoPlantsModule.kt
Johnmorales26
614,629,687
false
null
package com.johndev.momoplants.di import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import androidx.room.Room import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.johndev.momoplants.common.dataAccess.MomoPlantsDataSource import com.johndev.momoplants.common.dataAccess.MomoPlantsDataSourceRoom import com.johndev.momoplants.common.dataAccess.PlantDao import com.johndev.momoplants.common.utils.Constants.NAME_DATABASE import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module abstract class DataSourceModule { @Singleton @Binds abstract fun bindDataSource(impl: MomoPlantsDataSourceRoom): MomoPlantsDataSource } @InstallIn(SingletonComponent::class) @Module object FirebaseModule { @Singleton @Provides fun provideFirestore() = Firebase.firestore } @InstallIn(SingletonComponent::class) @Module object RoomModule { @Provides fun provideDao(database: MomoPlantsDatabase): PlantDao = database.plantDao() @Singleton @Provides fun provideDatabaseRoom(@ApplicationContext context: Context): MomoPlantsDatabase = Room.databaseBuilder(context, MomoPlantsDatabase::class.java, NAME_DATABASE).build() } @Module @InstallIn(SingletonComponent::class) object PreferenceModule { @Provides @Singleton fun provideSharedPreference(@ApplicationContext context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) }
0
Kotlin
0
0
737fed93f4ab43321b5776b9f20ea84eb76eaee3
1,750
Momo_Plants
W3C Software Notice and License (2002-12-31)
app/src/main/java/com/hilmihanif/kerawanangempadantsunami/ui/screens/kerawanan/DetailInfoScreen.kt
HanifHilmi
667,231,018
false
null
package com.hilmihanif.kerawanangempadantsunami.ui.screens.kerawanan import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column 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.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.hilmihanif.kerawanangempadantsunami.ui.screens.beranda.CustomUrlLinkText import com.hilmihanif.kerawanangempadantsunami.ui.theme.KerawananGempaDanTsunamiTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailInfoScreen( koordinat:String, krbGempa:Map<String,Any?>, krbGM:Map<String,Any?>, krbTsunami:Map<String,Any?>, visiblity:Boolean, onBackIconPressed:()->Unit ) { AnimatedVisibility(visible = visiblity) { BackHandler(visiblity) { onBackIconPressed() } Scaffold( topBar = { TopAppBar( title = { Text(text = "Informasi Lengkap") }, modifier = Modifier.background(MaterialTheme.colorScheme.primary), navigationIcon = { IconButton(onClick = { onBackIconPressed() }) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "back button") } }) } ) { Column( modifier = Modifier .padding(it) .padding(bottom = it.calculateBottomPadding()) .fillMaxSize() .padding(16.dp), //contentAlignment = Alignment.TopStart verticalArrangement = Arrangement.SpaceBetween ) { Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { Text( "Infomasi Kerawanan pada koordinat", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold ) Text( text = koordinat, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.padding(8.dp)) Text( text = "Kerawanan Gempa", style = MaterialTheme.typography.labelLarge ) Divider(thickness = 2.dp, modifier = Modifier.fillMaxWidth()) Text( text = "Tingkat Kerawanan:", ) Text( text = if (krbGempa.containsKey("KELAS")) krbGempa["KELAS"].toString() else "tidak tersedia", ) Text( text = if (krbGempa.containsKey("NAMOBJ")) krbGempa["NAMOBJ"].toString() else "", ) //Divider(thickness = 2.dp, modifier = Modifier.fillMaxWidth()) Spacer(modifier = Modifier.padding(8.dp)) Text( text = "Kerawanan Gerakan Tanah", style = MaterialTheme.typography.labelLarge ) Divider(thickness = 2.dp, modifier = Modifier.fillMaxWidth()) Text( text = "Tingkat Kerawanan:", ) Text( text = if (krbGM.containsKey("REMARK")) krbGM["REMARK"].toString() else "tidak tersedia", ) Text( text = if (krbGM.containsKey("NAMOBJ")) krbGM["NAMOBJ"].toString() else "", ) Text( text = if (krbGM.containsKey("PROVINSI")) krbGM["PROVINSI"].toString() else "", ) Spacer(modifier = Modifier.padding(8.dp)) Text( text = "Kerawanan Tsunami", style = MaterialTheme.typography.labelLarge ) Divider(thickness = 2.dp, modifier = Modifier.fillMaxWidth()) Text( text = "Tingkat Kerawanan:", ) Text( text = if (krbTsunami.containsKey("UNSUR")) krbTsunami["UNSUR"].toString() else "tidak tersedia", ) Text( text = if (krbTsunami.containsKey("KETERANGAN")) krbTsunami["KETERANGAN"].toString() else "", ) Text( text = if (krbTsunami.containsKey("WILAYAH")) krbTsunami["WILAYAH"].toString() else "", ) } CustomUrlLinkText( modifier = Modifier,//.align(Alignment.BottomEnd), str = "Sumber data KRB:", clickableLink = "vsi.esdm.go.id/portalmbg", url = "https://vsi.esdm.go.id/portalmbg/" ) } } } } @Preview @Composable fun DetailInfoScreenPrev() { KerawananGempaDanTsunamiTheme { Surface { DetailInfoScreen( koordinat = "lat :0.0, long:0.0, Provinsi:0.0", mapOf(), mapOf(), mapOf(), visiblity = true, onBackIconPressed = {} ) } } }
0
Kotlin
0
0
b6496d1681c9e008013ad0fa9f07b0313cfab7de
6,695
DiseminasiKerawananGempaAndroid
Apache License 2.0
app/src/main/java/zlc/season/yaksaproject/LinearExampleActivity.kt
Cmahjong
136,287,233
true
{"Kotlin": 21658, "Java": 377}
package zlc.season.yaksaproject import android.view.View import kotlinx.android.synthetic.main.activity_example.* import kotlinx.android.synthetic.main.header_item.view.* import kotlinx.android.synthetic.main.list_item.view.* import zlc.season.yaksa.YaksaItem import zlc.season.yaksa.linear class LinearExampleActivity : ExampleActivity() { override fun onChange(data: List<ExampleViewModel.ExampleData>?) { super.onChange(data) data?.let { rv_list.linear { item { HeaderItem("This is a Header") } itemDsl(index = 0) { xml(R.layout.header_item) render { it.tv_header.text = "This is a dsl Header" it.setOnClickListener { toast("DSL Header Clicked") } } } data.forEach { each -> itemDsl { xml(R.layout.list_item) render { it.textView.text = each.title } renderX { position, it -> it.setOnClickListener { toast("Clicked $position") } } } } item { ListItem("This is item too!") } } } } private class HeaderItem(val title: String) : YaksaItem { override fun render(position: Int, view: View) { view.tv_header.text = title view.setOnClickListener { } } override fun xml(): Int { return R.layout.header_item } } private class ListItem(val str: String) : YaksaItem { override fun render(position: Int, view: View) { view.textView.text = str view.setOnClickListener { } } override fun xml(): Int { return R.layout.list_item } } }
0
Kotlin
0
0
aec58d6919d2e2a1c80e791c9c19aa1c39d7dc2a
2,032
Yaksa
Apache License 2.0
src/main/kotlin/nieldw/socially/web/rest/InteractionResources.kt
nieldw
147,417,454
false
null
package nieldw.socially.web.rest import nieldw.socially.controllers.InteractionController import nieldw.socially.domain.ContactId import org.springframework.context.annotation.Profile import org.springframework.http.MediaType import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController import java.util.* @Profile("rest") @RestController internal class InteractionResources(private val interactionController: InteractionController) { @PostMapping("/contact/{id}/interaction/telephone", consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE]) fun addTelephoneInteraction(@PathVariable id: UUID, @RequestBody dto: TelephoneContactDTO) = interactionController.addInteraction(ContactId(id), dto.getTelephoneContact()) @PostMapping("/contact/{id}/interaction/email", consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE]) fun addEmailInteraction(@PathVariable id: UUID, @RequestBody dto: EmailContactDTO) = interactionController.addInteraction(ContactId(id), dto.getEmailContact()) @PostMapping("/contact/{id}/interaction/facebook", consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE]) fun addFacebookInteraction(@PathVariable id: UUID, @RequestBody dto: FacebookContactDTO) = interactionController.addInteraction(ContactId(id), dto.getFacebookContact()) }
0
Kotlin
2
9
e3bf090c836d76766a13fab34c6105c0116fbf54
1,488
ContactsAxonDemo
MIT License
app/src/main/java/ua/glebm/smartwaste/ui/screen/camera/CameraEvent.kt
glebushkaa
718,610,042
false
{"Kotlin": 241649}
package ua.glebm.smartwaste.ui.screen.camera import android.net.Uri /** * Created by gle.bushkaa email(<EMAIL>) on 11/15/2023 */ sealed class CameraEvent { data class SendImageUri( val imageUri: Uri? = null, ) : CameraEvent() }
0
Kotlin
0
1
be94eb8f216d5bfae8259611145511661f78ea4e
250
smart-waste-android
MIT License
app/src/main/kotlin/com/mitch/my_unibo/ui/courses/components/virtuale/VirtualeCourses.kt
seve-andre
511,074,187
false
{"Kotlin": 320965}
package com.mitch.my_unibo.ui.courses.components.virtuale import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import com.mitch.my_unibo.R import com.mitch.my_unibo.ui.custom.text.Title import com.mitch.my_unibo.ui.navigation.Screen @Composable fun VirtualeCourses( viewModel: VirtualeViewModel = hiltViewModel(), navController: NavHostController ) { Column( verticalArrangement = Arrangement.spacedBy(20.dp) ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Title(text = stringResource(R.string.my_courses)) SearchCourseButton { navController.navigate(Screen.SearchCourse.route) } } val courses = viewModel.findStudentCourses() if (courses.isEmpty()) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { Text(text = "Non sei iscritto a nessuno corso") } } else { Column( verticalArrangement = Arrangement.spacedBy(30.dp) ) { courses.forEach { VirtualeCourseCard( course = it, navController = navController ) } } } } } @Composable private fun SearchCourseButton( onClick: () -> Unit ) { TextButton( onClick = onClick, colors = ButtonDefaults.textButtonColors( contentColor = Color(0xFF2F7FEA) ) ) { Text(text = stringResource(R.string.add_course)) } } @Preview @Composable fun VirtualeCoursesPreview() { // VirtualeCourses() }
0
Kotlin
0
2
d10efb2a1676ecbf78643f88726b586a3d8c989d
2,527
myUniBo
Apache License 2.0
src/test/kotlin/com/hogwai/bananesexportkata/BananesExportKataApplicationTests.kt
Hogwai
651,528,744
false
null
package com.hogwai.bananesexportkata import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class BananesExportKataApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
faf6b7147030d4c1aade0a370bda367353696b29
227
bananes-export-kata
MIT License
pumping/src/main/kotlin/com/dpm/pumping/auth/oauth2/vo/OAuth2ApplePublicKeys.kt
depromeet
627,802,875
false
null
package com.dpm.pumping.auth.oauth2.vo data class OAuth2ApplePublicKeys( val keys: List<OAuth2ApplePublicKey> ) { fun getMatchesKey(alg: String?, kid: String?): OAuth2ApplePublicKey { return keys.stream() .filter { key -> key.alg == alg && key.kid == kid } .findFirst() .orElseThrow { IllegalArgumentException("Apple JWT 값의 alg, kid 정보가 올바르지 않습니다.") } } }
3
Kotlin
0
2
366e951c11eafc9369aa0095337579ffb23f7ec6
414
pumping-server
Apache License 2.0
app/src/main/java/aelsi2/natkschedule/ui/components/attribute_list/AttributeList.kt
aelsi2
588,422,030
false
null
package aelsi2.natkschedule.ui.components.attribute_list import aelsi2.natkschedule.R import aelsi2.natkschedule.model.* import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState 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.res.stringResource import androidx.compose.ui.text.style.TextAlign @Composable fun AttributeList( attributes: List<ScheduleAttribute>, modifier: Modifier = Modifier, lazyListState: LazyListState = rememberLazyListState(), filters: @Composable () -> Unit = {}, onAttributeClick: (ScheduleIdentifier) -> Unit = {}, ) { Box(modifier = modifier) { LazyColumn( state = lazyListState, modifier = Modifier.matchParentSize() ) { item { filters() } items(attributes) { attribute -> AttributeListItem( mainText = when (attribute) { is Teacher -> attribute.fullName is Classroom -> attribute.fullName is Group -> attribute.name else -> "" }, supportingText = when (attribute) { is Teacher -> null is Classroom -> attribute.address is Group -> stringResource( R.string.group_info, attribute.year, attribute.programName ) else -> null }, leadingIconResource = when (attribute) { is Teacher -> R.drawable.person_outlined is Classroom -> R.drawable.door_outlined is Group -> R.drawable.people_outlined else -> R.drawable.question_mark }, onClick = { onAttributeClick(attribute.scheduleIdentifier) } ) } } if (attributes.isEmpty()) { Box(modifier = Modifier.matchParentSize()) { Text( text = stringResource(R.string.message_attribute_list_empty), style = MaterialTheme.typography.bodyMedium.copy( color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center ), modifier = Modifier.align(Alignment.Center) ) } } } }
0
Kotlin
0
1
6494abd7cd80fd0c68c1cd5dbba5a3a7a546c654
3,191
NatkSchedule
Apache License 2.0
pluginApi/src/main/java/com/su/mediabox/pluginapi/components/IMediaDetailPageDataComponent.kt
RyensX
459,571,889
false
{"Kotlin": 43532}
package com.su.mediabox.pluginapi.components import com.su.mediabox.pluginapi.data.BaseData /** * 媒体详情页面数据组件 */ interface IMediaDetailPageDataComponent : IBasePageDataComponent { /** * 获取媒体详情页数据 * * @param partUrl 页面部分url * @return Triple<封面,名称,详情页其他数据集> */ suspend fun getMediaDetailData(partUrl: String): Triple<String, String, List<BaseData>> }
0
Kotlin
8
41
4616843a940b018865e2a5fb70d4e078d61dd652
386
MediaBoxPlugin
Apache License 2.0
wire4/src/commonTest/kotlin/mqtt/wire4/control/packet/PingRequest.kt
thebehera
171,056,445
false
null
package mqtt.wire4.control.packet import mqtt.buffer.allocateNewBuffer import kotlin.test.Test import kotlin.test.assertEquals class PingRequestTests { @Test fun serializeDeserialize() { val ping = PingRequest val buffer = allocateNewBuffer(4u, limits) ping.serialize(buffer) buffer.resetForRead() assertEquals(12.shl(4).toByte(), buffer.readByte()) assertEquals(0, buffer.readByte()) val buffer2 = allocateNewBuffer(4u, limits) ping.serialize(buffer2) buffer2.resetForRead() val result = ControlPacketV4.from(buffer2) assertEquals(result, ping) } }
2
Kotlin
1
32
2f2d176ca1d042f928fba3a9c49f4bc5ff39495f
653
mqtt
Apache License 2.0
asyncapi-core/src/test/kotlin/com/asyncapi/v3/schema/json/properties/ConstDefaultExamplesBigDecimalTest.kt
asyncapi
262,555,517
false
{"Kotlin": 1663312, "Java": 768695}
package com.asyncapi.v3.schema.json.properties import com.asyncapi.v3.schema.AsyncAPISchema import com.asyncapi.v3.schema.JsonSchema import com.asyncapi.v3.schema.SchemaProvider import java.math.BigDecimal class ConstDefaultExamplesBigDecimalTest: SchemaProvider { private val value = BigDecimal("1.123456789021474836471234567890214748364712345678902147483647") override fun jsonSchema(): JsonSchema { return JsonSchema.builder() .constValue(value) .defaultValue(value) .examples(listOf(value)) .build() } override fun asyncAPISchema(): AsyncAPISchema { return AsyncAPISchema.builder() .constValue(value) .defaultValue(value) .examples(listOf(value)) .build() } }
11
Kotlin
22
64
94a3d1628b17ec58659693bc9ad3b98bca53f172
833
jasyncapi
Apache License 2.0
app/src/main/java/com/bowhead/challenge/util/PreferencesManager.kt
bamby97
332,647,965
false
null
package com.bowhead.challenge.util import android.content.Context import android.content.SharedPreferences import android.os.Build object PreferencesManager { private val TAG = PreferencesManager::class.java.simpleName // private static PreferencesManager instance; private var pref: SharedPreferences? = null fun init(context: Context) { val PREF_NAME = context.packageName pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE or Context.MODE_MULTI_PROCESS) } private val editor: SharedPreferences.Editor private get() = pref!!.edit() fun savePref(key: String?, value: Any?) { val editor = editor if (value is Boolean) { editor.putBoolean(key, (value as Boolean?)!!) } else if (value is Int) { editor.putInt(key, (value as Int?)!!) } else if (value is Float) { editor.putFloat(key, (value as Float?)!!) } else if (value is Long) { editor.putLong(key, (value as Long?)!!) } else if (value is String) { editor.putString(key, value as String?) } else if (value is Enum<*>) { editor.putString(key, value.toString()) } else if (value != null) { throw RuntimeException("Attempting to save non-primitive preference") } editor.commit() } fun <T> getPref(key: String?): T? { return pref!!.all[key] as T? } fun <T> getPref(key: String?, defValue: T): T { val returnValue = pref!!.all[key] as T? return returnValue ?: defValue } fun remove(key: String?) { val editor = editor editor.remove(key) editor.commit() } fun clear() { val editor = editor editor.clear() editor.commit() } object keys { const val WALLET_DIR = "wallet_dir" const val PASS = "<PASSWORD>" } }
0
Kotlin
0
0
01d28ffc41ab8dfa795a9b15af6b9317daeb7cf1
1,938
Challenge
Apache License 2.0
src/main/kotlin/com/control/back/halo/basic/utils/UserUtils.kt
13316989184
188,695,926
false
{"JavaScript": 3747838, "CSS": 1264576, "FreeMarker": 92636, "Kotlin": 69762, "HTML": 22062}
package com.control.back.halo.basic.utils import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpSession import org.springframework.web.context.request.RequestContextHolder import org.springframework.web.context.request.ServletRequestAttributes import com.control.back.halo.basic.commons.Constants import com.control.back.halo.basic.entity.User object UserUtils { val currentUserName: String? get() = currentUser!!.username val currentUser: User? get() { val request = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request val session = request.session var user = session.getAttribute(Constants.USER_SESSION_ID); if (user != null) { return user as User? } return null } }
5
JavaScript
0
0
d83e27f7c5f5b0b003b69b5f6c399833f7d83678
847
kotlin-test-auth
Apache License 2.0
sample-compose/src/main/java/com/speakerboxlite/router/samplecompose/di/AppComponent.kt
AlexExiv
688,805,446
false
{"Kotlin": 446973}
package com.speakerboxlite.router.samplecompose.di import com.speakerboxlite.router.samplecompose.auth.AuthViewModel import com.speakerboxlite.router.samplecompose.base.middleware.MiddlewareControllerAuth import com.speakerboxlite.router.samplecompose.di.modules.AppModule import com.speakerboxlite.router.samplecompose.di.modules.UserModule import com.speakerboxlite.router.samplecompose.main.MainViewModel import com.speakerboxlite.router.samplecompose.result.ResultViewModel import com.speakerboxlite.router.samplecompose.step.StepViewModel import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [AppModule::class, UserModule::class]) interface AppComponent: com.speakerboxlite.router.controllers.Component { fun inject(mw: MiddlewareControllerAuth) fun inject(vm: MainViewModel) fun inject(vm: StepViewModel) fun inject(vm: AuthViewModel) fun inject(vm: ResultViewModel) }
11
Kotlin
2
3
2bda6051ed6888982889635cd2edbcaaec51cd51
930
Router-Android
MIT License
compiler/testData/codegen/boxInline/defaultValues/simpleDefaultMethod.1.kt
staltz
38,581,975
true
{"Java": 15969828, "Kotlin": 11078102, "JavaScript": 176060, "Protocol Buffer": 42992, "HTML": 26117, "Lex": 16668, "ANTLR": 9689, "CSS": 9358, "Groovy": 5204, "Shell": 4638, "Batchfile": 3703, "IDL": 3251}
import test.* fun testCompilation(): String { emptyFun() emptyFun("K") return "OK" } fun simple(): String { return simpleFun() + simpleFun("K") } fun box(): String { var result = testCompilation() if (result != "OK") return "fail1: ${result}" result = simple() if (result != "OK") return "fail2: ${result}" var result2 = simpleDoubleFun(2.0) if (result2 != 2.0 + 1.0) return "fail3: ${result2}" return "OK" }
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
459
kotlin
Apache License 2.0
detekt-test-utils/src/main/kotlin/io/github/detekt/test/utils/CompileExtensions.kt
detekt
71,729,669
false
{"Kotlin": 3939702, "MDX": 291397, "JavaScript": 34635, "HTML": 21039, "CSS": 2763, "Java": 852, "Shell": 249}
package io.github.detekt.test.utils import org.intellij.lang.annotations.Language import org.jetbrains.kotlin.psi.KtFile import java.nio.file.Path import kotlin.io.path.Path /** * Use this method if you define a kt file/class as a plain string in your test. */ fun compileContentForTest( @Language("kotlin") content: String, filename: String, ): KtFile { require('/' !in filename && '\\' !in filename) { "filename must be a file name only and not contain any path elements" } return compileContentForTest(content, path = Path("/$filename")) } /** * Use this method if you define a kt file/class as a plain string in your test. */ fun compileContentForTest( @Language("kotlin") content: String, basePath: Path = Path("/"), path: Path = Path("/Test.kt"), ): KtFile { return KtTestCompiler.createKtFile(content, basePath, path) } /** * Use this method if you test a kt file/class in the test resources. */ fun compileForTest(path: Path) = KtTestCompiler.compile(resourceAsPath("/"), path)
157
Kotlin
753
6,025
d4f3f99ca335a36d596007685d705d0d69f65c01
1,040
detekt
Apache License 2.0
app/src/main/kotlin/sk/mholecy/meteorites/App.kt
ashishkharcheiuforks
242,836,170
true
{"Kotlin": 48667}
package sk.mholecy.meteorites import androidx.work.Configuration import androidx.work.WorkManager import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication import sk.mholecy.meteorites.common.di.AppWorkerFactory import sk.mholecy.meteorites.common.di.DaggerAppComponent import javax.inject.Inject class App : DaggerApplication() { @Inject lateinit var appWorkerFactory: AppWorkerFactory override fun onCreate() { super.onCreate() WorkManager.initialize( this, Configuration.Builder() .setWorkerFactory(appWorkerFactory) .build() ) } override fun applicationInjector(): AndroidInjector<out App> = DaggerAppComponent .factory() .create(this) }
0
null
0
0
0d6a9c4f3b22646970435be105afb8b718452317
791
meteorites
MIT License
video-sdk/src/main/java/com/kaleyra/video_sdk/chat/screen/ChatScreen.kt
KaleyraVideo
686,975,102
false
{"Kotlin": 5025429, "Shell": 7470, "Python": 6756, "Java": 1213}
/* * Copyright 2023 Kaleyra @ https://www.kaleyra.com * * 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. */ @file:OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class) package com.kaleyra.video_sdk.chat.screen import android.content.res.Configuration import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.kaleyra.video_sdk.R import com.kaleyra.video_sdk.chat.appbar.view.GroupAppBar import com.kaleyra.video_sdk.chat.appbar.view.OneToOneAppBar import com.kaleyra.video_sdk.chat.conversation.ConversationComponent import com.kaleyra.video_sdk.chat.conversation.model.ConversationItem import com.kaleyra.video_sdk.chat.conversation.scrollToBottomFabEnabled import com.kaleyra.video_sdk.chat.conversation.view.ResetScrollFab import com.kaleyra.video_sdk.chat.input.ChatUserInput import com.kaleyra.video_sdk.chat.screen.model.ChatUiState import com.kaleyra.video_sdk.chat.screen.model.mockChatUiState import com.kaleyra.video_sdk.chat.screen.viewmodel.PhoneChatViewModel import com.kaleyra.video_sdk.common.usermessages.model.RecordingMessage import com.kaleyra.video_sdk.common.usermessages.model.UserMessage import com.kaleyra.video_sdk.common.usermessages.view.UserMessageSnackbarHandler import com.kaleyra.video_sdk.extensions.ModifierExtensions.highlightOnFocus import com.kaleyra.video_sdk.theme.CollaborationTheme import com.kaleyra.video_sdk.theme.KaleyraTheme import kotlinx.coroutines.launch internal const val ConversationComponentTag = "ConversationComponentTag" @Composable internal fun ChatScreen( onBackPressed: () -> Unit, viewModel: PhoneChatViewModel, embedded: Boolean = false ) { val theme by viewModel.theme.collectAsStateWithLifecycle() val uiState by viewModel.uiState.collectAsStateWithLifecycle() val userMessage by viewModel.userMessage.collectAsStateWithLifecycle(initialValue = null) // if (!uiState.isUserConnected || uiState.connectionState is ConnectionState.Error) { // LaunchedEffect(Unit) { // activity.finishAndRemoveTask() // } // } CollaborationTheme(theme = theme) { ChatScreen( uiState = uiState, userMessage = userMessage, onBackPressed = onBackPressed, embedded = embedded, onMessageScrolled = viewModel::onMessageScrolled, onResetMessagesScroll = viewModel::onAllMessagesScrolled, onFetchMessages = viewModel::fetchMessages, onShowCall = viewModel::showCall, onSendMessage = viewModel::sendMessage, onTyping = viewModel::typing ) } } @OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class) @Composable internal fun ChatScreen( uiState: ChatUiState, userMessage: UserMessage? = null, onBackPressed: () -> Unit, onMessageScrolled: (ConversationItem.Message) -> Unit, onResetMessagesScroll: () -> Unit, onFetchMessages: () -> Unit, onShowCall: () -> Unit, onSendMessage: (String) -> Unit, onTyping: () -> Unit, embedded: Boolean = false ) { val scope = rememberCoroutineScope() val topBarRef = remember { FocusRequester() } val scrollState = rememberLazyListState() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() val onMessageSent: ((String) -> Unit) = remember(scope, scrollState) { { text -> scope.launch { onSendMessage(text) scrollState.scrollToItem(0) } } } val fabRef = remember { FocusRequester() } val scrollToBottomFabEnabled by scrollToBottomFabEnabled(scrollState) val onFabClick = remember(scope, scrollState) { { scope.launch { scrollState.scrollToItem(0) } onResetMessagesScroll() } } var fabPadding by remember { mutableStateOf(0f) } var topAppBarPadding by remember { mutableStateOf(0f) } val chatUserInputContainerColor: Color by animateColorAsState( targetValue = if (scrollState.canScrollBackward) MaterialTheme.colorScheme.outline.copy(.16f) else MaterialTheme.colorScheme.surfaceContainerLowest, label = "chatUserInputContainerColor", animationSpec = spring(stiffness = Spring.StiffnessMediumLow) ) Box( modifier = Modifier.windowInsetsPadding( WindowInsets .navigationBars .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top) ) ) { Scaffold( containerColor = MaterialTheme.colorScheme.surfaceContainerLowest, modifier = Modifier .fillMaxSize() .nestedScroll(scrollBehavior.nestedScrollConnection) .semantics { testTagsAsResourceId = true } .onPreviewKeyEvent { return@onPreviewKeyEvent when { it.type != KeyEventType.KeyDown && it.key == Key.DirectionLeft -> { topBarRef.requestFocus(); true } scrollToBottomFabEnabled && it.type != KeyEventType.KeyDown && it.key == Key.DirectionRight -> { fabRef.requestFocus(); true } else -> false } }, topBar = (@Composable { Column( Modifier .focusRequester(topBarRef) .onGloballyPositioned { topAppBarPadding = it.boundsInRoot().height }) { if (uiState.isInCall) { OngoingCallLabel(onClick = onShowCall) } val topAppBarInsets = if (!uiState.isInCall) TopAppBarDefaults.windowInsets else WindowInsets(0, 0, 0, 0) when (uiState) { is ChatUiState.OneToOne -> { OneToOneAppBar( connectionState = uiState.connectionState, recipientDetails = uiState.recipientDetails, scrollBehavior = scrollBehavior, scrollState = scrollState, windowInsets = topAppBarInsets, isInCall = uiState.isInCall, actions = uiState.actions, onBackPressed = onBackPressed, ) } is ChatUiState.Group -> { GroupAppBar( image = uiState.image, name = uiState.name.ifBlank { stringResource(R.string.kaleyra_chat_group_title) }, scrollBehavior = scrollBehavior, scrollState = scrollState, windowInsets = topAppBarInsets, connectionState = uiState.connectionState, participantsDetails = uiState.participantsDetails, participantsState = uiState.participantsState, isInCall = uiState.isInCall, actions = uiState.actions, onBackPressed = onBackPressed, ) } } } }).takeIf { !embedded } ?: {}, snackbarHost = (@Composable { UserMessageSnackbarHandler( modifier = Modifier .fillMaxSize() .graphicsLayer { translationY = topAppBarPadding }, userMessage = userMessage ) }).takeIf { !embedded } ?: {}, floatingActionButton = { ResetScrollFab( modifier = Modifier .focusRequester(fabRef) .graphicsLayer { translationY = -fabPadding }, counter = uiState.conversationState.unreadMessagesCount, onClick = onFabClick, enabled = scrollToBottomFabEnabled ) }, contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { paddingValues -> Column( modifier = Modifier.padding(paddingValues) ) { ConversationComponent( conversationState = uiState.conversationState, participantsDetails = if (uiState is ChatUiState.Group) uiState.participantsDetails else null, onMessageScrolled = onMessageScrolled, onApproachingTop = onFetchMessages, scrollState = scrollState, modifier = Modifier .weight(1f) .fillMaxWidth() .testTag(ConversationComponentTag) ) HorizontalDivider(color = chatUserInputContainerColor) ChatUserInput( modifier = Modifier .onGloballyPositioned { fabPadding = it.boundsInRoot().height } .navigationBarsPadding() .let { if (!embedded) it.imePadding() else it }, onTextChanged = onTyping, onMessageSent = onMessageSent, onDirectionLeft = topBarRef::requestFocus ) } } } } @Composable internal fun OngoingCallLabel(onClick: () -> Unit) { val interactionSource = remember { MutableInteractionSource() } val systemUiController = rememberSystemUiController() DisposableEffect(Unit) { val hasStatusBarDarkIcons = systemUiController.statusBarDarkContentEnabled systemUiController.setStatusBarColor(color = Color.Transparent, darkIcons = false) onDispose { systemUiController.setStatusBarColor( color = Color.Transparent, darkIcons = hasStatusBarDarkIcons ) } } Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clickable( onClick = onClick, role = Role.Button, interactionSource = interactionSource, indication = LocalIndication.current ) .fillMaxWidth() .background( shape = RectangleShape, color = KaleyraTheme.colors.positiveContainer ) .highlightOnFocus(interactionSource) .padding(horizontal = 16.dp, vertical = 8.dp) .padding(WindowInsets.statusBars.asPaddingValues()) ) { Text( text = stringResource(id = R.string.kaleyra_ongoing_call_label), color = Color.White, style = MaterialTheme.typography.bodyMedium, ) } } @Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, name = "Light Mode") @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark Mode") @Composable internal fun ChatScreenPreview() = KaleyraTheme { ChatScreen( uiState = mockChatUiState, onBackPressed = { }, onMessageScrolled = { }, onResetMessagesScroll = { }, onFetchMessages = { }, onShowCall = { }, onSendMessage = { }, onTyping = { }, userMessage = RecordingMessage.Started, ) }
0
Kotlin
0
1
d73e4727cec4875a98b21110823947edcfe9e28c
15,499
VideoAndroidSDK
Apache License 2.0
src/tasks/Request5NotCancellable.kt
chunglun
431,555,438
true
{"Kotlin": 38814}
package tasks import contributors.* import kotlinx.coroutines.* import kotlin.coroutines.coroutineContext /** * Implement TODO(), use the previous loadContributorsSuspend() * * 1. copy the implementation of loadContributorsConcurrent() to loadContributorsNotCancellable() * 2. remove the creation of a new coroutineScope */ /* suspend fun loadContributorsNotCancellable(service: GitHubService, req: RequestData): List<User> { TODO() } */ suspend fun loadContributorsNotCancellable(service: GitHubService, req: RequestData): List<User> { val repos = service .getOrgRepos(req.org) .also { logRepos(req, it) } .bodyList() val result = repos.map { repo -> GlobalScope.async { log("starting loading for ${repo.name}") delay(3000) service.getRepoContributors(req.org, repo.name) .also { logUsers(repo, it) } .bodyList() } }.awaitAll().flatten().aggregate() return result }
0
Kotlin
0
0
7f8f40b48f7127c560100321657f2cf0b65d337e
1,004
intro-coroutines
Apache License 2.0
core/src/commonMain/kotlin/com/xebia/functional/xef/llm/openai/images/ImagesGenerationRequest.kt
xebia-functional
629,411,216
false
null
package com.xebia.functional.xef.llm.openai.images import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ImagesGenerationRequest( val prompt: String, @SerialName("n") val numberImages: Int = 1, val size: String = "1024x1024", @SerialName("response_format") val responseFormat: String = "url", val user: String? = null )
5
Kotlin
3
67
38277adadef844ac5536b8ff036e94b45c578132
385
xef
Apache License 2.0
app/src/main/java/ch/admin/foitt/pilotwallet/feature/qrscan/domain/usecase/implementation/CheckQrScanPermissionImpl.kt
e-id-admin
775,912,525
false
{"Kotlin": 1521284}
package ch.admin.foitt.pilotwallet.feature.qrscan.domain.usecase.implementation import androidx.annotation.CheckResult import ch.admin.foitt.pilotwallet.feature.qrscan.domain.model.PermissionState import ch.admin.foitt.pilotwallet.feature.qrscan.domain.repository.CameraIntroRepository import ch.admin.foitt.pilotwallet.feature.qrscan.domain.usecase.CheckQrScanPermission import timber.log.Timber import javax.inject.Inject class CheckQrScanPermissionImpl @Inject constructor( private val cameraIntroRepository: CameraIntroRepository, ) : CheckQrScanPermission { @CheckResult override suspend fun invoke( permissionsAreGranted: Boolean, rationaleShouldBeShown: Boolean, promptWasTriggered: Boolean, ): PermissionState { Timber.d( "Permission result\n" + "granted: $permissionsAreGranted\n" + "rationale should be shown: $rationaleShouldBeShown\n" + "prompt was Triggered: $promptWasTriggered" ) if (promptWasTriggered) { cameraIntroRepository.setPermissionPromptWasTriggered(true) } val cameraIntroPromptTriggered = cameraIntroRepository.getPermissionPromptWasTriggered() return when { permissionsAreGranted -> PermissionState.Granted rationaleShouldBeShown -> PermissionState.Rationale !cameraIntroPromptTriggered -> PermissionState.Intro // Permission were refused after an active prompt // but no rationale was asked // Can happen for various reasons, like // - permissions were toggled/changed outside the app // - the system reset the permissions after some time // - the prompt was denied after a rationale // The state is not always consistent, but we have to assume the permission could be permanently denied // As of vanilla android 11. else -> PermissionState.Blocked } } }
1
Kotlin
1
4
6572b418ec5abc5d94b18510ffa87a1e433a5c82
2,005
eidch-pilot-android-wallet
MIT License