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
brd-android/fabriik-common/src/main/java/com/fabriik/common/data/FabriikApiConstants.kt
fabriik
489,117,365
false
null
package com.fabriik.common.data import android.os.Build import com.fabriik.common.BuildConfig import okhttp3.Request object FabriikApiConstants { const val HOST = "${BuildConfig.SERVER_HOST}/blocksatoshi" private const val BASE_URL = "https://$HOST" const val HOST_WYRE_API = "$BASE_URL/wyre/" const val HOST_KYC_API = "$BASE_URL/one/kyc/" const val HOST_SWAP_API = "$BASE_URL/exchange/" const val HOST_AUTH_API = "$BASE_URL/one/auth/" const val HOST_WALLET_API = "$BASE_URL/wallet" const val HOST_BLOCKSATOSHI_API = "$BASE_URL/blocksatoshi" const val ENDPOINT_CURRENCIES = "$HOST_WALLET_API/currencies" const val ENDPOINT_FIAT_CURRENCIES = "$HOST_WALLET_API/fiat_currencies" const val URL_SUPPORT_PAGE = "https://app-support.fabriik.com/" const val URL_PRIVACY_POLICY = "https://fabriik.com/privacy-policy/" const val URL_TERMS_AND_CONDITIONS = "https://fabriik.com/terms-and-conditions/" const val HEADER_DEVICE_ID = "X-Device-ID" const val HEADER_USER_AGENT = "User-agent" const val HEADER_AUTHORIZATION = "Authorization" const val SYSTEM_PROPERTY_USER_AGENT = "http.agent" const val UA_APP_NAME = "fabriik/wallet/" const val UA_PLATFORM = "android/" val USER_AGENT_VALUE = getUserAgent() private fun getUserAgent(): String { val deviceUserAgent = (System.getProperty(SYSTEM_PROPERTY_USER_AGENT) ?: "") .split("\\s".toRegex()) .firstOrNull() //example: fabriik/wallet/100000 Dalvik/2.1.0 android/12 return "${UA_APP_NAME}${BuildConfig.VERSION_CODE} $deviceUserAgent ${UA_PLATFORM}${Build.VERSION.RELEASE}" } }
2
Kotlin
1
1
8894f5c38203c64e48242dae9ae9344ed4b2a61f
1,660
wallet-android
MIT License
modules/networking/src/main/kotlin/org/teamvoided/voidlib/networking/C2SVoidPacket.kt
TeamVoided
570,651,037
false
{"Kotlin": 316530, "Java": 10455, "GLSL": 386}
package org.teamvoided.voidlib.networking import net.fabricmc.fabric.api.networking.v1.PacketSender import net.minecraft.network.PacketByteBuf import net.minecraft.server.MinecraftServer import net.minecraft.server.network.ServerPlayNetworkHandler import net.minecraft.server.network.ServerPlayerEntity interface C2SVoidPacket<PacketData>: VoidPacket<PacketData> { fun handleC2S( server: MinecraftServer, player: ServerPlayerEntity, handler: ServerPlayNetworkHandler, data: PacketData, responseSender: PacketSender ) fun handleC2S( server: MinecraftServer, player: ServerPlayerEntity, handler: ServerPlayNetworkHandler, buf: PacketByteBuf, responseSender: PacketSender ) { handleC2S(server, player, handler, decode(buf), responseSender) } } typealias ServerReceiver<PacketData> = C2SVoidPacket<PacketData>
0
Kotlin
0
2
53b2d25509d4cb1c6e32577c0f6c4eb7990251b8
917
VoidLib
MIT License
work_13/shared/src/commonMain/kotlin/network/NetworkingConfig.kt
goldenplan
243,709,136
false
{"Swift": 436583, "Kotlin": 17889}
package com.overinet const val API_KEY = "0564bb225da38996fdbb42d71ab58067" const val BASE_URL = "https://api.themoviedb.org/" const val MOVIE_LIST_BASE_PATH = "${BASE_URL}3/movie/popular?api_key=$API_KEY&page=1" const val MOVIE_SEARCH_BASE_PATH = "${BASE_URL}3/search/movie?api_key=$API_KEY&page=1" const val MOVIE_IMAGE_BASE_PATH = "https://image.tmdb.org/t/p/w500"
0
Swift
0
0
32900adc508fd69207f25814e00a5453692cd30c
368
home_work
MIT License
src/main/kotlin/org/halflife/clientmanager/mapper/impl/ClientMapperImpl.kt
xEnakil
793,054,418
false
{"Kotlin": 72479}
package org.halflife.clientmanager.mapper.impl import org.halflife.clientmanager.dto.request.ClientRequest import org.halflife.clientmanager.dto.response.ClientResponse import org.halflife.clientmanager.dto.response.FullClientResponse import org.halflife.clientmanager.mapper.ClientMapper import org.halflife.clientmanager.model.Client import org.halflife.clientmanager.model.Role import org.springframework.stereotype.Component @Component class ClientMapperImpl : ClientMapper { override fun toResponse(client: Client): ClientResponse = ClientResponse( email = client.email, firstName = client.firstName, lastName = client.lastName, job = client.job, position = client.position, gender = client.gender, ) override fun toModel(clientRequest: ClientRequest): Client = Client( email = clientRequest.email, password = <PASSWORD>, firstName = clientRequest.firstName, lastName = clientRequest.lastName, gender = clientRequest.gender, role = Role.USER, job = clientRequest.job, position = clientRequest.position, ) override fun toFullResponse(client: Client): FullClientResponse = FullClientResponse( id = client.id.toString(), email = client.email, firstName = client.firstName, lastName = client.lastName, job = client.job.toString(), position = client.position.toString(), role = client.role.toString(), gender = client.gender.toString() ) }
0
Kotlin
0
0
763b04aa6046eaef1eb72ec6114233e8b621763a
1,667
ClientManager
MIT License
shared/src/commonMain/kotlin/markdown/elements/MarkdownText.kt
AntonAlekseevich93
683,819,027
false
null
package markdown.elements import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import markdown.linkhandler.LocalReferenceLinkHandler import markdown.theme.LocalMarkdownColors import markdown.theme.LocalMarkdownTypography @Composable internal fun MarkdownText( content: String, modifier: Modifier = Modifier, style: TextStyle = LocalMarkdownTypography.current.text, ) { MarkdownText(AnnotatedString(content), modifier, style) } @Composable internal fun MarkdownText( content: AnnotatedString, modifier: Modifier = Modifier, style: TextStyle = LocalMarkdownTypography.current.text, ) { val uriHandler = LocalUriHandler.current val referenceLinkHandler = LocalReferenceLinkHandler.current val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) } SelectionContainer() { Text( text = content, modifier = modifier, color = LocalMarkdownColors.current.text, onTextLayout = { layoutResult.value = it } ) } }
0
Kotlin
0
0
3f328a95c2de861889b81c1c571954d6e67b02d2
1,445
ChatGTP
Apache License 2.0
app/src/main/java/org/rfcx/incidents/data/SubscribeRepositoryImp.kt
rfcx
104,899,135
false
{"Kotlin": 1176262, "Java": 1049}
package org.rfcx.incidents.data import io.reactivex.Single import org.rfcx.incidents.data.interfaces.SubscribeRepository import org.rfcx.incidents.data.remote.subscribe.SubscribeEndpoint import org.rfcx.incidents.entity.user.SubscribeRequest import org.rfcx.incidents.entity.user.SubscribeResponse class SubscribeRepositoryImp(private val subscribeEndpoint: SubscribeEndpoint) : SubscribeRepository { override fun subscribe(request: SubscribeRequest): Single<SubscribeResponse> { return subscribeEndpoint.sendGroups(request) } override fun unsubscribe(request: SubscribeRequest): Single<SubscribeResponse> { return subscribeEndpoint.sendGroupsUnsubscribe(request) } }
30
Kotlin
0
0
cbcb9402733a959104aff97f26d04244b73bc109
703
guardian-app-android
Apache License 2.0
app/src/main/java/org/rfcx/incidents/data/SubscribeRepositoryImp.kt
rfcx
104,899,135
false
{"Kotlin": 1176262, "Java": 1049}
package org.rfcx.incidents.data import io.reactivex.Single import org.rfcx.incidents.data.interfaces.SubscribeRepository import org.rfcx.incidents.data.remote.subscribe.SubscribeEndpoint import org.rfcx.incidents.entity.user.SubscribeRequest import org.rfcx.incidents.entity.user.SubscribeResponse class SubscribeRepositoryImp(private val subscribeEndpoint: SubscribeEndpoint) : SubscribeRepository { override fun subscribe(request: SubscribeRequest): Single<SubscribeResponse> { return subscribeEndpoint.sendGroups(request) } override fun unsubscribe(request: SubscribeRequest): Single<SubscribeResponse> { return subscribeEndpoint.sendGroupsUnsubscribe(request) } }
30
Kotlin
0
0
cbcb9402733a959104aff97f26d04244b73bc109
703
guardian-app-android
Apache License 2.0
app/src/main/java/com/weibo/biz/kotlin/listview/ToDoListAdapter.kt
huipengo
166,368,980
false
null
package com.weibo.biz.kotlin.listview import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.weibo.biz.kotlin.R import android.widget.BaseAdapter import android.widget.ImageView import com.bumptech.glide.Glide class ToDoListAdapter(dl: List<ListModel>, mContext: Context) : BaseAdapter() { var todoList: List<ListModel>? = null var mViewHolder: MyViewHoler? = null var mContext:Context init { todoList = dl this.mContext = mContext } override fun getItem(position: Int): Any { return todoList!![position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getCount(): Int { return todoList?.size ?: 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var mConvertView = convertView if (convertView == null) { mConvertView = LayoutInflater.from(mContext).inflate(R.layout.holder_list_item, null) mViewHolder = MyViewHoler() mViewHolder!!.mImageView = mConvertView?.findViewById(R.id.tv_imageView) mViewHolder!!.mTitle = mConvertView?.findViewById(R.id.tv_title) mViewHolder!!.mContentTv = mConvertView?.findViewById(R.id.tv_content) (if (mConvertView != null) mConvertView else { throw KotlinNullPointerException() }).tag = this.mViewHolder } else { mViewHolder = mConvertView?.getTag() as MyViewHoler } val model: ListModel = todoList!![position] mViewHolder?.mTitle?.text = model?.title mViewHolder?.mContentTv?.text = model?.content val imageView = mViewHolder?.mImageView as ImageView Glide.with(mContext).load(model.url).into(imageView) return mConvertView!! } inner class MyViewHoler() { public var mImageView:ImageView? = null public var mTitle:TextView? = null public var mContentTv:TextView? = null } }
0
Kotlin
0
1
f163bcb30c89bd42de1ac1b50313d6f9fc293f51
2,129
Kotlin_Learning
MIT License
plugin/src/main/kotlin/io/github/realyusufismail/config/impl/JConfigPluginImpl.kt
RealYusufIsmail
790,074,096
false
{"Kotlin": 19093}
/* * Copyright 2024 Yusuf Arfan Ismail (RealYusufIsmail) * * * 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 io.github.realyusufismail.config.impl import com.fasterxml.jackson.databind.JsonNode import io.github.realyusufismail.config.JConfigPlugin import io.github.realyusufismail.config.JConfigPluginObject import io.github.realyusufismail.jconfig.classes.JsonEntry class JConfigPluginImpl(entries: List<JsonEntry>) : JConfigPlugin { private var mapEntries: Map<String, Any> = HashMap() private var jsonEntries: Set<JsonEntry> = HashSet() init { this.mapEntries = JsonEntry.toMap(entries) jsonEntries = this.mapEntries.map { JsonEntry(it.key, it.value) }.toSet() } override val entries: Set<JsonEntry> get() = jsonEntries val values: Set<Map.Entry<String, JConfigPluginObject>> get() { val map = HashMap<String, JConfigPluginObject>() for (entry in jsonEntries) { map[entry.key] = getAsJConfigObject(entry.key)!! } return map.entries } override fun get(key: String): JsonNode? { val value = mapEntries[key] ?: throw NoSuchElementException("No value present for key: $key") return if (value is JsonNode) { value } else { null } } override fun set(key: String, value: Any) { mapEntries = mapEntries.toMutableMap().apply { put(key, value) } jsonEntries = mapEntries.map { JsonEntry(it.key, it.value) }.toSet() } override fun set(key: String, value: JConfigPluginObject) { set(key, value.asJsonEntry) } override fun contains(key: String): Boolean { return mapEntries.containsKey(key) } }
0
Kotlin
0
0
ed4c56f666e1874ad59774c7292f40a8e029f432
2,280
jconfig-plugin
Apache License 2.0
composeApp/src/commonMain/kotlin/presentation/components/GroupLayout.kt
Coding-Meet
740,487,604
false
{"Kotlin": 107587, "JavaScript": 707, "Swift": 659, "HTML": 401}
package presentation.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import domain.model.Group import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import theme.borderColor import theme.selectedBGColor import theme.whiteColor import utils.capitalizeFirstLetter @OptIn(ExperimentalMaterial3Api::class) @Composable fun GroupLayout(group: Group, isSelected: Boolean, onClick: () -> Unit) { Card( modifier = Modifier .fillMaxWidth() .padding(10.dp), elevation = CardDefaults.elevatedCardElevation(defaultElevation = 8.dp), onClick = { onClick() }, colors = CardDefaults.cardColors( containerColor = if (isSelected) selectedBGColor else borderColor, contentColor = whiteColor ) ) { GroupRowLayout(group, Modifier.padding(10.dp)) } } @OptIn(ExperimentalResourceApi::class) @Composable fun GroupRowLayout(group: Group, customModifier: Modifier = Modifier) { Row( Modifier .fillMaxWidth() .then(customModifier), verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(group.icon), null, modifier = Modifier.size(50.dp) ) Spacer(modifier = Modifier.width(10.dp)) Column( modifier = Modifier .weight(0.8f) ) { Text( text = group.groupName.capitalizeFirstLetter(), style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( text = group.date, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 8.dp)) } } }
0
Kotlin
0
7
d1680ef03820bb5e6645ff16c88ad3b0e4a73bc8
2,241
Gemini-AI-KMP-App
MIT License
app/src/main/java/com/cuong/moviehero/domain/use_case/movie/FetchMovieDetail.kt
cuonghuynhvan
471,910,042
false
{"Kotlin": 141883}
package com.cuong.moviehero.domain.use_case.movie import com.cuong.moviehero.domain.model.MovieDetail import com.cuong.moviehero.domain.repository.MovieRepository class FetchMovieDetail( private val repository: MovieRepository ) { suspend operator fun invoke(movieId: String): MovieDetail { return repository.fetchMovieDetail(movieId) } }
0
Kotlin
0
0
36bc4b4d840343e7f7b63bc70f81546f8b49665d
360
MovieHero
MIT License
src/main/kotlin/me/hrrocha0/avaliaunb/models/data/ProfessorOuDisciplinaDAO.kt
hrrocha0
657,358,914
false
null
package me.hrrocha0.avaliaunb.models.data import me.hrrocha0.avaliaunb.models.ProfessorOuDisciplinaModel import java.sql.ResultSet object ProfessorOuDisciplinaDAO : ReadWriteDAO<ProfessorOuDisciplinaModel> { override fun create(model: ProfessorOuDisciplinaModel) = try { val sql = """ INSERT INTO ProfessorOuDisciplina VALUES (${model.codigo}) """.trimIndent() executeSql(sql) model } catch (e: Exception) { null } override fun read(vararg keys: String) = try { val sql = """ SELECT * FROM ProfessorOuDisciplina WHERE id = ${keys[0]} """.trimIndent() executeSql(sql).first() } catch (e: Exception) { null } override fun update(model: ProfessorOuDisciplinaModel, vararg keys: String) = try { val sql = """ UPDATE ProfessorOuDisciplina SET codigo = ${model.codigo} WHERE codigo = ${keys[0]} """.trimIndent() val professorOuDisciplina = read(*keys) executeSql(sql) professorOuDisciplina } catch (e: Exception) { null } override fun delete(vararg keys: String) = try { val sql = """ DELETE FROM ProfessorOuDisciplina WHERE codigo = ${keys[0]} """.trimIndent() val professorOuDisciplina = read(*keys) executeSql(sql) professorOuDisciplina } catch (e: Exception) { null } override fun index(predicate: (ProfessorOuDisciplinaModel) -> Boolean) = try { val sql = "SELECT * FROM ProfessorOuDisciplina" executeSql(sql).filter(predicate) } catch (e: Exception) { listOf() } override fun transform(resultSet: ResultSet): ProfessorOuDisciplinaModel { val codigo = resultSet.getInt("codigo") return ProfessorOuDisciplinaModel(codigo) } }
0
Kotlin
0
0
80b2205c73e9bc0ca0eec81148f776e885761534
1,918
AvaliaUnB
MIT License
app/src/main/java/br/com/natanloterio/bankingapp/presentation/ui/welcome/WelcomeContract.kt
natanloterio
188,720,586
false
null
package br.com.natanloterio.bankingapp.presentation.ui.welcome import br.com.natanloterio.bankingapp.presentation.base.BasePresenterInterface import br.com.natanloterio.bankingapp.presentation.base.BaseViewInterface interface WelcomeContract{ interface View : BaseViewInterface{ fun openMainScreen() fun openCreateAccount() } interface Presenter : BasePresenterInterface { val view: View fun onClickLogin() fun onClickCreateAccount() } }
0
Kotlin
0
4
50c851e36c9e15f718a5ac40ae13a001024044cb
499
BankingAppBoilerplate
MIT License
app/src/main/java/com/mospolytech/mospolyhelper/domain/account/messaging/repository/MessagingRepository.kt
mospolyhelper
259,442,737
false
{"Kotlin": 839539, "Batchfile": 69}
package com.mospolytech.mospolyhelper.domain.account.messaging.repository import com.mospolytech.mospolyhelper.domain.account.messaging.model.Message import com.mospolytech.mospolyhelper.utils.Result0 import kotlinx.coroutines.flow.Flow interface MessagingRepository { suspend fun getDialog(dialogKey: String): Flow<Result0<List<Message>>> suspend fun getLocalDialog(dialogKey: String): Flow<Result0<List<Message>>> suspend fun sendMessage(dialogKey: String, message: String, fileNames: List<String>): Flow<Result0<List<Message>>> suspend fun deleteMessage(dialogKey: String, removeKey: String): Flow<Result0<List<Message>>> }
2
Kotlin
2
8
4f37c3617cf7523f22f03a22d7de2d7ecc74a098
644
mospolyhelper-android
MIT License
cookbook/src/main/kotlin/chapter03/Task.kt
highright96
499,829,960
false
{"Kotlin": 114073, "Java": 941}
package chapter03 class Task(val name: String, _priority: Int = DEFAULT_PRIORITY) { companion object { const val MIN_PRIORITY = 1 const val MAX_PRIORITY = 5 const val DEFAULT_PRIORITY = 3 } val isLowPriority get() = priority < 3 var priority = validPriority(_priority) set(value) { field = validPriority(value) } private fun validPriority(p: Int) = p.coerceIn(MIN_PRIORITY, MAX_PRIORITY) } fun main() { var myTask = Task("name").apply { priority = 4 } val isLow = myTask.isLowPriority println(isLow) }
0
Kotlin
0
2
c3cd06deba34ac5b1e60650c638af65034d6ac42
612
kotlin-sandbox
MIT License
app/src/main/java/com/example/lun/pocket_health_advisor/medicReport/MedicReportHistoryFragment.kt
WLun001
110,719,603
false
null
package com.example.lun.pocket_health_advisor.medicReport import android.content.Intent import android.os.Bundle import android.support.v4.app.ListFragment import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ListView import com.example.lun.pocket_health_advisor.R import com.example.lun.pocket_health_advisor.adapter.MedicReportAdapter import com.example.lun.pocket_health_advisor.ulti.DataClassWrapper.* import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import org.jetbrains.anko.support.v4.* import org.jetbrains.anko.toast import org.jetbrains.anko.yesButton /** * Created by wlun on 2/10/18. */ class MedicReportHistoryFragment : ListFragment() { companion object { @JvmStatic val MEDIC_REPORT = "com.example.lun.pocket_health_advisor.medicReport.MEDIC_REPORT" } private var medicReportList = ArrayList<MedicReport>() private var displayName: String? = "" private lateinit var db: FirebaseFirestore private var authUid: String? = "" override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) db = FirebaseFirestore.getInstance() val listener = AdapterView.OnItemLongClickListener { p0, p1, position, p3 -> val options = listOf("Send report to hospital", "Delete report") selector("Choose an option to perform", options, { _, i -> when (i) { 0 -> sendReport(position) 1 -> deleteReport(position) } }) false } listView.onItemLongClickListener = listener val auth = FirebaseAuth.getInstance() authUid = auth.currentUser?.uid displayName = auth.currentUser?.displayName getReportFromDb() } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_medic_report_fragment, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val id = item?.itemId when (id) { R.id.send_to_hospital -> { if (listAdapter.count > 0) { val progress = progressDialog("Please wait", "Getting report") progress.show() progress.max = listAdapter.count val reportList = ArrayList<String>() for (i in 0 until listAdapter.count) { reportList.add((listAdapter.getItem(i) as MedicReport).diagnoseCondition.commonName) progress.incrementProgressBy(1) } progress.dismiss() selector("Please choose one report to send", reportList, { _, i -> sendReport(i) }) } else alert("No report available yet") { yesButton { dialog -> dialog.dismiss() } }.show() } } return super.onOptionsItemSelected(item) } override fun onListItemClick(l: ListView?, v: View?, position: Int, id: Long) { val intent = Intent(context, MReportDetailsActivity::class.java) intent.putExtra(MEDIC_REPORT, medicReportList[position]) startActivity(intent) } private fun deleteReport(position: Int) { authUid?.let { db.collection(getString(R.string.first_col)) .document(authUid.toString()) .collection("medic_report") .document((listAdapter.getItem(position) as MedicReport).reportId) .delete() .addOnCompleteListener { getReportFromDb() alert("Successfully deleted report, revisit again see the changes") { yesButton { dialog -> dialog.dismiss() } }.show() } .addOnFailureListener { alert(it.message.toString()) { yesButton { dialog -> dialog.dismiss() } }.show() } } } // TODO: match with ic instead of name private fun sendReport(choice: Int) { val progress = indeterminateProgressDialog("sending report...") progress.show() db.collection("patients") .whereEqualTo("name", displayName) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val doc = task.result for (i in doc) { val docId = i.id FirebaseFirestore.getInstance() .collection("patients") .document(docId) .update( "diagnosis_history", (listAdapter.getItem(choice) as MedicReport).generateMap() ) .addOnCompleteListener { task -> if (task.isComplete) { progress.dismiss() } alert("Successfully sent report to hospital") { yesButton { dialog -> dialog.dismiss() } }.show() } .addOnFailureListener { task -> progress.dismiss() toast("error sending report".plus(task.message)) } } } } } private fun getReportFromDb() { authUid?.let { db.collection(getString(R.string.first_col)) .document(authUid.toString()) .collection("medic_report") .orderBy("timestamp") .get() .addOnCompleteListener { task -> if (task.isSuccessful) { for (i: DocumentSnapshot in task.result) { medicReportList.add( MedicReport( readDiagnoseCondition(i), readInitialSyndrome(i), readPossibleConditions(i), readQuestions(i), i.get("timestamp").toString(), i.id ) ) } setUpListFragment(medicReportList) } else { activity.toast(task.exception.toString()) } } } } private fun readInitialSyndrome(doc: DocumentSnapshot): ArrayList<InitialSyndrome> { val initialSyndromeList = ArrayList<InitialSyndrome>() val initialSyndrome = (doc["initial"] as HashMap<*, *>)["initial"] as ArrayList<*> for (initial in initialSyndrome) { initialSyndromeList.add( InitialSyndrome( (initial as HashMap<*, *>)["name"].toString(), initial["choice_id"].toString(), initial) ) } return initialSyndromeList } private fun readPossibleConditions(doc: DocumentSnapshot): ArrayList<PossibleCondition> { val possibleConditionsList = ArrayList<PossibleCondition>() val possibleConditions = doc["possible_conditions"] as HashMap<*, *> val conditions = possibleConditions["conditions"] as ArrayList<*> for (cond in conditions) { possibleConditionsList.add( PossibleCondition( (cond as HashMap<*, *>)["name"].toString(), cond["probability"].toString().toDouble(), cond ) ) } return possibleConditionsList } private fun readDiagnoseCondition(doc: DocumentSnapshot): Condition { val diagnoseCondition = doc["diagnose_condition"] as HashMap<*, *> val name = diagnoseCondition["name"].toString() val commonName = diagnoseCondition["common_name"].toString() var acuteness = diagnoseCondition["acuteness"].toString() val categories = diagnoseCondition["categories"] as ArrayList<*> val hints = (diagnoseCondition["extras"] as HashMap<*, *>)["hint"].toString() var prevalence = diagnoseCondition["prevalence"].toString() var severity = diagnoseCondition["severity"].toString() var triageLevel = diagnoseCondition["triage_level"].toString() acuteness = formatString(acuteness) prevalence = formatString(prevalence) severity = formatString(severity) triageLevel = formatString(triageLevel) val categoriesList = ArrayList<String>() for (cat in categories) { categoriesList.add(cat.toString()) } return Condition( name, commonName, acuteness, categoriesList, hints, prevalence, severity, triageLevel, diagnoseCondition ) } private fun readQuestions(doc: DocumentSnapshot): ArrayList<Question> { val questionList = ArrayList<Question>() val question = doc["questions"] as ArrayList<*> for (i in question) { questionList.add( Question( (i as HashMap<*, *>)["question"].toString(), i["symptom"].toString(), i["user_response"].toString(), question ) ) } return questionList } private fun formatString(s: String): String { return s.replace('_', ' ') } private fun setUpListFragment(medicReport: ArrayList<MedicReport>) { val adapter = MedicReportAdapter(context, medicReport) listAdapter = adapter } }
4
Kotlin
9
9
603967a465f1e4c1cd46877be6892a50cf0bb030
11,001
pocket-health-advisor
MIT License
app/src/main/kotlin/me/miguelos/sample/data/MarvelRepositoryImpl.kt
Miguelos
321,421,228
false
null
package me.miguelos.sample.data import io.reactivex.rxjava3.core.Single import me.miguelos.sample.data.source.local.MarvelLocalRemoteDataSource import me.miguelos.sample.data.source.remote.MarvelRemoteRemoteDataSource import me.miguelos.sample.domain.MarvelRepository import me.miguelos.sample.domain.usecase.GetCharacter import me.miguelos.sample.domain.usecase.GetCharacters import me.miguelos.sample.domain.usecase.SaveCharacters import javax.inject.Inject /** * Concrete implementation to load characters from the data sources into a cache. * * * Use the remote data source only if the local database doesn't exist or is empty. */ class MarvelRepositoryImpl @Inject constructor( private val marvelLocalDS: MarvelLocalRemoteDataSource, private val marvelRemoteDS: MarvelRemoteRemoteDataSource ) : MarvelRepository { /** * Gets Marvel characters from cache, local data source (SQLite) or remote data source, * in that order or preference. */ override fun getMarvelCharacters( requestValues: GetCharacters.RequestValues ): Single<GetCharacters.ResponseValues?> = if (requestValues.ranked) { getLocalRankedMarvelCharacters(requestValues) } else { marvelRemoteDS.getMarvelCharacters(requestValues) } private fun getLocalRankedMarvelCharacters( requestValues: GetCharacters.RequestValues ): Single<GetCharacters.ResponseValues?> = marvelLocalDS.getRankedMarvelCharacters(requestValues) /** * Gets characters from local data source (sqlite) unless the table is new or empty. * In that case it uses the network data source. This is done to simplify the sample. */ override fun getMarvelCharacter( requestValues: GetCharacter.RequestValues ): Single<GetCharacter.ResponseValues?> = Single.concat( marvelLocalDS.getRankedMarvelCharacter(requestValues), marvelRemoteDS.getMarvelCharacter(requestValues) ) .filter { response -> response?.marvelCharacter != null } .first(GetCharacter.ResponseValues()) override fun deleteAllMarvelCharacters() = marvelLocalDS.deleteRankedMarvelCharacters() override fun saveMarvelCharacters(requestValues: SaveCharacters.RequestValues) = marvelLocalDS.saveMarvelCharacters(requestValues) }
0
Kotlin
0
0
9d03ca4e7690973d7d1a1378742ff8e601db3f56
2,342
AndroidSample
Apache License 2.0
app/src/main/java/com/stack/open_work_mobile/models/UpdateResponse.kt
1OPENWORK
708,477,953
false
{"Kotlin": 132763}
package com.stack.open_work_mobile.models data class UpdateResponse ( val userId: Long, var nome: String, var email: String, var tipo: String, var token: String, var companyId: Long, var image: String, )
0
Kotlin
0
0
a00ad9c6c60c89bd1379052c7b07c7553ea3231b
232
Kotlin
MIT License
src/main/kotlin/com/dymesolutions/linkedevents/migrations/Migrations.kt
dymesolutions
155,518,740
false
null
package com.dymesolutions.linkedevents.migrations import com.dymesolutions.common.utils.Readers import com.dymesolutions.linkedevents.App import com.dymesolutions.linkedevents.dao.* import com.dymesolutions.linkedevents.models.* import com.google.gson.JsonArray import com.google.gson.JsonParser import org.jetbrains.exposed.sql.transactions.transaction import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.io.File class Migrations { companion object { private val jsonParser = JsonParser() private val log = LoggerFactory.getLogger(App::class.java) private val tableNames = listOf("events_event", "helevents_user", "django_orghierarchy_organization", "events_datasource") private val migrationsPath = "${File.separator}migrations${File.separator}" } private fun checkTableExists(tableName: String): Boolean { return transaction { val query = """ SELECT EXISTS( SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '$tableName' );""".trimIndent() exec(query) { it.next() it.getBoolean(1) } ?: false } } fun checkSchemaAndMigrateData(): Boolean { log.info("Checking database schema...") // First check that required tables exist tableNames.forEach { if (!checkTableExists(it)) { log.error("Required table '$it' doesn't exist!") return false } } migrateDataSources() migrateOrganizations() migrateUsers() migrateKeywordSets() migrateKeywords() return true } private fun migrateUsers() { parseJsonArrayFromResource("${migrationsPath}users.json") { array -> array.map { val user = it.asJsonObject UserSave( username = user["username"].asString, email = user["email"].asString, password = user["password"].asString, firstName = user["firstName"].asString, lastName = user["lastName"].asString, isStaff = user["isStaff"].asBoolean, isSuperUser = user["isSuperUser"].asBoolean, isActive = user["isActive"].asBoolean ) }.forEach { userToSave -> if (Users.findByUsername(userToSave.username) == null) { log.info("Saving user with username '${userToSave.username}'") Users.add(userToSave)?.let { userId -> // Add user to system admins OrganizationRegularUsers.add(userId, "system:admins") EmailAddresses.add(email = userToSave.email, userId = userId) }?.let { emailAddressId -> EmailAddresses.verifyById(emailAddressId) } } else { log.warn("User with username '${userToSave.email}' already exists!") } } } } private fun migrateDataSources() { parseJsonArrayFromResource("${migrationsPath}datasources.json") { array -> array.map { val dataSource = it.asJsonObject DataSourceSave( id = dataSource["id"].asString, name = dataSource["name"].asString, apiKey = dataSource["apiKey"].asString, ownerId = dataSource["ownerId"].let { ownerId -> if (ownerId.isJsonNull) null else ownerId.asString }, userEditable = dataSource["userEditable"].asBoolean ) }.forEach { dataSourceToSave -> if (DataSources.findById(dataSourceToSave.id) == null) { log.info("Saving datasource with ID '${dataSourceToSave.id}'") DataSources.add(dataSourceToSave) } else { log.warn("Data Source with ID ${dataSourceToSave.id} already exists!") } } } } private fun migrateOrganizations() { parseJsonArrayFromResource("${migrationsPath}organizations.json") { array -> array.map { val organization = it.asJsonObject OrganizationSave( originId = organization["originId"].asString, name = organization["name"].asString, dataSourceId = organization["dataSourceId"].asString, foundingDate = null, dissolutionDate = null, classificationId = null, createdById = null, lastModifiedById = null, parentId = null, replacedById = null, internalType = "" ) }.forEach { organizationToSave -> val organizationId = "${organizationToSave.dataSourceId}:${organizationToSave.originId}" if (Organizations.findById(organizationId) == null) { log.info("Saving organization with ID '$organizationId'") Organizations.add(organizationToSave) } else { log.warn("Organization with ID $organizationId already exists!") } } } } private fun migratePlaces() { parseJsonArrayFromResource("${migrationsPath}places.json") { array -> array.map { val place = it.asJsonObject } } } private fun migrateKeywordSets() { parseJsonArrayFromResource("${migrationsPath}keyword-sets.json") { array -> array.map { val keywordSet = it.asJsonObject KeywordSetSave( name = MultiLangValue( fi = keywordSet["name"].asString, sv = null, en = null ), usage = keywordSet["usage"].asInt, origin = keywordSet["originId"].asString, dataSourceId = keywordSet["dataSourceId"].asString, image = keywordSet["image"].let { image -> if (image.isJsonNull) null else image.asInt }, organization = keywordSet["organization"].asString ) }.forEach { keywordSetToSave -> val keywordSetId = "${keywordSetToSave.dataSourceId}:${keywordSetToSave.origin}" if (KeywordSets.findById(keywordSetId) == null) { log.info("Saving keyword set with ID '$keywordSetId'") KeywordSets.add(keywordSetToSave) } else { log.warn("Keyword set with ID $keywordSetId already exists!") } } } } private fun migrateKeywords() { parseJsonArrayFromResource("${migrationsPath}keywords.json") { array -> array.map { val keyword = it.asJsonObject KeywordSave( id = keyword["id"].asString, name = MultiLangValue( fi = keyword["name"].asString, sv = null, en = null ), originId = keyword["originId"].asString, createdTime = DateTime(), lastModifiedTime = DateTime(), aggregate = false, createdById = null, dataSourceId = keyword["dataSourceId"].asString, lastModifiedById = null, imageId = null, deprecated = false, nEvents = 0, nEventsChanged = false, publisherId = keyword["publisherId"].asString ) }.forEach { keywordToSave -> val keywordSetId = "${keywordToSave.dataSourceId}:${keywordToSave.originId}" val keywordId = "$keywordSetId:${keywordToSave.id}" if (Keywords.findById(keywordId) == null) { log.info("Saving keyword with ID '$keywordId'") Keywords.add(keywordToSave) KeywordSetKeywords.add( keywordSetId, keywordId ) } else { log.warn("Keyword with ID $keywordId already exists!") } } } } private fun parseJsonArrayFromResource(resourceName: String, process: (JsonArray) -> Unit) { val jsonArray = javaClass.getResourceAsStream(resourceName)?.let { inputStream -> inputStream.use { jsonParser.parse(Readers.readInputStream(it)).asJsonArray } } process(jsonArray ?: JsonArray()) } }
0
Kotlin
0
1
f43b33d2c24bdbbc5375106b61bb9a2d2f9fa3aa
9,199
satakunta-events-api
MIT License
data/src/main/java/com/yvkalume/data/util/Extension.kt
yveskalume
356,004,687
false
null
package com.yvkalume.data.util
3
Kotlin
0
2
b0911c5bd75172708c52d86d3540958236d2c25e
32
eventcademy-old
Apache License 2.0
app/src/main/java/com/migueldev/floranotify/Cadastro.kt
MiguelDK17
775,581,227
false
{"Kotlin": 6465}
package com.migueldev.floranotify import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.userProfileChangeRequest import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.migueldev.floranotify.databinding.ActivityCadastroBinding class Cadastro: AppCompatActivity() { private lateinit var binding: ActivityCadastroBinding private lateinit var mAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCadastroBinding.inflate(layoutInflater) val view = binding.root val context = view.context setContentView(view) val edtSenha = binding.edtSenha.text val edtRepitaSenha = binding.edtRepitaSenha.text val btCriarConta = binding.btCriarConta btCriarConta.setOnClickListener { if (edtSenha.toString() == edtRepitaSenha.toString()){ criaConta() } else { Toast.makeText( context,"As senhas fornecidas não estão iguais" ,Toast.LENGTH_SHORT ).show() } } } private fun criaConta(){ val view = binding.root val nome = binding.edtNome.text.toString() val email = binding.edtEmail.text.toString() val password = binding.edtSenha.text.toString() mAuth = FirebaseAuth.getInstance() val db = Firebase.firestore mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener{ task -> if (task.isSuccessful){ //Se a criação da conta for um sucesso val uid = mAuth.currentUser?.uid val dados = hashMapOf( "id" to uid.toString(), "nome" to nome, "foto" to "foto" ) val profilerUpdates = userProfileChangeRequest { displayName = nome } val user = mAuth.currentUser user!!.updateProfile(profilerUpdates) .addOnCompleteListener{ task -> if (task.isSuccessful) { db.collection("Users") .document(uid.toString()) .set(dados) .addOnSuccessListener { document -> val intent = Intent(this, Principal::class.java) startActivity(intent) } } } } } .addOnFailureListener { error-> Toast.makeText( this,getString(R.string.verifique_conexao_internet) ,Toast.LENGTH_SHORT).show() } } }
0
Kotlin
0
0
0db0a1c38aba1ed88427e200be9c9cfc9e4b75cf
3,188
FloraNotify
Apache License 2.0
src/main/kotlin/com/github/jschlicht/multitenantdbbenchmark/strategy/PartitionHash.kt
jschlicht
744,785,772
false
{"Kotlin": 25061}
package com.github.jschlicht.multitenantdbbenchmark.strategy data object PartitionHash : Strategy("partition_hash") { override val simpleKeys = false override val denormalizedTenantId = true }
0
Kotlin
0
0
1b9fbeb637cad3e6cf3d9abf2eaeac07a8d03fcd
202
multi-tenant-db-benchmark
MIT License
app/src/main/java/fi/jara/thesis/thesisnative/listitems/data/filesystem/AssetsImageLoader.kt
jarkkos-crossplatform-comparison-thesis
145,214,257
false
null
package fi.jara.thesis.thesisnative.listitems.data.filesystem import android.content.Context import fi.jara.thesis.thesisnative.listitems.data.ImageLoader import kotlinx.coroutines.CoroutineScope import java.io.InputStream class AssetsImageLoader(private val context: Context): ImageLoader() { override fun getImageInputStream(uri: String): InputStream { return context.assets.open(uri) } }
0
Kotlin
0
0
4d9d05a3f097042e9d615b27a219787f609a7d7e
408
android-native
MIT License
src/commonMain/kotlin/csense/kotlin/logger/L.kt
csense-oss
136,911,995
false
null
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package csense.kotlin.logger import csense.kotlin.* import csense.kotlin.extensions.collections.* import csense.kotlin.extensions.primitives.* /** * Logging types / levels * A simple enumeration over the types of logging that can happen. * @property stringValue [String] the textual representation (useful for tags) */ public enum class LoggingLevel(public val stringValue: String) { Production("Production"), Error("Error"), Warning("Warning"), Debug("Debug"); /** * Gets the string representation. * @return String */ override fun toString(): String { return stringValue } } /** * The Basis logging function. */ public typealias LoggingFunctionType<T> = (tag: String, message: String, exception: Throwable?) -> T /** * The definition of a logging formatter. */ public typealias FunctionLoggerFormatter = (level: LoggingLevel, tag: String, message: String, exception: Throwable?) -> String /** * The L logger, capable of being instantiated, and inherited. * Contains all necessary logging features. [LoggingLevel] channels, each capable of being enabled / disabled. * and a list of listeners for that logging level. * The main instance is called "L" */ public open class LLogger { /** * controls whenever production logging is allowed * default is true */ public var isProductionLoggingAllowed: Boolean = true /** * Controls whenever error logging is allowed. * default is true */ public var isErrorLoggingAllowed: Boolean = true /** * controls whenever warning logging is allowed * default is true */ public var isWarningLoggingAllowed: Boolean = true /** * controls whenever debug logging is allowed * default is true */ public var isDebugLoggingAllowed: Boolean = true /** * Production level loggers; the intention here is to allow this logging in production. * its controlled separate from all the other logging flags. */ public var productionLoggers: MutableList<LoggingFunctionType<Any>> = mutableListOf() /** * */ public var errorLoggers: MutableList<LoggingFunctionType<Any>> = mutableListOf() /** * */ public var warningLoggers: MutableList<LoggingFunctionType<Any>> = mutableListOf() /** * */ public var debugLoggers: MutableList<LoggingFunctionType<Any>> = mutableListOf() /** * Controls whenever logging is allowed. * This turns on all the other logging features * INCLUDING productionLogging (so if you want to turn off all logs, except production logging * the advice is to set isAllowedLogging(false); and then explicit enable productionLogging.) */ public fun isLoggingAllowed(enable: Boolean) { isProductionLoggingAllowed = enable isErrorLoggingAllowed = enable isWarningLoggingAllowed = enable isDebugLoggingAllowed = enable } //region log prod /** * A production logging channel. * purpose is to allow logging even in production, such as very specific errors,warnings, assertions, * and other well though logs. any regular library or none application code shall not use this, * as this is for application level only. * @param tag [String] * @param message [String] * @param exception [Throwable]? */ public fun logProd(tag: String, message: String, exception: Throwable?): Unit = ifMayLogProduction { productionLoggers.invokeEachWith(tag, message, exception) } public fun logProd(tag: String, message: String): Unit = logProd(tag, message, null) /** * Lazy logging where, computing the message is non "trivial" or you do not want to pay for creating / computing * it if it's not going to get logged. * @param tag [String] * @param messageFnc [Function0R]<[String]> * @param exception [Throwable]? */ public fun logProdLazy(tag: String, messageFnc: Function0R<String>, exception: Throwable?): Unit = ifMayLogProduction { productionLoggers.invokeEachWithLoggingLazy(tag, messageFnc, exception) } public fun logProdLazy(tag: String, messageFnc: Function0R<String>): Unit = logProdLazy(tag, messageFnc, null) //endregion //region log error /** * An error logging channel * this logs messages as the level "Error", meant for "bad things", eg application / library errors, * logging important messages (due to issues / bugs), or alike. * @param tag [String] a categorization of the log, should be 20 characters or fewer * @param message [String] the message to be logged can be as long as needed, and contain control characters * (newlines, tabs ect) * @param exception [Throwable] a stacktrace of some sort of error / exception. * * Requires the isErrorLoggingAllowed to be true to log anything * */ public fun error(tag: String, message: String, exception: Throwable?): Unit = ifMayLogError { errorLoggers.invokeEachWith(tag, message, exception) } public fun error(tag: String, message: String): Unit = error(tag, message, null) /** * * @param tag [String] * @param messageFnc [Function0R]<[String]> * @param exception [Throwable]? */ public fun errorLazy(tag: String, messageFnc: Function0R<String>, exception: Throwable?): Unit = ifMayLogError { errorLoggers.invokeEachWithLoggingLazy(tag, messageFnc, exception) } public fun errorLazy(tag: String, messageFnc: Function0R<String>): Unit = errorLazy(tag, messageFnc, null) //endregion //region log warning /** * A warning logging channel * this logs messages as the level "Warning", mean for not fatal / very bad things, * but things that are usually not bound to happen and should not happen. * @param tag [String] * @param message [String] * @param exception [Throwable]? */ public fun warning(tag: String, message: String, exception: Throwable?): Unit = ifMayLogWarning { warningLoggers.invokeEachWith(tag, message, exception) } public fun warning(tag: String, message: String): Unit = warning(tag, message, null) /** * * @param tag [String] * @param messageFnc [Function0R]<[String]> * @param exception [Throwable]? * */ public fun warningLazy(tag: String, messageFnc: Function0R<String>, exception: Throwable?): Unit = ifMayLogWarning { warningLoggers.invokeEachWithLoggingLazy(tag, messageFnc, exception) } public fun warningLazy(tag: String, messageFnc: Function0R<String>): Unit = warningLazy(tag, messageFnc, null) //endregion //region log debug /** * Debug level logging channel. * @param tag [String] * @param message [String] * @param exception [Throwable]? * */ public fun debug(tag: String, message: String, exception: Throwable? = null): Unit = ifMayLogDebug { debugLoggers.invokeEachWith(tag, message, exception) } public fun debug(tag: String, message: String): Unit = debug(tag, message, null) /** * A lazy debug logging * @param tag [String] * @param messageFnc [Function0R]<[String]> * @param exception [Throwable]? * */ public fun debugLazy(tag: String, messageFnc: Function0R<String>, exception: Throwable?): Unit = ifMayLogDebug { debugLoggers.invokeEachWithLoggingLazy(tag, messageFnc, exception) } public fun debugLazy(tag: String, messageFnc: Function0R<String>): Unit = debugLazy(tag, messageFnc, null) //endregion //region Util functions /** * if production logging is allowed, runs the given action. * @param action [EmptyFunction] */ private fun ifMayLogProduction(action: EmptyFunction) { isProductionLoggingAllowed.onTrue(action) } /** * if error logging is allowed, runs the given action. * @param action [EmptyFunction] */ private fun ifMayLogError(action: EmptyFunction) { isErrorLoggingAllowed.onTrue(action) } /** * if warning logging is allowed, runs the given action. * @param action [EmptyFunction] */ private fun ifMayLogWarning(action: EmptyFunction) { isWarningLoggingAllowed.onTrue(action) } /** * if debug logging is allowed, runs the given action. * @param action [EmptyFunction] */ private fun ifMayLogDebug(action: EmptyFunction) { isDebugLoggingAllowed.onTrue(action) } //endregion } /** * Invokes each listener of a logging type function with a lazily computed message. * Skips the message if there are no loggers. * @receiver [Iterable]<T> * @param tag [String] * @param messageFnc [Function0R]<String> * @param exception [Throwable]? */ public inline fun <T : LoggingFunctionType<*>> Iterable<T>.invokeEachWithLoggingLazy( tag: String, messageFnc: Function0R<String>, exception: Throwable? ): Unit = skipIfEmptyOr { invokeEachWith(tag, messageFnc(), exception) } /** * Container for all shared logging. * Shared single instance. */ public object L : LLogger()
1
Kotlin
0
2
49113dd6b2cb1e18992d07faa1e0305d18f766f4
9,383
csense-kotlin
MIT License
app/src/main/java/com/bengisusahin/wordwander/di/WordRepositoryModule.kt
bengisusaahin
855,798,311
false
{"Kotlin": 22839}
package com.bengisusahin.wordwander.di import com.bengisusahin.wordwander.data.datasource.WordDataSource import com.bengisusahin.wordwander.data.repository.WordRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object WordRepositoryModule { @Provides @Singleton fun provideDataSource() :WordDataSource { return WordDataSource } @Provides @Singleton fun provideWordRepository( wordDataSource: WordDataSource ): WordRepository { return WordRepository(wordDataSource) } }
0
Kotlin
0
0
a564ebba2be2256d3a6aad432ef1c11195ef1860
690
WordWander
MIT License
app/src/main/java/com/example/scankitdemo/core_example/FormActivity.kt
albertpatera
690,790,271
false
{"Kotlin": 328450, "Java": 78652}
package com.example.scankitdemo.core import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.os.Environment import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.* import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.scankitdemo.MainActivity import com.example.scankitdemo.R //import com.example.scankitdemo.R import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVParser import org.apache.poi.hssf.usermodel.HSSFCell import org.apache.poi.hssf.usermodel.HSSFRow import org.apache.poi.hssf.usermodel.HSSFSheet import org.apache.poi.hssf.usermodel.HSSFWorkbook import org.apache.poi.ss.usermodel.Workbook import java.io.File import java.io.FileOutputStream import java.nio.file.Files import java.nio.file.Paths class FormActivity : Activity(), ActivityCompat.OnRequestPermissionsResultCallback { private lateinit var alert : AlertDialog private lateinit var textViewLabel: TextView private lateinit var editTextView: TextView private lateinit var editTextViewEdit: EditText private lateinit var editTextViewEditText: TextView private lateinit var addArray: ArrayList<String> private lateinit var save: Button private lateinit var show: ListView lateinit var arrayAdapter : ArrayAdapter<String> lateinit var options: Data private lateinit var upload : ImageButton private lateinit var barcodeValue : TextView // private lateinit var arrayAdapter: ArrayAdapter<String> private lateinit var finishBtn : Button private lateinit var data: Data private lateinit var btnSaveBG : Button private lateinit var excelFile : WriteExcel private val filePathRender = File(Environment.getExternalStorageDirectory().toString() + "/Download", "/final_cutz_down.xls") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_form) //return // finishBtn = findViewById(R.id.btn_complete) //return alert = AlertDialog.Builder(this).create() textViewLabel = findViewById(R.id.textViewBar) editTextView = findViewById(R.id.textViewBar) editTextViewEdit = findViewById(R.id.editTextTextPersonName) editTextViewEditText = findViewById(R.id.editTextTextPersonName) show = findViewById(R.id.listView) // return save = findViewById(R.id.button2) //btnSaveBG = findViewById(R.id.btn_complete) addArray = ArrayList() options = Data() // return // barcodeValue = findViewById(R.id.textViewBar) textViewLabel.text = intent.getStringExtra("barcodeValueTemp").toString() //return //upload = findViewById(R.id.leaveBtn) // finishBtn.visibility = View.VISIBLE //return data = Data() // return //excelFile = WriteExcel() var workbook: Workbook = HSSFWorkbook() //var fileOutputStream = FileOutputStream(filePathRender) //var tv = TextView(this) // return save.setOnClickListener { var getInput : String = editTextViewEdit.text.toString() if(addArray.contains(getInput)) { Toast.makeText(this, "Item added", Toast.LENGTH_LONG).show(); finishBtn.visibility = View.VISIBLE } else if (getInput == null || getInput.trim() == "") { Toast.makeText(this, "Input field is empty ", Toast.LENGTH_LONG).show(); } else { addArray.add(getInput) arrayAdapter= ArrayAdapter(this@FormActivity, android.R.layout.simple_expandable_list_item_1, addArray); show.setAdapter(arrayAdapter) //editTextViewEdit.setText(" ") finishBtn.visibility = View.VISIBLE return@setOnClickListener try { //options.loadData(this, addArray.last(), "/output.csv") } catch (e: Exception) { alert.setMessage(e.message) alert.show() } Toast.makeText(applicationContext, "Item added", Toast.LENGTH_LONG).show() } } upload.setOnClickListener { Toast.makeText(this, "pressed", Toast.LENGTH_LONG).show() //return@setOnClickListener //data.getDataFromCSV(this, workbook) try { //excelFile.writeExcel(this) } catch (e: Exception) { alert.setMessage(e.message) alert.show() } try { startActivity(Intent(this, FinalRenderActivity::class.java)) } catch (e : Exception) { Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show() } } editTextViewEdit.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { //TODO("Not yet implemented") //editTextViewEdit.background = ContextCompat.getDrawable(this, R.drawable.if_is_empty); if(count == 0) { finishBtn.visibility = View.INVISIBLE } else { finishBtn.visibility = View.VISIBLE } } override fun afterTextChanged(s: Editable?) { //TODO("Not yet implemented") } }) /*finishBtn.setOnClickListener { var intentActivityRes = Intent(this@FormActivity, FinalRenderActivity::class.java) try { data.alertCancelOrExit(this@FormActivity, intentActivityRes) //startActivity(intentActivityRes) //data.alertShow(applicationContext) //data.alertShow(this) } catch (e : Exception) { alert.setMessage(e.message) alert.show() } }*/ /*finishBtn.setOnClickListener { var getInput : String = editTextViewEdit.text.toString() if(addArray.contains(getInput)) { Toast.makeText(this, "Item added", Toast.LENGTH_LONG).show(); //startActivity(Intent(this, MainActivity::class.java)) finishBtn.visibility = View.VISIBLE // startActivity(Intent(this@FormActivity, FinalRenderActivity::class.java)) var activityContinue = Intent(this@FormActivity, FormActivity::class.java) data.alertCancelOrExit(this, activityContinue) } else if (getInput == null || getInput.trim() == "") { Toast.makeText(this, "Input field is empty ", Toast.LENGTH_LONG).show(); editTextViewEdit.background = ContextCompat.getDrawable(this, R.drawable.if_is_empty); } else { addArray.add(getInput) arrayAdapter= ArrayAdapter(this@FormActivity, android.R.layout.simple_expandable_list_item_1, addArray); show.setAdapter(arrayAdapter) //editTextViewEdit.setText(" ") try { options.loadData(this, addArray.last(), "/output.csv") } catch (e: Exception) { alert.setMessage(e.message) alert.show() } Toast.makeText(applicationContext, "Item from edit added", Toast.LENGTH_LONG).show() options.loadData(this, ";\n", "/output.csv") //startActivity(Intent(this@FormActivity, MainActivity::class.java)) //requestPermissions() fun decodePermission(requestCode: Int) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE), requestCode ) } fun generatePermission(requestCode: Int) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), requestCode ) } fun requestPermission(requestCode: Int, mode: Int) { if (mode == MainActivity.DECODE) { decodePermission(requestCode) } else if (mode == MainActivity.GENERATE) { generatePermission(requestCode) } } // requestPermissions(MainActivity.DEFINED_CODE, MainActivity.DECODE) try { // requestPermission(MainActivity.CAMERA_REQ_CODE, MainActivity.DECODE) } catch (e : Exception) { alert.setMessage(e.message) alert.show() } //startActivity(Intent(this, FinalRenderActivity::class.java)) } }*/ editTextViewEdit.setOnClickListener { var getInput : String = editTextViewEdit.text.toString() if(addArray.contains(getInput)) { Toast.makeText(this, "Item added", Toast.LENGTH_LONG).show(); //startActivity(Intent(this, MainActivity::class.java)) finishBtn.visibility = View.VISIBLE // startActivity(Intent(this@FormActivity, FinalRenderActivity::class.java)) startActivity(Intent(this@FormActivity, MainActivity::class.java)) } else if (getInput == null || getInput.trim() == "") { Toast.makeText(this, "Input field is empty ", Toast.LENGTH_LONG).show(); } else { addArray.add(getInput) arrayAdapter= ArrayAdapter(this@FormActivity, android.R.layout.simple_expandable_list_item_1, addArray); show.setAdapter(arrayAdapter) editTextViewEdit.setText(" ") try { options.loadData(this, addArray.last(), "/output.csv") } catch (e: Exception) { alert.setMessage(e.message) alert.show() } Toast.makeText(applicationContext, "Item from edit added", Toast.LENGTH_LONG).show() options.loadData(this, ";\n", "/output.csv") //startActivity(Intent(this@FormActivity, MainActivity::class.java)) //requestPermissions() fun decodePermission(requestCode: Int) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE), requestCode ) } fun generatePermission(requestCode: Int) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), requestCode ) } fun requestPermission(requestCode: Int, mode: Int) { if (mode == MainActivity.DECODE) { decodePermission(requestCode) } else if (mode == MainActivity.GENERATE) { generatePermission(requestCode) } } // requestPermissions(MainActivity.DEFINED_CODE, MainActivity.DECODE) try { // requestPermission(MainActivity.CAMERA_REQ_CODE, MainActivity.DECODE) } catch (e : Exception) { alert.setMessage(e.message) alert.show() } //startActivity(Intent(this, FinalRenderActivity::class.java)) } } fun buttonRender(view: View) { alert.setMessage("rrr") alert.show() // return //return val headers = arrayOf("PLU") var rows = mutableListOf("12", "777", "a", "b") val workbook: Workbook = HSSFWorkbook() var fileOutputStream = FileOutputStream(filePathRender) var tv = TextView(this) val hssfWorkbook = HSSFWorkbook() val hssfSheet: HSSFSheet = hssfWorkbook.createSheet("Custom Sheet") val hssfRow: HSSFRow = hssfSheet.createRow(0) val hssfCell: HSSFCell = hssfRow.createCell(0) hssfCell.setCellValue("rrr") var rowCount = 0; try { /*if (!filePathRender.exists()) { filePathRender.createNewFile() alert.setMessage("ffdf") alert.show() } else { alert.setMessage("exists") alert.show() }*/ //val bufferedReader = BufferedReader(File(Environment.getExternalStorageDirectory().toString(), "/null.csv")); val bufferedReader = Files.newBufferedReader( Paths.get( Environment.getExternalStorageDirectory().toString() + "/Download//output.csv" ) ); var csvParser = CSVParser(bufferedReader, CSVFormat.DEFAULT) var del = "name, 2012, 2017".split(",").toTypedArray() try { var row = hssfSheet.createRow(del.count()) var cell = row.createCell(1) for (pol in csvParser) { tv.text = tv.text.toString() + del.contentToString() + pol.get(0) + "\n" cell?.setCellValue(tv.text.toString() + del.contentToString() + pol.get(0)) } } catch (e : Exception) { alert.setMessage(e.message) alert.show() } alert.setMessage(tv.text.toString()) alert.show() for (rn in rows.indices) { //val r: Row = hssfSheet.createRow(++rowCount) var del = "name, 2012, 2017".split(",").toTypedArray() try { var row = hssfSheet.createRow(del.count()) var cell = row.createCell(1) for (pol in csvParser) { tv.text = tv.text.toString() + del.contentToString() + pol.get(0) + "\n" cell?.setCellValue(tv.text.toString() + del.contentToString() + pol.get(0)) } } catch (e : Exception) { alert.setMessage(e.message) alert.show() } // val header: Row = sheet.createRow(0) // r.createCell(0).setCellValue("PLU") //r.createCell(1).setCellValue("KS") //r.createCell(2).setCellValue("Header3") //val cell: Cell = r.createCell(++columnCount) // tv.text = tv.text.toString() + r.createCell(0).setCellValue("12804") //tv.text = tv.text.toString() + r.createCell(1).setCellValue("10") //r.createCell(3).setCellValue("Header4") // alert.setMessage(tv.text) //alert.show() hssfWorkbook.write(fileOutputStream) // hssfWorkbook.write(headers[rn]) if (fileOutputStream != null) { // fileOutputStream.flush() //fileOutputStream.close() } } try { val fileOut = FileOutputStream(filePathRender) workbook.write(fileOut) fileOut.close() //Toast.makeText(applicationContext, "super je to tady :)))", Toast.LENGTH_LONG).show() } catch (e: Exception) { alert.setMessage(e.message) alert.show() } catch (e: Exception) { alert.setMessage(e.message) alert.show() } //alert.setMessage(tv.text.toString(ú + "ahoj") //alert.show() //var del = tv.text.split(';') // alert.setMessage(del.contentToString()) alert.show() //for (pol_ in csvParser) return /*for (rn in headers.indices) { val r: Row = hssfSheet.createRow(++rowCount) // val header: Row = sheet.createRow(0) tv.text = tv.text.toString() + r.createCell(0).setCellValue("PLU") tv.text = tv.text.toString() + r.createCell(1).setCellValue("KS") //r.createCell(2).setCellValue("Header3") // tv.text = tv.text.toString() + r.createCell(0).setCellValue("12804") // tv.text = tv.text.toString() + r.createCell(1).setCellValue("10") r.createCell(0).setCellValue("PLU") r.createCell(1).setCellValue("KS") //r.createCell(3).setCellValue("Header4") // hssfWorkbook.write(fileOutputStream) // hssfWorkbook.write(headers[rn]) if (fileOutputStream != null) { //fileOutputStream.flush() //fileOutputStream.close() } }*/ // var columnCount = 0; } catch (e : Exception) { alert.setMessage(e.message) alert.show() } } } override fun onBackPressed() { } }
0
Kotlin
0
0
ac936d0b90979cdfd5c0b7873c525e81ed2a11e9
18,233
barCodeScanner
Apache License 2.0
app/src/main/java/com/prisma/prismavi/permissions/PermissionManeger.kt
PrismaVision
846,809,499
false
{"Kotlin": 8146}
package com.prisma.prismavi.permissions import android.Manifest import android.app.AlertDialog import android.content.pm.PackageManager import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import com.prisma.prismavi.MainActivity class PermissionManager(private val activity: MainActivity) { private val requestPermissionLauncher = activity.registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { activity.onPermissionGranted() } else { activity.onPermissionDenied() } } fun isCameraPermissionGranted(): Boolean { return ContextCompat.checkSelfPermission( activity, Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED } fun requestCameraPermission() { requestPermissionLauncher.launch(Manifest.permission.CAMERA) } fun showPermissionDeniedDialog() { AlertDialog.Builder(activity) .setTitle("Permissão Necessária") .setMessage("A permissão para usar a câmera é necessária para o funcionamento do aplicativo.") .setPositiveButton("Tentar Novamente") { _, _ -> requestCameraPermission() } .setNegativeButton("Sair") { _, _ -> activity.finish() } .show() } }
1
Kotlin
1
0
0e8f1c4e76db0f66ce4823f6b8d118b310f50269
1,383
Prisma-VI
MIT License
src/main/kotlin/server/RequestType.kt
Liu-Junyan
392,420,224
false
null
package server import kotlinx.serialization.Serializable @Serializable data class Message(val raw_message: String, val message_type: String, val user_id: Long, val group_id: Long? = null)
0
Kotlin
0
0
c8aa5f97461a9693720bd3c0326afd9c36f32dd9
189
cq_backend
MIT License
app/src/androidTest/java/com/santansarah/scan/di/TestUsecases.kt
santansarah
588,753,371
false
null
package com.santansarah.scan.di import com.santansarah.scan.domain.usecases.ParseDescriptor import com.santansarah.scan.domain.usecases.ParseNotification import com.santansarah.scan.domain.usecases.ParseRead import com.santansarah.scan.domain.usecases.ParseScanResult import com.santansarah.scan.domain.usecases.ParseService import com.santansarah.scan.local.room.TestBleDatabase import org.koin.dsl.module val testUsecasesModule = module { scope<TestBleDatabase> { scoped { ParseScanResult(get()) } scoped { ParseService(get()) } } single { ParseRead() } single { ParseNotification() } single { ParseDescriptor() } }
0
Kotlin
1
16
9e76dab6a244e1eded2480e5e19a812612698326
659
ble-scanner
MIT License
app/src/main/java/levkaantonov/com/study/notice/screens/start/StartFragment.kt
levkaantonov
335,081,649
false
null
package levkaantonov.com.study.notice.screens.start import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import levkaantonov.com.study.notice.R import levkaantonov.com.study.notice.databinding.FragmentStartBinding import levkaantonov.com.study.notice.utils.* class StartFragment : Fragment() { private var _binding: FragmentStartBinding? = null private val mBinding get() = _binding!! private lateinit var mViewModel: StartFragmentVewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentStartBinding.inflate(layoutInflater, container, false) return mBinding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onStart() { super.onStart() mViewModel = ViewModelProvider(this).get(StartFragmentVewModel::class.java) if(AppPreference.getInitUser()){ mViewModel.initDb(AppPreference.getDbType()){ APP_ACTIVITY.navController.navigate(R.id.action_startFragment_to_mainFragment) } }else initialization() } private fun initialization() { mBinding.startBtnRoom.setOnClickListener { mViewModel.initDb(TYPE_ROOM){ AppPreference.setInitUser(true) AppPreference.setDbType(TYPE_ROOM) APP_ACTIVITY.navController.navigate(R.id.action_startFragment_to_mainFragment) } } mBinding.startBtnFb.setOnClickListener { mBinding.emailInput.visibility = View.VISIBLE mBinding.passwordInput.visibility = View.VISIBLE mBinding.startBtnLogin.visibility = View.VISIBLE mBinding.startBtnLogin.setOnClickListener { val email = mBinding.emailInput.text.toString() val password = mBinding.passwordInput.text.toString() if(email.isNotEmpty() && password.isNotEmpty()){ EMAIL = email PASSWORD = <PASSWORD> mViewModel.initDb(TYPE_FIREBASE){ AppPreference.setInitUser(true) AppPreference.setDbType(TYPE_FIREBASE) APP_ACTIVITY.navController.navigate(R.id.action_startFragment_to_mainFragment) } }else{ showToast(getString(R.string.bad_enter_toast)) } } } } }
0
Kotlin
0
0
fefc4b155b5ceacb4c055362be2377658c4cbdb2
2,697
Notice
MIT License
wear/src/main/java/com/devlomi/prayerwatchface/ui/calculationmethods/CalculationMethodsScreen.kt
3llomi
569,805,694
false
{"Kotlin": 353465}
package com.devlomi.prayerwatchface.ui.calculationmethods import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.input.rotary.onRotaryScrollEvent import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.wear.compose.foundation.ExperimentalWearFoundationApi import androidx.wear.compose.foundation.lazy.AutoCenteringParams import androidx.wear.compose.foundation.lazy.ScalingLazyColumn import androidx.wear.compose.foundation.lazy.itemsIndexed import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState import androidx.wear.compose.foundation.rememberActiveFocusRequester import androidx.wear.compose.material.Icon import androidx.wear.compose.material.PositionIndicator import androidx.wear.compose.material.Scaffold import androidx.wear.compose.material.Text import androidx.wear.compose.material.ToggleChip import androidx.wear.compose.material.ToggleChipDefaults import kotlinx.coroutines.launch @OptIn(ExperimentalWearFoundationApi::class, ExperimentalWearFoundationApi::class) @Composable fun CalculationMethodsScreen(viewModel: CalculationMethodsViewModel) { val listState = rememberScalingLazyListState() val focusRequester = rememberActiveFocusRequester() val coroutineScope = rememberCoroutineScope() val items by viewModel.items Scaffold( positionIndicator = { PositionIndicator(scalingLazyListState = listState) } ) { ScalingLazyColumn( modifier = Modifier .onRotaryScrollEvent { coroutineScope.launch { listState.scrollBy(it.verticalScrollPixels) } true } .focusRequester(focusRequester) .focusable(), autoCentering = AutoCenteringParams(0), state = listState) { itemsIndexed(items) { index, item -> val checked = item.type == viewModel.currentCalculationMethod.value ToggleChip( modifier = Modifier.fillMaxWidth(), checked = checked, onCheckedChange = { viewModel.itemClicked(item) }, label = { Text( modifier = Modifier.padding(top = 4.dp, bottom = 4.dp), text = item.title, fontSize = 12.sp ) }, toggleControl = { Icon( imageVector = ToggleChipDefaults.radioIcon(checked = checked), contentDescription = null ) }) } } } }
2
Kotlin
2
9
d42a6c69d5013177274d127484696173d67ee33d
3,314
PrayerWatchFace
Apache License 2.0
app/src/main/java/com/lucidsoftworksllc/taxidi/main_activities/driver_user/fragments/DriverMapFragment.kt
Wakamoly
331,492,101
false
null
package com.lucidsoftworksllc.taxidi.main_activities.driver_user.fragments import android.annotation.SuppressLint import android.content.pm.PackageManager import android.content.res.Resources import android.graphics.Color import android.os.Bundle import android.os.Looper import android.util.Log import android.view.* import android.widget.Toast import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.* import com.lucidsoftworksllc.taxidi.R import com.lucidsoftworksllc.taxidi.base.BaseFragment import com.lucidsoftworksllc.taxidi.databinding.DialogDriverAtDropoffBinding import com.lucidsoftworksllc.taxidi.databinding.DialogStartDriveBinding import com.lucidsoftworksllc.taxidi.databinding.DriverMapFragmentBinding import com.lucidsoftworksllc.taxidi.main_activities.driver_user.fragments.repositories.DriverMapRepository import com.lucidsoftworksllc.taxidi.main_activities.driver_user.fragments.repositories.api.DriverMapAPI import com.lucidsoftworksllc.taxidi.main_activities.driver_user.fragments.repositories.api.DriverMapsView import com.lucidsoftworksllc.taxidi.main_activities.driver_user.fragments.view_models.DriverMapViewModel import com.lucidsoftworksllc.taxidi.main_activities.driver_user.list_adapters.CompanyMarkerCustomInfoWindow import com.lucidsoftworksllc.taxidi.others.models.server_responses.CompanyMapMarkerModel import com.lucidsoftworksllc.taxidi.utils.* import com.lucidsoftworksllc.taxidi.utils.Extensions.authToken import com.lucidsoftworksllc.taxidi.utils.Extensions.fcmToken import com.lucidsoftworksllc.taxidi.utils.Extensions.setTitle import com.lucidsoftworksllc.taxidi.utils.Extensions.snackbar import com.lucidsoftworksllc.taxidi.utils.Extensions.toastLong import com.yarolegovich.lovelydialog.LovelyCustomDialog import java.util.* class DriverMapFragment : BaseFragment<DriverMapViewModel, DriverMapFragmentBinding, DriverMapRepository>(), DriverMapsView { private lateinit var googleMap: GoogleMap private var fusedLocationProviderClient: FusedLocationProviderClient? = null private lateinit var locationCallback: LocationCallback private var currentLatLng: LatLng? = null private var pickUpLatLng: LatLng? = null private var dropLatLng: LatLng? = null private val nearbyCompanyMarkerList = arrayListOf<Marker>() private var destinationMarker: Marker? = null private var originMarker: Marker? = null private var greyPolyLine: Polyline? = null private var blackPolyline: Polyline? = null private var previousLatLngFromServer: LatLng? = null private var currentLatLngFromServer: LatLng? = null private var movingDriverMarker: Marker? = null private var reInitNearby = false private var companyMapMarkerModel : CompanyMapMarkerModel? = null companion object { private const val TAG = "MapsActivity" private const val LOCATION_PERMISSION_REQUEST_CODE = 999 private const val PICKUP_REQUEST_CODE = 1 private const val DROP_REQUEST_CODE = 2 } override fun onCreate(savedInstanceState: Bundle?) { setTitle(getString(R.string.map_fragment_name)) super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewModel = viewModel binding.lifecycleOwner = this setTitle(getString(R.string.map_fragment_name)) val mapFragment = childFragmentManager.findFragmentById(R.id.driver_map) as SupportMapFragment mapFragment.getMapAsync(callback) setUpClickListener() setupObservers() } private fun setupObservers() { viewModel.viewState.observe(viewLifecycleOwner, { when (it) { 1 -> { informCompanyBooked() } 2 -> { showPath(viewModel.pickUpPath.value?.toList()) } 3 -> { updateSimulatedDriverLocation(viewModel.driverLocation.value) } 4 -> { informDriverIsArriving() } 5 -> { informDriverArrived() } 6 -> { informTripStart() } 7 -> { informTripEnd() } 8 -> { showRoutesNotAvailableError() } 9 -> { showDirectionApiFailedError(viewModel.directionApiFailedError.value) } 10 -> { showNearbyCompanies(viewModel.nearbyCompanies.value) } 11 -> { showSampleTripPath(viewModel.sampleTripPath.value) } 12 -> { generateAndShowPickupTicket() } 13 -> { generateAndShowDropoffTicket() } } }) } private fun generateAndShowDropoffTicket() { if (companyMapMarkerModel != null) { val dialogBinding = DialogDriverAtDropoffBinding.inflate(layoutInflater) dialogBinding.model = companyMapMarkerModel binding.executePendingBindings() val dialog = LovelyCustomDialog(requireContext()) dialog.setView(dialogBinding.root) .setTopColorRes(R.color.primaryColor) .setIcon(R.drawable.ic_baseline_local_shipping_64) .setCancelable(false) .setListener(dialogBinding.buttonStartDrive.id) { dialog.dismiss() viewModel.finishedDropOff() } .show() } else { requireView().snackbar("Map marker info null!") } } private fun generateAndShowPickupTicket() { if (companyMapMarkerModel != null) { // TODO: 2/16/2021 Make a dialog layout for pickup val dialogBinding = DialogDriverAtDropoffBinding.inflate(layoutInflater) dialogBinding.model = companyMapMarkerModel binding.executePendingBindings() val dialog = LovelyCustomDialog(requireContext()) dialog.setView(dialogBinding.root) .setTopColorRes(R.color.primaryColor) .setIcon(R.drawable.ic_baseline_local_shipping_64) .setCancelable(false) .setListener(dialogBinding.buttonStartDrive.id) { dialog.dismiss() viewModel.finishedPickup() } .show() } else { requireView().snackbar("Map marker info null!") } } private fun showSampleTripPath(values: ArrayList<LatLng>?) { values?.let { showPath(values) } } private fun setUpClickListener() { binding.tripDismissButton.setOnClickListener { binding.tripDetailAccessWindowMotion.transitionToStart() } binding.tripDetailsButton.setOnClickListener { if (companyMapMarkerModel != null) { binding.tripDetailAccessWindowMotion.transitionToStart() val dialogBinding = DialogStartDriveBinding.inflate(layoutInflater) dialogBinding.model = companyMapMarkerModel binding.executePendingBindings() val dialog = LovelyCustomDialog(requireContext()) dialog.setView(dialogBinding.root) .setTopColorRes(R.color.primaryColor) .setIcon(R.drawable.ic_baseline_local_shipping_64) .setListener(dialogBinding.buttonCancel.id) { dialog.dismiss() } .setListener(dialogBinding.buttonStartDrive.id) { dialog.dismiss() viewModel.requestCompany(companyMapMarkerModel!!.latLng, companyMapMarkerModel!!.toLatLng) } .show() } else { requireView().snackbar("Map marker info null!") } } } private fun moveCamera(latLng: LatLng?) { if (::googleMap.isInitialized){ googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)) } } private fun animateCamera(latLng: LatLng?) { val cameraPosition = CameraPosition.Builder().target(latLng).zoom(15.5f).build() if (::googleMap.isInitialized){ googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } } private fun centerCamera(latLng: LatLng?) { val cameraPosition = CameraPosition.Builder().target(latLng).zoom(15.5f).build() if (::googleMap.isInitialized){ googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } } private fun addCompanyMarkerAndGet(company: CompanyMapMarkerModel): Marker { val bitmapDescriptor = BitmapDescriptorFactory.fromBitmap( MapUtils.getBusinessBitmap( requireContext() ) ) return googleMap.addMarker( MarkerOptions().position(company.latLng).flat(true).icon(bitmapDescriptor) ).apply { tag = company } } private fun addOriginDestinationMarkerAndGet(latLng: LatLng): Marker { val bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(MapUtils.getDestinationBitmap()) return googleMap.addMarker( MarkerOptions().position(latLng).flat(true).icon(bitmapDescriptor) ) } private fun setCurrentLocationAsPickUp() { pickUpLatLng = currentLatLng //pickUpTextView.text = getString(R.string.current_location) } @SuppressLint("MissingPermission") private fun enableMyLocationOnMap() { googleMap.setPadding(0, ViewUtils.dpToPx(48f), 0, 0) googleMap.isMyLocationEnabled = true } @SuppressLint("MissingPermission") private fun setUpLocationListener() { fusedLocationProviderClient = FusedLocationProviderClient(requireActivity()) // for getting the current location update after every 2 seconds val locationRequest = LocationRequest().setInterval(2000).setFastestInterval(2000) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { super.onLocationResult(locationResult) if (currentLatLng == null) { val location = locationResult.locations.first() currentLatLng = LatLng(location.latitude, location.longitude) setCurrentLocationAsPickUp() enableMyLocationOnMap() moveCamera(currentLatLng) animateCamera(currentLatLng) if (viewModel.nearbyCompanies.value != null && viewModel.nearbyCompanies.value!!.isNotEmpty()){ showNearbyCompanies(viewModel.nearbyCompanies.value) } else { viewModel.requestNearbyCompanies(currentLatLng!!) } } // Few more things we can do here: // For example: Update the location of user on server } } fusedLocationProviderClient?.requestLocationUpdates( locationRequest, locationCallback, Looper.myLooper() ) } private fun reset() { nearbyCompanyMarkerList.forEach { it.remove() } nearbyCompanyMarkerList.clear() previousLatLngFromServer = null currentLatLngFromServer = null if (currentLatLng != null) { moveCamera(currentLatLng) animateCamera(currentLatLng) setCurrentLocationAsPickUp() viewModel.requestNearbyCompanies(currentLatLng!!) } movingDriverMarker?.remove() greyPolyLine?.remove() blackPolyline?.remove() originMarker?.remove() destinationMarker?.remove() dropLatLng = null greyPolyLine = null blackPolyline = null originMarker = null destinationMarker = null movingDriverMarker = null } override fun onStart() { super.onStart() if (currentLatLng == null) { when { PermissionUtils.isAccessFineLocationGranted(requireContext()) -> { when { PermissionUtils.isLocationEnabled(requireContext()) -> { setUpLocationListener() } else -> { PermissionUtils.showGPSNotEnabledDialog(requireContext()) } } } else -> { PermissionUtils.requestAccessFineLocationPermission( requireActivity(), LOCATION_PERMISSION_REQUEST_CODE ) } } } } override fun onDestroy() { fusedLocationProviderClient?.removeLocationUpdates(locationCallback) super.onDestroy() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { LOCATION_PERMISSION_REQUEST_CODE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { when { PermissionUtils.isLocationEnabled(requireContext()) -> { setUpLocationListener() } else -> { PermissionUtils.showGPSNotEnabledDialog(requireContext()) } } } else { Toast.makeText( requireContext(), getString(R.string.location_permission_not_granted), Toast.LENGTH_LONG ).show() } } } } private val callback = OnMapReadyCallback { googleMap -> this.googleMap = googleMap val companyInfoWindow = CompanyMarkerCustomInfoWindow(requireContext()) googleMap.setInfoWindowAdapter(companyInfoWindow) if (reInitNearby) { showNearbyCompanies(viewModel.nearbyCompanies.value) } googleMap.setOnInfoWindowClickListener(infoWindowClickCallback) } private val infoWindowClickCallback = GoogleMap.OnInfoWindowClickListener { marker -> val infoWindowData: CompanyMapMarkerModel? = marker.tag as CompanyMapMarkerModel? infoWindowData?.let { // Reset the selected marker, then set it again companyMapMarkerModel = null companyMapMarkerModel = it val origin = infoWindowData.latLng val destination = infoWindowData.toLatLng viewModel.getRoute(origin, destination) binding.tripDetailAccessWindowMotion.transitionToEnd() /*if (currentLatLng != null){ } else { showPath(listOf(infoWindowData.latLng, infoWindowData.toLatLng)) }*/ } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.map_options, menu) } override fun showNearbyCompanies(companies: List<CompanyMapMarkerModel>?) { companies?.let { nearbyCompanyMarkerList.clear() if (::googleMap.isInitialized){ for (company in companies) { val nearbyCompanyMarker = addCompanyMarkerAndGet(company) nearbyCompanyMarkerList.add(nearbyCompanyMarker) } } else { reInitNearby = true } } } override fun informCompanyBooked() { nearbyCompanyMarkerList.forEach { it.remove() } nearbyCompanyMarkerList.clear() viewModel.showSnackBarInt.value = R.string.your_pickup_is_booked } override fun showPath(latLngList: List<LatLng>?) { latLngList?.let { resetMarkers() val builder = LatLngBounds.Builder() for (latLng in latLngList) { builder.include(latLng) } val bounds = builder.build() googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 64)) PolylineOptions().color(Color.GRAY).width(5f).addAll(latLngList).apply { greyPolyLine = googleMap.addPolyline(this) } PolylineOptions().width(5f).color(Color.BLACK).apply { googleMap.addPolyline(this) } originMarker = addOriginDestinationMarkerAndGet(latLngList[0]).apply { setAnchor(0.5f, 0.5f) } destinationMarker = addOriginDestinationMarkerAndGet(latLngList[latLngList.size - 1]).apply { setAnchor(0.5f, 0.5f) } AnimationUtils.polyLineAnimator().apply { addUpdateListener { valueAnimator -> val percentValue = (valueAnimator.animatedValue as Int) val index = (greyPolyLine?.points!!.size * (percentValue / 100.0f)).toInt() blackPolyline?.points = greyPolyLine?.points!!.subList(0, index) } start() } } } private fun addTruckMarkerAndGet(latLng: LatLng): Marker? { val bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(MapUtils.getTruckBitmap(requireContext())) return if (::googleMap.isInitialized){ googleMap.addMarker(MarkerOptions().position(latLng).flat(true).icon(bitmapDescriptor)) } else { // TODO: 2/15/2021 Set latlng and googlemap init reinit null } } override fun updateSimulatedDriverLocation(latLng: LatLng?) { latLng?.let { if (movingDriverMarker == null) { movingDriverMarker = addTruckMarkerAndGet(latLng) } if (previousLatLngFromServer == null) { currentLatLngFromServer = latLng previousLatLngFromServer = currentLatLngFromServer movingDriverMarker?.position = currentLatLngFromServer movingDriverMarker?.setAnchor(0.5f, 0.5f) animateCamera(currentLatLngFromServer) } else { previousLatLngFromServer = currentLatLngFromServer currentLatLngFromServer = latLng val valueAnimator = AnimationUtils.truckAnimator() var rotation = 0f var count = 0 valueAnimator.addUpdateListener { va -> if (currentLatLngFromServer != null && previousLatLngFromServer != null) { val multiplier = va.animatedFraction val nextLocation = LatLng( multiplier * currentLatLngFromServer!!.latitude + (1 - multiplier) * previousLatLngFromServer!!.latitude, multiplier * currentLatLngFromServer!!.longitude + (1 - multiplier) * previousLatLngFromServer!!.longitude ) movingDriverMarker?.position = nextLocation movingDriverMarker?.setAnchor(0.5f, 0.5f) // Reducing rate at which the rotation is set if (count % 10 == 0 || count == 0) { rotation = MapUtils.getRotation( previousLatLngFromServer!!, nextLocation ) count = 0 } count++ if (!rotation.isNaN()) { movingDriverMarker?.rotation = rotation } centerCamera(nextLocation) } } valueAnimator.start() } } } override fun informDriverIsArriving() { viewModel.showSnackBarInt.value = R.string.you_are_arriving_at_pickup } override fun informDriverArrived() { viewModel.showSnackBarInt.value = R.string.you_have_arrived_at_pickup resetMarkers() // TODO: 2/15/2021 Generate pickup ticket } override fun informTripStart() { viewModel.showSnackBarInt.value = R.string.you_are_on_route_to_dropoff previousLatLngFromServer = null } override fun informTripEnd() { viewModel.showSnackBarInt.value = R.string.route_end_driver resetMarkers() // TODO: 2/15/2021 Generate dropoff ticket // TODO: 2/15/2021 Inform server dropoff has occured } private fun resetMarkers() { greyPolyLine?.remove() blackPolyline?.remove() originMarker?.remove() destinationMarker?.remove() } override fun showRoutesNotAvailableError() { viewModel.showSnackBarInt.value = R.string.route_not_available_most_likely_in_the_ocean } override fun showDirectionApiFailedError(error: String?) { Log.d(TAG, "showDirectionApiFailedError: error: $error") requireContext().toastLong(error ?: getString(R.string.srverr_unknown)) reset() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if(::googleMap.isInitialized){ when (item.itemId) { // Change the map type based on the user's selection. R.id.normal_map -> { googleMap.mapType = GoogleMap.MAP_TYPE_NORMAL; return true } R.id.hybrid_map -> { googleMap.mapType = GoogleMap.MAP_TYPE_HYBRID; return true } R.id.satellite_map -> { googleMap.mapType = GoogleMap.MAP_TYPE_SATELLITE; return true } R.id.terrain_map -> { googleMap.mapType = GoogleMap.MAP_TYPE_TERRAIN; return true } else -> super.onOptionsItemSelected(item) } } return false } /** * * Navigate to https://mapstyle.withgoogle.com/ in your browser to style the map. * */ private fun setMapStyle(map: GoogleMap) { try { // Customize the styling of the base map using a JSON object defined // in a raw resource file. val success = map.setMapStyle( MapStyleOptions.loadRawResourceStyle( mCtx, R.raw.map_style ) ) if (!success) { Log.e(TAG, "Style parsing failed.") } } catch (e: Resources.NotFoundException) { Log.e(TAG, "Can't find style. Error: ", e) } } override fun getFragmentBinding( inflater: LayoutInflater, container: ViewGroup? ) = DriverMapFragmentBinding.inflate(inflater, container, false) override fun getViewModel() = DriverMapViewModel::class.java override fun getFragmentRepository() = DriverMapRepository( userPreferences, remoteDataSource.buildApi(DriverMapAPI::class.java, authToken) ) }
0
Kotlin
0
2
bb03b30490d11d31363e38ed8b84e328c37e06fb
24,287
Taxidi
Apache License 2.0
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/inheritance/InheritanceManagementUiStateMachineImpl.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 7954899, "Rust": 2637832, "Swift": 864356, "HCL": 349275, "Python": 338898, "Shell": 136166, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.statemachine.inheritance import androidx.compose.runtime.* import build.wallet.statemachine.core.ScreenModel import build.wallet.statemachine.core.form.FormBodyModel import build.wallet.statemachine.core.form.FormHeaderModel import build.wallet.ui.model.StandardClick import build.wallet.ui.model.button.ButtonModel import build.wallet.ui.model.toolbar.ToolbarAccessoryModel import build.wallet.ui.model.toolbar.ToolbarModel class InheritanceManagementUiStateMachineImpl( private val inviteBeneficiaryUiStateMachine: InviteBeneficiaryUiStateMachine, ) : InheritanceManagementUiStateMachine { @Composable override fun model(props: InheritanceManagementUiProps): ScreenModel { var uiState: UiState by remember { mutableStateOf(UiState.ManagingInheritance) } return when (uiState) { // TODO W-9135 W-9383 add inheritance management UI to design spec UiState.ManagingInheritance -> FormBodyModel( id = null, onBack = props.onBack, header = FormHeaderModel( headline = "Inheritance", subline = "Manage your beneficiaries and inheritance claims." ), toolbar = ToolbarModel( leadingAccessory = ToolbarAccessoryModel.IconAccessory.BackAccessory { props.onBack() } ), primaryButton = ButtonModel( text = "Invite", onClick = StandardClick { uiState = UiState.InvitingBeneficiary }, size = ButtonModel.Size.Footer ), secondaryButton = ButtonModel( text = "Accept", onClick = StandardClick { }, size = ButtonModel.Size.Footer ) ).asRootScreen() UiState.InvitingBeneficiary -> inviteBeneficiaryUiStateMachine.model( InviteBeneficiaryUiProps( account = props.account, onExit = { uiState = UiState.ManagingInheritance } ) ) } } } private sealed interface UiState { data object ManagingInheritance : UiState data object InvitingBeneficiary : UiState }
3
C
16
113
1af1bc74d51ecf1dff2f5355e3f33d000957b19b
2,076
bitkey
MIT License
kotlin-antd/antd-samples/src/main/kotlin/samples/radio/RadioGroup.kt
oxiadenine
206,398,615
false
{"Kotlin": 1619835, "HTML": 1515}
package samples.radio import antd.radio.RadioChangeEvent import antd.radio.radio import antd.radio.radioGroup import react.* import styled.css import styled.styledDiv external interface RadioGroupAppState : State { var value: Any } class RadioGroupApp : RComponent<Props, RadioGroupAppState>() { private val handleChange = fun(event: RadioChangeEvent) { console.log("radio checked", event.target.value) setState { value = event.target.value!! } } override fun RadioGroupAppState.init() { value = 1 } override fun RBuilder.render() { radioGroup { attrs { onChange = handleChange value = state.value } radio { attrs.value = 1 +"A" } radio { attrs.value = 2 +"B" } radio { attrs.value = 3 +"C" } radio { attrs.value = 4 +"D" } } } } fun RBuilder.radioGroupApp() = child(RadioGroupApp::class) {} fun RBuilder.radioGroup() { styledDiv { css { +RadioStyles.radioGroup } radioGroupApp() } }
1
Kotlin
8
50
e0017a108b36025630c354c7663256347e867251
1,284
kotlin-js-wrappers
Apache License 2.0
app/src/main/java/com/blazecode/tsviewer/util/database/UserCount.kt
BlazeCodeDev
434,321,563
false
null
/* * * * Copyright (c) BlazeCode / <NAME>, 2022. * */ package com.blazecode.tsviewer.util.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class UserCount( @PrimaryKey(autoGenerate = true) val id: Int?, @ColumnInfo(name = "timeStamp") val timestamp : Long?, @ColumnInfo(name = "amount") val amount: Int?, @ColumnInfo(name = "names") val names: String? ) { }
1
Kotlin
1
12
8c425360db42ab6bb2bfad304ac87011f1f88922
446
TSViewer
MIT License
app/src/main/java/com/mahmudur/gitcommitviewer/model/CommitViewModel.kt
MAHMUDURRAHMANARNOB
666,666,963
false
null
package com.mahmudur.gitcommitviewer.model import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.cachedIn import com.mahmudur.gitcommitviewer.data.GitHubRepository import com.mahmudur.gitcommitviewer.paging.CommitsPagingSource class CommitViewModel: ViewModel() { private val repository = GitHubRepository() //PagingConfig private val pageSize = 20 private val config = PagingConfig(pageSize = pageSize, enablePlaceholders = false) // Flow for fetching commits val commitFlow = Pager(config) { CommitsPagingSource(repository,pageSize) }.flow.cachedIn(viewModelScope) }
0
Kotlin
0
0
42163426483e278960286a1099673ce70b48da72
719
GitCommitsViewer
MIT License
app/src/main/java/jp/cordea/gene/viewmodels/GenesListItemViewModel.kt
CORDEA
93,741,813
false
null
package jp.cordea.gene.viewmodels import android.arch.lifecycle.ViewModel import jp.cordea.gene.api.response.Gene /** * Created by <NAME> on 2017/05/26. */ class GenesListItemViewModel(item: Gene) : ViewModel() { val id = item.id val title = item.symbol val description = item.name }
0
Kotlin
0
0
a048af5f1e83f7a847fee71f60ba94b276d79dab
303
Gene
Apache License 2.0
app/src/main/java/jp/cordea/gene/viewmodels/GenesListItemViewModel.kt
CORDEA
93,741,813
false
null
package jp.cordea.gene.viewmodels import android.arch.lifecycle.ViewModel import jp.cordea.gene.api.response.Gene /** * Created by <NAME> on 2017/05/26. */ class GenesListItemViewModel(item: Gene) : ViewModel() { val id = item.id val title = item.symbol val description = item.name }
0
Kotlin
0
0
a048af5f1e83f7a847fee71f60ba94b276d79dab
303
Gene
Apache License 2.0
domain/src/main/java/com/athimue/domain/usecase/getFavoriteTracks/GetFavoriteTracksUseCaseImpl.kt
athimue
676,430,924
false
{"Kotlin": 168414}
package com.athimue.domain.usecase.getFavoriteTracks import com.athimue.domain.model.Track import com.athimue.domain.repository.FavoriteTracksRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class GetFavoriteTracksUseCaseImpl @Inject constructor( private val favoriteTracksRepository: FavoriteTracksRepository, ) : GetFavoriteTracksUseCase { override suspend fun invoke(): Flow<List<Track>> = favoriteTracksRepository.getFavorites() }
0
Kotlin
0
0
76df1a4b661dae0246dc3bd16fca86e571b68e32
478
GrooveWave
MIT License
app/src/main/java/com/github/skytoph/simpleweather/data/location/mapper/LocalNameDataMapper.kt
skytoph
482,520,275
false
null
package com.github.skytoph.simpleweather.data.location.mapper import com.github.skytoph.simpleweather.core.Mapper import java.util.* import javax.inject.Inject interface LocalNameDataMapper : Mapper<Pair<String, String>> { fun map(language: String = "en", name: String): Pair<String, String> fun map(language: Locale, name: String): Pair<String, String> class Base @Inject constructor() : LocalNameDataMapper { override fun map(language: String, name: String) = language to name override fun map(language: Locale, name: String): Pair<String, String> = map(language.language, name) } }
0
Kotlin
0
0
5629e9b11861dc3866510a366a1ba3cc95075fc9
632
SimpleWeather
MIT License
shared/src/commonMain/kotlin/cat/alexgluque/paraulogicsolver/data/words/W.kt
alexluque
451,162,453
false
null
package cat.alexgluque.paraulogicsolver.data.words val wordsW = listOf( "wagnerisme", "washingtònia", "waterpolo", "watt", "wattímetre", "wàttmetre", "waw", "web", "weber", "welwítsquia", "whisky", "wolfram", "wolframat", "wolframi", "wolfràmic -a", "wolframita", "wol·lastonita", "wòlof", "wulfenita", "wurtzita" )
0
Kotlin
0
0
4d1d0b78d4c5d8b9a9d7c20a75e1fc857e9b1ccf
396
ParaulogicSolver
Apache License 2.0
app/src/main/kotlin/kozyriatskyi/anton/sked/login/student/StudentLoginComponent.kt
antonKozyriatskyi
123,421,471
false
null
package kozyriatskyi.anton.sked.login.student import dagger.Component import kozyriatskyi.anton.sked.di.Login import kozyriatskyi.anton.sked.di.AppComponent import kozyriatskyi.anton.sked.di.module.ConnectionModule @Login @Component(modules = [StudentLoginModule::class, ConnectionModule::class], dependencies = [AppComponent::class]) interface StudentLoginComponent { fun inject(studentLoginFragment: StudentLoginFragment) }
0
Kotlin
0
3
0814886758513a7d836e6908aeb7f14a45273683
439
sked
Apache License 2.0
datacapture/src/main/java/com/google/android/fhir/datacapture/views/QuestionnaireItemEditTextViewHolderFactory.kt
sbh04101989
329,770,920
true
{"Kotlin": 285905, "Shell": 1101}
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.views import android.text.Editable import android.view.View import androidx.core.widget.doAfterTextChanged import com.google.android.fhir.datacapture.R import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import org.hl7.fhir.r4.model.QuestionnaireResponse import org.hl7.fhir.r4.model.StringType object QuestionnaireItemEditTextViewHolderFactory : QuestionnaireItemViewHolderFactory( R.layout.questionnaire_item_edit_text_view ) { override fun getQuestionnaireItemViewHolderDelegate() = object : QuestionnaireItemViewHolderDelegate { private lateinit var textInputLayout: TextInputLayout private lateinit var textInputEditText: TextInputEditText private lateinit var questionnaireItemViewItem: QuestionnaireItemViewItem override fun init(itemView: View) { textInputLayout = itemView.findViewById(R.id.textInputLayout) textInputEditText = itemView.findViewById(R.id.textInputEditText) textInputEditText.doAfterTextChanged { editable: Editable? -> questionnaireItemViewItem.singleAnswerOrNull = QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .apply { value = StringType(editable.toString()) } } } override fun bind(questionnaireItemViewItem: QuestionnaireItemViewItem) { this.questionnaireItemViewItem = questionnaireItemViewItem textInputLayout.hint = questionnaireItemViewItem.questionnaireItemComponent.text textInputEditText.setText( questionnaireItemViewItem.singleAnswerOrNull?.valueStringType?.value ?: "" ) } } }
0
null
0
0
0a206de34740db8f45ae105fb36d2dd40c97ba6a
2,347
android-fhir
Apache License 2.0
app/src/main/java/com/ghataa/metaweather/data/source/DefaultWeatherInfoRepository.kt
ghataa
360,263,493
false
null
package com.ghataa.metaweather.data.source import android.util.Log import com.ghataa.metaweather.data.Result import com.ghataa.metaweather.data.Result.Error import com.ghataa.metaweather.data.Result.Success import com.ghataa.metaweather.data.model.WeatherInfo import com.ghataa.metaweather.di.ApplicationModule.WeatherInfoLocalDataSource import com.ghataa.metaweather.di.ApplicationModule.WeatherInfoRemoteDataSource import javax.inject.Inject /** The default implementation of the [WeatherInfoRepository] interface. */ class DefaultWeatherInfoRepository @Inject constructor( @WeatherInfoRemoteDataSource private val remoteWeatherInfoDataSource: WeatherInfoDataSource, @WeatherInfoLocalDataSource private val localWeatherInfoDataSource: WeatherInfoDataSource ) : WeatherInfoRepository { private var cacheRefreshTimestamp: Long = 0 /** Fetches data from the remote data source if the cache is invalid and saves it to the local data source. * Serves the requests always from the local data source. */ override suspend fun getWeatherInfoList(month: Int, day: Int): Result<List<WeatherInfo>> { if (cacheIsInvalid()) fetchFromRemoteAndSaveToLocal(month, day) return fetchWeatherInfoFromLocal(month, day) } override fun invalidateCache() { cacheRefreshTimestamp = 0 } /** Returns true if the local cache is outdated. */ private fun cacheIsInvalid(): Boolean = System.currentTimeMillis() - cacheRefreshTimestamp > ONE_MINUTE_MS private suspend fun fetchFromRemoteAndSaveToLocal(month: Int, day: Int) { val remoteWeatherInfoList = remoteWeatherInfoDataSource.getWeatherInfoList(month, day) when (remoteWeatherInfoList) { is Error -> Log.e("Error", "Remote data source fetch failed for WeatherInfoList") is Success -> { refreshLocalDataSource(remoteWeatherInfoList.data) cacheRefreshTimestamp = System.currentTimeMillis() } else -> throw IllegalStateException() } } private suspend fun fetchWeatherInfoFromLocal(month: Int, day: Int): Result<List<WeatherInfo>> { val localWeatherInfoList = localWeatherInfoDataSource.getWeatherInfoList(month, day) if (localWeatherInfoList is Success) return localWeatherInfoList return Error(Exception("Error fetching WeatherInfoList from local")) } private suspend fun refreshLocalDataSource(weatherInfoList: List<WeatherInfo>) { localWeatherInfoDataSource.deleteWeatherInfoList() for (weatherInfo in weatherInfoList) { localWeatherInfoDataSource.saveWeatherInfo(weatherInfo) } } companion object { private const val ONE_MINUTE_MS = 60_000L } }
0
Kotlin
0
0
3b28eb0c5b5b55e110d4e04647db913daad1f1ad
2,777
MetaWeather
Apache License 2.0
core/src/main/kotlin/edu/umontreal/kotlingrad/experimental/Vector.kt
cerkut
287,769,250
true
{"Kotlin": 238851}
@file:Suppress("ClassName", "LocalVariableName", "NonAsciiCharacters", "FunctionName", "MemberVisibilityCanBePrivate", "UNUSED_VARIABLE") package edu.umontreal.kotlingrad.experimental import edu.mcgill.kaliningraph.circuits.* import edu.umontreal.kotlingrad.utils.matmul import org.jetbrains.bio.viktor.F64Array import kotlin.reflect.KProperty /** * Vector function. */ sealed class VFun<X: SFun<X>, E: D1>(override vararg val inputs: Fun<X>): Fun<X> { @Suppress("UNCHECKED_CAST") override fun invoke(newBindings: Bindings<X>): VFun<X, E> = VComposition(this, newBindings) .run { if (bindings.complete || newBindings.readyToBind || EAGER) evaluate else this } // Materializes the concrete vector from the dataflow graph operator fun invoke(): Vec<X, E> = VComposition(this).evaluate.let { try { it as Vec<X, E> } catch (e: ClassCastException) { show("before"); it.show("after") throw NumberFormatException("Vector function has unbound free variables: ${bindings.allFreeVariables.keys}") } } val mapInput by lazy { SVar(proto, "mapInput") } open fun map(ef: (SFun<X>) -> SFun<X>): VFun<X, E> = VMap(this, ef(mapInput), mapInput) open fun <C: D1> vMap(ef: (SFun<X>) -> VFun<X, C>): MFun<X, E, C> = VVMap(this, ef(mapInput), mapInput) fun <Q: D1> d(v1: VVar<X, Q>): MFun<X, E, Q> = Jacobian(this, v1) fun d(v1: SVar<X>) = VDerivative(this, v1) fun d(v1: SVar<X>, v2: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j2", D2, Vec(v1, v2))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j3", D3, Vec(v1, v2, v3))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>, v4: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j4", D4, Vec(v1, v2, v3, v4))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>, v4: SVar<X>, v5: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j5", D5, Vec(v1, v2, v3, v4, v5))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>, v4: SVar<X>, v5: SVar<X>, v6: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j6", D6, Vec(v1, v2, v3, v4, v5, v6))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>, v4: SVar<X>, v5: SVar<X>, v6: SVar<X>, v7: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j7", D7, Vec(v1, v2, v3, v4, v5, v6, v7))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>, v4: SVar<X>, v5: SVar<X>, v6: SVar<X>, v7: SVar<X>, v8: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j8", D8, Vec(v1, v2, v3, v4, v5, v6, v7, v8))) fun d(v1: SVar<X>, v2: SVar<X>, v3: SVar<X>, v4: SVar<X>, v5: SVar<X>, v6: SVar<X>, v7: SVar<X>, v8: SVar<X>, v9: SVar<X>) = Jacobian(this, VVar(bindings.proto, "j9", D9, Vec(v1, v2, v3, v4, v5, v6, v7, v8, v9))) fun d(vararg vars: SVar<X>): Map<SVar<X>, VFun<X, E>> = vars.map { it to d(it) }.toMap() fun grad(): Map<SVar<X>, VFun<X, E>> = bindings.sVars.map { it to d(it) }.toMap() open operator fun unaryMinus(): VFun<X, E> = VNegative(this) open operator fun plus(addend: VFun<X, E>): VFun<X, E> = VSum(this, addend) open operator fun minus(subtrahend: VFun<X, E>): VFun<X, E> = VSum(this, -subtrahend) open infix fun ʘ(multiplicand: VFun<X, E>): VFun<X, E> = VVProd(this, multiplicand) open operator fun times(multiplicand: SFun<X>): VFun<X, E> = VSProd(this, multiplicand) open operator fun <Q: D1> times(multiplicand: MFun<X, Q, E>): VFun<X, Q> = VMProd(this, multiplicand) open infix fun dot(multiplicand: VFun<X, E>): SFun<X> = DProd(this, multiplicand) operator fun times(multiplicand: Number): VFun<X, E> = this * wrap(multiplicand) fun magnitude() = (this ʘ this).sum().sqrt() open fun sum(): SFun<X> = VSumAll(this) override fun toString() = when (this) { is Vec -> contents.joinToString(", ", "[", "]") is VMap -> "$input.map { $ssMap }" is VVar -> "VVar($name)" is VComposition -> "($input)$bindings" else -> asString() } override val op: Op = when(this) { is VNegative<X, *> -> Monad.`-` is VMap<X, *> -> Polyad.map is VSum<X, *> -> Dyad.`+` is Gradient<X, *> -> Dyad.d is VDerivative<X, *> -> Dyad.d is VVProd<X, *> -> Dyad.`*` is SVProd<X, *> -> Dyad.`*` is VSProd<X, *> -> Dyad.`*` is MVProd<X, *, *> -> Dyad.dot is VMProd<X, *, *> -> Dyad.dot is VComposition<X, *> -> Polyad.λ is MSumRows<X, *, *> -> Polyad.Σ else -> Monad.id } override operator fun invoke(vararg numbers: Number): VFun<X, E> = invoke(bindings.zip(numbers.map { wrap(it) })) override operator fun invoke(vararg funs: Fun<X>): VFun<X, E> = invoke(bindings.zip(funs.toList())) override operator fun invoke(vararg ps: Pair<Fun<X>, Any>): VFun<X, E> = invoke(ps.toList().bind()) } class VNegative<X: SFun<X>, E: D1>(override val input: VFun<X, E>): VFun<X, E>(input), UnFun<X> class VMap<X: SFun<X>, E: D1>( override val input: VFun<X, E>, val ssMap: SFun<X>, placeholder: SVar<X> ): VFun<X, E>(input, ssMap), UnFun<X> { override val bindings: Bindings<X> = input.bindings + ssMap.bindings - placeholder } class VVMap<X: SFun<X>, R: D1, C: D1>( val input: VFun<X, R>, val svMap: VFun<X, C>, placeholder: SVar<X> ): MFun<X, R, C>(input, svMap), PolyFun<X> { override val bindings: Bindings<X> = input.bindings + svMap.bindings - placeholder override val inputs: Array<out Fun<X>> = arrayOf(input, svMap) } class VSum<X: SFun<X>, E: D1>(override val left: VFun<X, E>, override val right: VFun<X, E>): VFun<X, E>(left, right), BiFun<X> class VVProd<X: SFun<X>, E: D1>(override val left: VFun<X, E>, override val right: VFun<X, E>): VFun<X, E>(left, right), BiFun<X> class SVProd<X: SFun<X>, E: D1>(override val left: SFun<X>, override val right: VFun<X, E>): VFun<X, E>(left, right), BiFun<X> class VSProd<X: SFun<X>, E: D1>(override val left: VFun<X, E>, override val right: SFun<X>): VFun<X, E>(left, right), BiFun<X> class MVProd<X: SFun<X>, R: D1, C: D1>(override val left: MFun<X, R, C>, override val right: VFun<X, C>): VFun<X, R>(left, right), BiFun<X> class VMProd<X: SFun<X>, R: D1, C: D1>(override val left: VFun<X, C>, override val right: MFun<X, R, C>): VFun<X, R>(left, right), BiFun<X> class MSumRows<X: SFun<X>, R: D1, C: D1>(val input: MFun<X, R, C>): VFun<X, C>(input), PolyFun<X> { override val inputs: Array<out Fun<X>> = arrayOf(input) } class VDerivative<X : SFun<X>, E: D1>(override val input: VFun<X, E>, override val vrb: SVar<X>) : VFun<X, E>(input, vrb), Grad<X> { fun df() = input.df() private fun VFun<X, E>.df(): VFun<X, E> = when (this@df) { is VVar -> sVars.map { it.d(vrb) } is VConst<X, E> -> map { Zero() } is VSum -> left.df() + right.df() is VVProd -> left.df() ʘ right + left ʘ right.df() is SVProd -> left.d(vrb) * right + left * right.df() is VSProd -> left.df() * right + left * right.d(vrb) is VNegative -> -input.df() is VDerivative -> input.df() is Vec -> Vec(contents.map { it.d(vrb) }) is MVProd<X, *, *> -> (left.d(vrb) as MFun<X, E, E>) * right as VFun<X, E> + (left as MFun<X, E, E> * right.d(vrb)) is VMProd<X, *, *> -> (left.d(vrb) as VFun<X, E> * right as MFun<X, E, E>) + (left as VFun<X, E> * right.d(vrb)) is Gradient -> invoke().df() // map { it.d(sVar) } is VMap -> input.df().map { it * ssMap(mapInput to it).d(vrb) } // Chain rule is VComposition -> evaluate.df() else -> TODO(<EMAIL>) } } class Gradient<X : SFun<X>, E: D1>(override val input: SFun<X>, override val vrb: VVar<X, E>): VFun<X, E>(input, vrb), Grad<X> { fun df() = input.df() private fun SFun<X>.df(): VFun<X, E> = when (this@df) { is SVar -> vrb.sVars.map { if(this@df == it) One() else Zero() } is SConst -> vrb.sVars.map { Zero() } is Sum -> left.df() + right.df() is Prod -> left.df() * right + left * right.df() is Power -> if (right.isConstant()) right * left.pow(right - One()) * left.df() else (left.df() * right * (One<X>() / left) + right.df() * left.ln()) is Negative -> -input.df() is Log -> (left pow -One<X>()) * left.df() is DProd -> (left.d(vrb) as MFun<X, E, E> * right as VFun<X, E>) + (left as VFun<X, E> * right.d(vrb)) is SComposition -> evaluate.df() is VSumAll<X, *> -> (input as VFun<X, E>).d(vrb).sum() else -> TODO(<EMAIL>) } } open class VVar<X: SFun<X>, E: D1> constructor( override val proto: X, override val name: String = "", val length: E, val sVars: Vec<X, E> = Vec(List(length.i) { SVar(proto, "$name[$it]") }) ): Variable<X>, VFun<X, E>() { override val bindings: Bindings<X> = Bindings(mapOf(this to sVars)) override fun equals(other: Any?) = other is VVar<*, *> && name == other.name override fun hashCode(): Int = name.hashCode() operator fun getValue(thisRef: Any?, property: KProperty<*>) = VVar(proto, if (name.isEmpty()) property.name else name, length, sVars) } class VComposition<X: SFun<X>, E: D1>(override val input: VFun<X, E>, arguments: Bindings<X> = Bindings(input.proto)): VFun<X, E>(input), UnFun<X> { override val bindings: Bindings<X> = input.bindings + arguments val evaluate: VFun<X, E> by lazy { bind(bindings) } @Suppress("UNCHECKED_CAST") fun VFun<X, E>.bind(bnds: Bindings<X>): VFun<X, E> = bnds[this@bind] ?: when (this@bind) { is VVar<X, E> -> sVars is Vec<X, E> -> map { it(bnds) } is VNegative<X, E> -> -input.bind(bnds) is VSum<X, E> -> left.bind(bnds) + right.bind(bnds) is VVProd<X, E> -> left.bind(bnds) ʘ right.bind(bnds) is SVProd<X, E> -> left(bnds) * right.bind(bnds) is VSProd<X, E> -> left.bind(bnds) * right(bnds) is VDerivative -> df().bind(bnds) is Gradient -> df().bind(bnds) is MVProd<X, *, *> -> left(bnds) as MFun<X, E, E> * (right as VFun<X, E>).bind(bnds) is VMProd<X, *, *> -> (left as VFun<X, E>).bind(bnds) * (right as MFun<X, E, E>)(bnds) is VMap<X, E> -> input.bind(bnds).map { ssMap(mapInput to it)(bnds) } is VComposition -> input.bind(bnds) is MSumRows<X, *, *> -> input(bnds).sum() as VFun<X, E> }.also { result -> bnds.checkForUnpropagatedVariables(this@bind, result) } } open class VConst<X: SFun<X>, E: D1> constructor(vararg val consts: SConst<X>): Vec<X, E>(consts.toList()), Constant<X> { constructor(proto: X, fVec: F64Array): this(*fVec.toDoubleArray().map { proto.wrap(it) }.toTypedArray()) constructor(proto: X, vararg values: Number): this(*values.map { proto.wrap(it) }.toTypedArray()) override val proto by lazy { consts[0].proto } val simdVec by lazy { F64Array(consts.size) { consts[it].doubleValue } } override fun plus(addend: VFun<X, E>) = when(addend) { is VConst<X, E> -> VConst(proto, simdVec + addend.simdVec) else -> super.plus(addend) } override fun minus(subtrahend: VFun<X, E>) = when(subtrahend) { is VConst<X, E> -> VConst(proto, simdVec - subtrahend.simdVec) else -> super.minus(subtrahend) } override fun ʘ(multiplicand: VFun<X, E>) = when(multiplicand) { is VConst<X, E> -> VConst(proto, simdVec * multiplicand.simdVec) else -> super.ʘ(multiplicand) } override fun dot(multiplicand: VFun<X, E>): SFun<X> = when(multiplicand) { is VConst<X, E> -> SConst(simdVec dot multiplicand.simdVec) else -> super.dot(multiplicand) } override fun times(multiplicand: SFun<X>) = when (multiplicand) { is SConst<X> -> VConst(proto, simdVec * multiplicand.doubleValue) else -> super.times(multiplicand) } override operator fun <Q: D1> times(multiplicand: MFun<X, Q, E>): VFun<X, Q> = when (multiplicand) { is MConst<X, Q, E> -> VConst(proto, simdVec matmul multiplicand.simdVec) else -> super.times(multiplicand) } } open class Vec<X: SFun<X>, E: D1>(val contents: List<SFun<X>>): VFun<X, E>(*contents.toTypedArray()), Iterable<SFun<X>> by contents { constructor(len: Nat<E>, gen: (Int) -> SFun<X>): this(List(len.i) { gen(it) }) override val proto by lazy { contents.first().proto } val size = contents.size operator fun get(index: Int) = contents[index] override fun plus(addend: VFun<X, E>) = when (addend) { is Vec<X, E> -> Vec(mapIndexed { i, v -> v + addend[i] }) else -> super.plus(addend) } override fun minus(subtrahend: VFun<X, E>) = when (subtrahend) { is Vec<X, E> -> Vec(mapIndexed { i, v -> v - subtrahend[i] }) else -> super.minus(subtrahend) } override fun ʘ(multiplicand: VFun<X, E>) = when(multiplicand) { is Vec<X, E> -> Vec(mapIndexed { i, v -> v * multiplicand[i] }) else -> super.ʘ(multiplicand) } override fun times(multiplicand: SFun<X>) = map { it * multiplicand } override fun dot(multiplicand: VFun<X, E>) = when(multiplicand) { is Vec<X, E> -> mapIndexed { i, v -> v * multiplicand[i] }.reduce { acc, it -> acc + it } else -> super.dot(multiplicand) } override operator fun <Q: D1> times(multiplicand: MFun<X, Q, E>): VFun<X, Q> = when (multiplicand) { is Mat<X, Q, E> -> Vec(multiplicand.map { row: VFun<X, E> -> row dot this }) else -> super.times(multiplicand) } override fun map(ef: (SFun<X>) -> SFun<X>) = Vec<X, E>(contents.map { ef(it)(mapInput to it) }) override fun <C: D1> vMap(ef: (SFun<X>) -> VFun<X, C>) = Mat<X, E, C>(contents.map { ef(it)(mapInput to it) }) override fun unaryMinus() = map { -it } override fun sum() = reduce { acc, it -> acc + it } companion object { operator fun <T: SFun<T>> invoke(s0: SConst<T>): VConst<T, D1> = VConst(s0) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>): VConst<T, D2> = VConst(s0, s1) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>): VConst<T, D3> = VConst(s0, s1, s2) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>, s3: SConst<T>): VConst<T, D4> = VConst(s0, s1, s2, s3) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>, s3: SConst<T>, s4: SConst<T>): VConst<T, D5> = VConst(s0, s1, s2, s3, s4) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>, s3: SConst<T>, s4: SConst<T>, s5: SConst<T>): VConst<T, D6> = VConst(s0, s1, s2, s3, s4, s5) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>, s3: SConst<T>, s4: SConst<T>, s5: SConst<T>, s6: SConst<T>): VConst<T, D7> = VConst(s0, s1, s2, s3, s4, s5, s6) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>, s3: SConst<T>, s4: SConst<T>, s5: SConst<T>, s6: SConst<T>, s7: SConst<T>): VConst<T, D8> = VConst(s0, s1, s2, s3, s4, s5, s6, s7) operator fun <T: SFun<T>> invoke(s0: SConst<T>, s1: SConst<T>, s2: SConst<T>, s3: SConst<T>, s4: SConst<T>, s5: SConst<T>, s6: SConst<T>, s7: SConst<T>, s8: SConst<T>): VConst<T, D9> = VConst(s0, s1, s2, s3, s4, s5, s6, s7, s8) operator fun <T: SFun<T>> invoke(t0: SFun<T>): Vec<T, D1> = Vec(arrayListOf(t0)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>): Vec<T, D2> = Vec(arrayListOf(t0, t1)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>): Vec<T, D3> = Vec(arrayListOf(t0, t1, t2)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>, t3: SFun<T>): Vec<T, D4> = Vec(arrayListOf(t0, t1, t2, t3)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>, t3: SFun<T>, t4: SFun<T>): Vec<T, D5> = Vec(arrayListOf(t0, t1, t2, t3, t4)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>, t3: SFun<T>, t4: SFun<T>, t5: SFun<T>): Vec<T, D6> = Vec(arrayListOf(t0, t1, t2, t3, t4, t5)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>, t3: SFun<T>, t4: SFun<T>, t5: SFun<T>, t6: SFun<T>): Vec<T, D7> = Vec(arrayListOf(t0, t1, t2, t3, t4, t5, t6)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>, t3: SFun<T>, t4: SFun<T>, t5: SFun<T>, t6: SFun<T>, t7: SFun<T>): Vec<T, D8> = Vec(arrayListOf(t0, t1, t2, t3, t4, t5, t6, t7)) operator fun <T: SFun<T>> invoke(t0: SFun<T>, t1: SFun<T>, t2: SFun<T>, t3: SFun<T>, t4: SFun<T>, t5: SFun<T>, t6: SFun<T>, t7: SFun<T>, t8: SFun<T>): Vec<T, D9> = Vec(arrayListOf(t0, t1, t2, t3, t4, t5, t6, t7, t8)) } } /** * Type level integers. */ interface Nat<T: D0> { val i: Int } sealed class INat<T: D0>: SConst<INat<T>>() { abstract val i: Int override fun toString() = "$i" } sealed class D0(override val i: Int = 0):INat<D0>(){ companion object: D0(), Nat<D0> } sealed class D1(override val i: Int = 1): D0(i) { companion object: D1(), Nat<D1> } sealed class D2(override val i: Int = 2): D1(i) { companion object: D2(), Nat<D2> } sealed class D3(override val i: Int = 3): D2(i) { companion object: D3(), Nat<D3> } sealed class D4(override val i: Int = 4): D3(i) { companion object: D4(), Nat<D4> } sealed class D5(override val i: Int = 5): D4(i) { companion object: D5(), Nat<D5> } sealed class D6(override val i: Int = 6): D5(i) { companion object: D6(), Nat<D6> } sealed class D7(override val i: Int = 7): D6(i) { companion object: D7(), Nat<D7> } sealed class D8(override val i: Int = 8): D7(i) { companion object: D8(), Nat<D8> } sealed class D9(override val i: Int = 9): D8(i) { companion object: D9(), Nat<D9> } sealed class D10(override val i: Int = 10): D9(i) { companion object: D10(), Nat<D10> } sealed class D11(override val i: Int = 11): D10(i) { companion object: D11(), Nat<D11> } sealed class D12(override val i: Int = 12): D11(i) { companion object: D12(), Nat<D12> } sealed class D13(override val i: Int = 13): D12(i) { companion object: D13(), Nat<D13> } sealed class D14(override val i: Int = 14): D13(i) { companion object: D14(), Nat<D14> } sealed class D15(override val i: Int = 15): D14(i) { companion object: D15(), Nat<D15> } sealed class D16(override val i: Int = 16): D15(i) { companion object: D16(), Nat<D16> } sealed class D17(override val i: Int = 17): D16(i) { companion object: D17(), Nat<D17> } sealed class D18(override val i: Int = 18): D17(i) { companion object: D18(), Nat<D18> } sealed class D19(override val i: Int = 19): D18(i) { companion object: D19(), Nat<D19> } sealed class D20(override val i: Int = 20): D19(i) { companion object: D20(), Nat<D20> } sealed class D21(override val i: Int = 21): D20(i) { companion object: D21(), Nat<D21> } sealed class D22(override val i: Int = 22): D21(i) { companion object: D22(), Nat<D22> } sealed class D23(override val i: Int = 23): D22(i) { companion object: D23(), Nat<D23> } sealed class D24(override val i: Int = 24): D23(i) { companion object: D24(), Nat<D24> } sealed class D25(override val i: Int = 25): D24(i) { companion object: D25(), Nat<D25> } sealed class D26(override val i: Int = 26): D25(i) { companion object: D26(), Nat<D26> } sealed class D27(override val i: Int = 27): D26(i) { companion object: D27(), Nat<D27> } sealed class D28(override val i: Int = 28): D27(i) { companion object: D28(), Nat<D28> } sealed class D29(override val i: Int = 29): D28(i) { companion object: D29(), Nat<D29> } sealed class D30(override val i: Int = 30): D29(i) { companion object: D30(), Nat<D30> } sealed class D50(override val i: Int = 50): D30(i) { companion object: D50(), Nat<D50> } sealed class D100(override val i: Int = 100): D50(i) { companion object: D100(), Nat<D100> }
0
null
0
0
a105474549a6ae24df629164bd0cb546e449b4da
19,184
kotlingrad
Apache License 2.0
features/settings/src/main/kotlin/io/plastique/settings/SettingsActivityComponent.kt
plastiqueapp
150,879,887
false
null
package io.plastique.settings import io.plastique.settings.licenses.LicensesActivity interface SettingsActivityComponent { fun inject(activity: LicensesActivity) fun inject(activity: SettingsActivity) }
0
Kotlin
2
9
9271853f3741add18822858cbad9d4f8e8104f54
214
plastique
Apache License 2.0
features/settings/src/main/kotlin/io/plastique/settings/SettingsActivityComponent.kt
plastiqueapp
150,879,887
false
null
package io.plastique.settings import io.plastique.settings.licenses.LicensesActivity interface SettingsActivityComponent { fun inject(activity: LicensesActivity) fun inject(activity: SettingsActivity) }
0
Kotlin
2
9
9271853f3741add18822858cbad9d4f8e8104f54
214
plastique
Apache License 2.0
src/main/java/lu/jimenez/research/tools/utils/Serialization.kt
mmakowski
170,404,529
false
null
/*- * #%L * Utilitary * %% * Copyright (C) 2016 <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. * #L% */ package lu.jimenez.research.tools.utils import java.io.* /** * Serialization Utilitary object * * this object contains several functions that allow to serialize/ Deserialize a list of Serializable Object */ object Serialization { /** * Saving to an object file the array List of Serializable object * * @param listFile List to save * @param path pah of the file in which we will save */ fun saveListData(listFile: List<Any>, path: String) { try { val fos = FileOutputStream(path) val oos = ObjectOutputStream(fos) oos.writeObject(listFile) oos.close() fos.close() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } /** * Saving to an object file the map of objects * * @param mapHashObject map of object using its hash as a key * @param path pah of the file in which we will save */ fun saveMapHashData(mapHashObject: Map<Int, Any>, path: String) { try { val fos = FileOutputStream(path) val oos = ObjectOutputStream(fos) oos.writeObject(mapHashObject) oos.close() fos.close() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } /** * Saving to an object file a map of string object * * @param mapStringObject map of object using a string as a key * @param path pah of the file in which we will save */ fun saveMapStringData(mapStringObject: Map<String, Any>, path: String) { try { val fos = FileOutputStream(path) val oos = ObjectOutputStream(fos) oos.writeObject(mapStringObject) oos.close() fos.close() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } /** * Saving to an object file a map of string object * * @param mapStringObject map of object using a string as a key * @param path pah of the file in which we will save */ fun saveMapData(mapStringObject: Map<Serializable, Serializable>, path: String) { try { val fos = FileOutputStream(path) val oos = ObjectOutputStream(fos) oos.writeObject(mapStringObject) oos.close() fos.close() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } /** * Loading the data save in an object file * Reverse of saveListData * * @param path path of the file * @return list of serialized objects */ fun loadListData(path: String): List<Any>? { val fileIn = FileInputStream(path) val read = ObjectInputStream(fileIn) try { val listFile = read.readObject() as List<Any> read.close() fileIn.close() return listFile } catch(e: FileNotFoundException) { e.printStackTrace() return null } } /** * Loading the data save in an object file * Reverse of saveMapHashData * * @param path path of the file * @return map of object with their key as key */ fun loadMapHashData(path: String): Map<Int, Any>? { val fileIn = FileInputStream(path) val read = ObjectInputStream(fileIn) try { val listFile = read.readObject() as Map<Int, Any> read.close() fileIn.close() return listFile } catch(e: FileNotFoundException) { e.printStackTrace() return null } } /** * Loading the data save in an object file * Reverse of saveMapStringData * * @param path path of the file * @return map of string object */ fun loadMapStringData(path: String): Map<String, Any>? { val fileIn = FileInputStream(path) val read = ObjectInputStream(fileIn) try { val listFile = read.readObject() as Map<String, Any> read.close() fileIn.close() return listFile } catch(e: FileNotFoundException) { e.printStackTrace() return null } } /** * Loading the data save in an object file * Reverse of saveMapStringData * * @param path path of the file * @return map of string object */ fun loadMapData(path: String): Map<Serializable, Serializable>? { val fileIn = FileInputStream(path) val read = ObjectInputStream(fileIn) try { val listFile = read.readObject() as Map<Serializable, Serializable> read.close() fileIn.close() return listFile } catch(e: FileNotFoundException) { e.printStackTrace() return null } } }
0
Kotlin
0
0
77964d4e37043d460c05f33366d75b99cced12b6
5,814
vpmreplication-utils
Apache License 2.0
v2-model-enumeration/src/commonMain/kotlin/com/bselzer/gw2/v2/model/enumeration/EquipmentSlot.kt
Woody230
388,820,096
false
{"Kotlin": 750899}
package com.bselzer.gw2.v2.model.enumeration import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class EquipmentSlot { /** * The breathing apparatus for aquatic environments. */ @SerialName("HelmAquatic") BREATHING_APPARATUS, /** * The back trinket. */ @SerialName("Backpack") BACK, /** * The coat armor. */ @SerialName("Coat") COAT, /** * The boot armor. */ @SerialName("Boots") BOOTS, /** * The glove armor. */ @SerialName("Gloves") GLOVES, /** * The helm armor. */ @SerialName("Helm") HELM, /** * The legging armor. */ @SerialName("Leggings") LEGGINGS, /** * The shoulder armor. */ @SerialName("Shoulders") SHOULDERS, /** * The first accessory trinket. */ @SerialName("Accessory1") ACCESSORY1, /** * The second accessory trinket. */ @SerialName("Accessory2") ACCESSORY2, /** * The first ring trinket. */ @SerialName("Ring1") RING1, /** * The second ring trinket. */ @SerialName("Ring2") RING2, /** * The amulet trinket. */ @SerialName("Amulet") AMULET, /** * The first (and only) weapon in the first set for aquatic environments. */ @SerialName("WeaponAquaticA") AQUATIC_WEAPON1_SET1, /** * The first (and only) weapon in the second set for aquatic environments. */ @SerialName("WeaponAquaticB") AQUATIC_WEAPON1_SET2, /** * The first weapon in the first set for terrestrial environments. */ @SerialName("WeaponA1") WEAPON1_SET1, /** * The second weapon in the first set for terrestrial environments. */ @SerialName("WeaponA2") WEAPON2_SET1, /** * The first weapon in the second set for terrestrial environments. */ @SerialName("WeaponB1") WEAPON1_SET2, /** * The second weapon in the second set for terrestrial environments. */ @SerialName("WeaponB2") WEAPON2_SET2, /** * The forging gathering tool. */ @SerialName("Sickle") FORGING_TOOL, /** * The logging gathering tool. */ @SerialName("Axe") LOGGING_TOOL, /** * The mining gathering tool. */ @SerialName("Pick") MINING_TOOL }
2
Kotlin
0
2
32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27
2,437
GW2Wrapper
Apache License 2.0
reposilite-backend/src/main/kotlin/com/reposilite/frontend/application/FrontendPlugin.kt
Saladoc
512,031,617
true
{"Kotlin": 551099, "JavaScript": 88725, "Vue": 72681, "CSS": 9405, "Java": 5555, "HTML": 4501, "Shell": 1835, "Dockerfile": 1563, "Groovy": 1136}
/* * Copyright (c) 2022 dzikoysk * * 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.reposilite.frontend.application import com.reposilite.Reposilite import com.reposilite.configuration.local.LocalConfiguration import com.reposilite.configuration.shared.SharedConfigurationFacade import com.reposilite.frontend.FrontendFacade import com.reposilite.frontend.infrastructure.CustomFrontendHandler import com.reposilite.frontend.infrastructure.NotFoundHandler import com.reposilite.frontend.infrastructure.ResourcesFrontendHandler import com.reposilite.plugin.api.Plugin import com.reposilite.plugin.api.ReposiliteInitializeEvent import com.reposilite.plugin.api.ReposilitePlugin import com.reposilite.plugin.event import com.reposilite.plugin.facade import com.reposilite.web.api.HttpServerInitializationEvent import com.reposilite.web.api.ReposiliteRoutes import com.reposilite.web.api.RoutingSetupEvent import io.javalin.http.NotFoundResponse import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.exists @Plugin(name = "frontend", dependencies = ["local-configuration", "shared-configuration"], settings = FrontendSettings::class) internal class FrontendPlugin : ReposilitePlugin() { internal companion object { private const val STATIC_DIRECTORY = "static" private const val FRONTEND_DIRECTORY = "reposilite-frontend" } override fun initialize(): FrontendFacade { val sharedConfigurationFacade = facade<SharedConfigurationFacade>() val frontendSettings = sharedConfigurationFacade.getDomainSettings<FrontendSettings>() val localConfiguration = facade<LocalConfiguration>() val frontendFacade = FrontendFacade(localConfiguration.cacheContent, frontendSettings) event { event: ReposiliteInitializeEvent -> staticDirectory(event.reposilite) .takeIf { it.exists().not() } ?.run { Files.createDirectory(this) Files.copy(Reposilite::class.java.getResourceAsStream("/$STATIC_DIRECTORY/index.html")!!, resolve("index.html")) } } event { event: RoutingSetupEvent -> event.registerRoutes( mutableSetOf<ReposiliteRoutes>().also { routes -> if (frontendSettings.map { it.frontend }) { routes.add(ResourcesFrontendHandler(frontendFacade, FRONTEND_DIRECTORY)) } routes.add(CustomFrontendHandler(frontendFacade, staticDirectory(event.reposilite))) } )} event { event: HttpServerInitializationEvent -> event.javalin.exception(NotFoundResponse::class.java, NotFoundHandler(frontendFacade)) event.javalin.error(404, NotFoundHandler(frontendFacade)) } return frontendFacade } private fun staticDirectory(reposilite: Reposilite): Path = reposilite.parameters.workingDirectory.resolve(STATIC_DIRECTORY) }
0
Kotlin
0
0
e59d785c042792b46165149b693a94c23ba457db
3,457
reposilite
Apache License 2.0
search-client/src/commonTest/kotlin/com/jillesvangurp/ktsearch/IndexCreateTest.kt
jillesvangurp
494,038,243
false
{"Kotlin": 292386, "Jupyter Notebook": 4181, "Shell": 511}
package com.jillesvangurp.ktsearch import io.kotest.matchers.shouldBe import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlin.test.Test class IndexCreateTest: SearchTestBase() { @Test fun createIndex() = runTest { val index = randomIndexName() val response = client.createIndex(index) { dynamicTemplate("test_fields") { match = "test*" mapping("text") { fields { keyword("keyword") } } } dynamicTemplate("more_fields") { match = "more*" mapping("keyword") } mappings(true) { keyword("foo") number<Long>("bar") objField("foo", dynamic = "true") } meta { this["foo"] = "bar" } settings { replicas=0 shards=5 } } response.acknowledged shouldBe true client.getIndexMappings(index).let { it[index]?.jsonObject?.get("mappings")?.jsonObject?.get("dynamic_templates")?.jsonArray?.size shouldBe 2 } } }
7
Kotlin
13
72
404eaaf952ad8d2a1e5bac4fe2faff2d014318da
1,313
kt-search
MIT License
core/src/main/kotlin/io/github/shaksternano/borgar/core/collect/CollectionUtil.kt
shaksternano
482,092,089
false
{"Kotlin": 577124}
package io.github.shaksternano.borgar.core.collect import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow fun <T> MutableCollection<in T>.addAll(vararg elements: T): Boolean = addAll(elements) suspend fun <T, R> Iterable<T>.parallelMap(transform: suspend (T) -> R): List<R> = if (this is Collection && size <= 1) map { transform(it) } else coroutineScope { map { async { transform(it) } }.awaitAll() } suspend fun <T> Iterable<T>.parallelForEach(action: suspend (T) -> Unit) { if (this is Collection && size <= 1) forEach { action(it) } else parallelMap(action) } fun <K, V> MutableMap<K, V>.putAllKeys(keys: Iterable<K>, value: V) = keys.forEach { put(it, value) } inline fun <T> forEachNotNull( supplier: () -> T?, action: (T) -> Unit, ) { var value = supplier() while (value != null) { action(value) value = supplier() } } operator fun <T> Flow<T>.plus(other: Flow<T>): Flow<T> = flow { collect { emit(it) } other.collect { emit(it) } }
2
Kotlin
3
9
9966f86126e32b18fea3e5cc8456359745ca82d2
1,200
borgar
MIT License
src/commonMain/kotlin/guru/zoroark/lixy/matchers/LixyMatcherResult.kt
utybo
234,806,930
false
null
package guru.zoroark.lixy.matchers import guru.zoroark.lixy.LixyToken /** * Subclasses of this class represent the different possible outputs for * matchers. * @see LixyNoMatchResult * @see LixyIgnoreMatchResult * @see LixyMatchedTokenResult */ sealed class LixyMatcherResult /** * Indicates that the match was not successful, that there was no match. */ object LixyNoMatchResult : LixyMatcherResult() /** * Indicates that the match was successful, but no token should be created for * this match. * * @property tokenEndsAt Where the ignored token ends (exclusive, this is the * index where the lexer will resume) * @property nextStateBehavior The behavior to follow after processing this * match regarding states */ class LixyIgnoreMatchResult(val tokenEndsAt: Int, val nextStateBehavior: LixyNextStateBehavior) : LixyMatcherResult() /** * Indicates that the match was successful and a token was created. * * @property token The token that is the result of the match. */ class LixyMatchedTokenResult(val token: LixyToken, val nextStateBehavior: LixyNextStateBehavior) : LixyMatcherResult()
1
Kotlin
0
48
1849bb1d75c1c775c28b4e411fb705a4d642fc89
1,115
Lixy
Apache License 2.0
src/commonMain/kotlin/guru/zoroark/lixy/matchers/LixyMatcherResult.kt
utybo
234,806,930
false
null
package guru.zoroark.lixy.matchers import guru.zoroark.lixy.LixyToken /** * Subclasses of this class represent the different possible outputs for * matchers. * @see LixyNoMatchResult * @see LixyIgnoreMatchResult * @see LixyMatchedTokenResult */ sealed class LixyMatcherResult /** * Indicates that the match was not successful, that there was no match. */ object LixyNoMatchResult : LixyMatcherResult() /** * Indicates that the match was successful, but no token should be created for * this match. * * @property tokenEndsAt Where the ignored token ends (exclusive, this is the * index where the lexer will resume) * @property nextStateBehavior The behavior to follow after processing this * match regarding states */ class LixyIgnoreMatchResult(val tokenEndsAt: Int, val nextStateBehavior: LixyNextStateBehavior) : LixyMatcherResult() /** * Indicates that the match was successful and a token was created. * * @property token The token that is the result of the match. */ class LixyMatchedTokenResult(val token: LixyToken, val nextStateBehavior: LixyNextStateBehavior) : LixyMatcherResult()
1
Kotlin
0
48
1849bb1d75c1c775c28b4e411fb705a4d642fc89
1,115
Lixy
Apache License 2.0
core/notifications/src/main/kotlin/com/matabel/core/notifications/NotificationBuilderImpl.kt
anthony-cannon
642,328,700
false
null
package com.matabel.core.notifications import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationChannelGroup import android.app.NotificationManager import android.content.Context import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.matabel.core.notifications.model.LBNotificationChannel import com.matabel.core.notifications.model.LBNotificationGroups import com.matabel.core.notifications.model.LBNotificationType import javax.inject.Inject class NotificationBuilderImpl @Inject constructor() : NotificationBuilder { override fun show(context: Context, type: LBNotificationType) { with(NotificationManagerCompat.from(context)) { if (ActivityCompat.checkSelfPermission( context, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { return } notify(type.id, build(context, type)) } } private fun build(context: Context, type: LBNotificationType): Notification { createNotificationSettings(context) return NotificationCompat.Builder(context, type.channelId) .setContentTitle(type.title) .setContentText(type.text) .setSmallIcon(R.drawable.ic_launcher_foreground) .setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_STATUS) .setOngoing(true) .build() } override fun cancel(context: Context, type: LBNotificationType) { with(NotificationManagerCompat.from(context)) { cancel(type.id) } } private fun createNotificationSettings(appContext: Context) { val groups = LBNotificationGroups.values() .map { NotificationChannelGroup(it.groupId, it.groupName) } val channels = LBNotificationChannel.values() .map { NotificationChannel( it.channelId, it.channelName, NotificationManager.IMPORTANCE_HIGH ).apply { description = "Notifications about the general app" group = it.groupId } } val notificationManager = appContext.getSystemService( NotificationManager::class.java ) as NotificationManager notificationManager.createNotificationChannelGroups(groups) notificationManager.createNotificationChannels(channels) } }
0
Kotlin
0
0
226ad1f20a6f35f2a7fb01744a9f04bfd1c47003
2,723
left-behind
MIT License
app/src/main/java/com/example/fiadosafe/Presentation/ClientsListViewModel.kt
BrunoAnndrade
651,568,365
false
null
package com.example.fiadosafe.Presentation import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.fiadosafe.FiadoSafeApplication import com.example.fiadosafe.data.Clients import com.example.fiadosafe.data.ClientsDao import com.example.fiadosafe.data.ClientsWithPaymentAndPurchase import com.example.fiadosafe.data.PaymentAndPurchase class ClientsListViewModel(private val clientsDao: ClientsDao) : ViewModel() { val clientsListLiveData:LiveData<List<Clients>> = clientsDao.getAllLiveData() companion object { fun create(application: Application): ClientsListViewModel { val dataBAseInstance = (application as FiadoSafeApplication).getAppDataBase() val dao = dataBAseInstance.clientsDao() return ClientsListViewModel(dao) } } }
0
Kotlin
0
0
7032248ece6ee3e67849012916ae9c441bcc7b50
903
FiadoSafe
MIT License
src/commonMain/kotlin/com/bkahlert/kommons/kaomoji/categories/RollOver.kt
bkahlert
323,048,013
false
null
@file:Suppress( "KDocMissingDocumentation", "ObjectPropertyName", "RemoveRedundantBackticks", "unused", "NonAsciiCharacters", "SpellCheckingInspection" ) package com.bkahlert.kommons.kaomoji.categories import com.bkahlert.kommons.kaomoji.Category import com.bkahlert.kommons.kaomoji.Kaomoji import kotlin.js.JsName public object RollOver : Category() { @JsName("rollOver00") public val `(o_△_)o`: Kaomoji by parsing("(o_△_)o") @JsName("rollOver01") public val `/(_-_)l`: Kaomoji by parsing("/(_-_)l") @JsName("rollOver02") public val `(﹕3_ヽ)_`: Kaomoji by parsing("(:3_ヽ)_") @JsName("rollOver03") public val `_(﹕3」∠)_`: Kaomoji by parsing("_(:3」∠)_") @JsName("rollOver04") public val `_(┐「ε﹕)_`: Kaomoji by parsing("_(┐「ε:)_") @JsName("rollOver05") public val `_(﹕3」∠)_`: Kaomoji by parsing("_(:3」∠)_") @JsName("rollOver06") public val `(﹕3 _ )=`: Kaomoji by parsing("(:3 _ )=") @JsName("rollOver07") public val `_(┐「ε﹕)_♡`: Kaomoji by parsing("_(┐「ε:)_♡") @JsName("rollOver08") public val `ヽ(﹕3ノ ヽ)ノ`: Kaomoji by parsing("ヽ(:3ノ ヽ)ノ") @JsName("rollOver09") public val `ヾ(﹕3ノシヾ)ノシ`: Kaomoji by parsing("ヾ(:3ノシヾ)ノシ") @JsName("rollOver10") public val `_(:3 」∠ )_`: Kaomoji by parsing("_(:3 」∠ )_") @JsName("rollOver11") public val `_/ ̄│(冫、)-c`: Kaomoji by parsing("_/ ̄|(冫、)-c") @JsName("rollOver12") public val `( ( (((_⊿_)`: Kaomoji by parsing("( ( (((_⊿_)") @JsName("rollOver13") public val `_(﹕D」┌)⁼³₌₃`: Kaomoji by parsing("_(:D」┌)⁼³₌₃") @JsName("rollOver14") public val `((└(﹕3」┌)┘))`: Kaomoji by parsing("((└(:3」┌)┘))") @JsName("rollOver15") public val `(﹕3っ)っ -=三[]`: Kaomoji by parsing("(:3っ)っ -=三[]") @JsName("rollOver16") public val `○)))ヘ(^・・^=)~`: Kaomoji by parsing("○)))ヘ(^・・^=)~") @JsName("rollOver17") public val `((o_△_)o)^▽^;)`: Kaomoji by parsing("((o_△_)o)^▽^;)") @JsName("rollOver18") public val `( ̄∇ ̄;)))( ((((;_⊿_)`: Kaomoji by parsing("( ̄∇ ̄;)))( ((((;_⊿_)") @JsName("rollOver19") public val `(o°▽°)o(o_△_)o(o°▽°)o`: Kaomoji by parsing("(o°▽°)o(o_△_)o(o°▽°)o") @JsName("rollOver20") public val `(((․-․)(﹕I )(゚‐゚)( I﹕)`: Kaomoji by parsing("(((.-.)(:I )(゚‐゚)( I:)") @JsName("rollOver21") public val `((((((‥)(﹕ )(¨)( ﹕)(*‥)`: Kaomoji by parsing("((((((‥)(: )(¨)( :)(*‥)") @JsName("rollOver22") public val `(┐「ε﹕)_三┌(․ω․)┐三_(﹕3 」∠)_`: Kaomoji by parsing("(┐「ε:)_三┌(.ω.)┐三_(:3 」∠)_") @JsName("rollOver23") public val `(․․)(・․)(﹕ )(¨)( ﹕)(․・)(․․)`: Kaomoji by parsing("(..)(・.)(: )(¨)( :)(.・)(..)") @JsName("rollOver24") public val `o_ _)o(o- -)o(o°▽°)o(o_△_)o(o_ _)o․。o○`: Kaomoji by parsing("o_ _)o(o- -)o(o°▽°)o(o_△_)o(o_ _)o.。o○") @JsName("rollOver25") public val `(°o°)(°o。)(。o。)(。o°)(°o°)(°o。)(。o。)(。o°)`: Kaomoji by parsing("(°o°)(°o。)(。o。)(。o°)(°o°)(°o。)(。o。)(。o°)") @JsName("rollOver26") public val `(․-․)(﹕I )(゜-゜)( I﹕) (․-․)(﹕I )(゜-゜)( I﹕)`: Kaomoji by parsing("(.-.)(:I )(゜-゜)( I:) (.-.)(:I )(゜-゜)( I:)") @JsName("rollOver27") public val `(((((;___▲___))(((((;___▲___))(( ̄▼ ̄ ;)))))`: Kaomoji by parsing("(((((;___▲___))(((((;___▲___))(( ̄▼ ̄ ;)))))") @JsName("rollOver28") public val `三(`ω`)三( ε﹕ )三(․ω․)三( ﹕3 )三(`ω`)三( ε﹕ )三(․ω․)三( ﹕3 )`: Kaomoji by parsing("三('ω')三( ε: )三(.ω.)三( :3 )三('ω')三( ε: )三(.ω.)三( :3 )") @JsName("rollOver29") public val `(`ω`) 三 ( ε﹕ ) 三 (․ ․) 三 ( ﹕з ) 三 (`ω`) 三 ( ε﹕ ) 三 (․ ․) 三 。・*・﹕≡( ε﹕)`: Kaomoji by parsing("('ω') 三 ( ε: ) 三 (. .) 三 ( :з ) 三 ('ω') 三 ( ε: ) 三 (. .) 三 。・*・:≡( ε:)") }
7
Kotlin
0
9
35e2ac1c4246decdf7e7a1160bfdd5c9e28fd066
3,506
kommons
MIT License
src/day24/Interactive.kt
g0dzill3r
576,012,003
false
null
package day24 fun main (args: Array<String>) { val example = true var valley = loadValley(example) val blizzards = { p: Point -> val dirs = valley.getBlizzards (p) when (dirs.size) { 0 -> '.' 1 -> dirs[0].encoded in 1..9 -> "${dirs.size}"[0] else -> 'B' } } println ("Valley interpreter, v0.1") while (true) { print ("> ") val input = readln().trim () if (input.isEmpty()) { continue } val cmds = input.split (" ") val pos = valley.positions[0] as Point when (cmds[0]) { "d" -> valley.dump () "t" -> valley.tick () "td" -> { valley.tick() valley.dump() } "p" -> valley.possibleMoves(pos).forEach { println (it) } "pd" -> { val ps = valley.possibleMoves(pos) println (ps) println (valley.render { if (ps.contains(it)) { append ('P') } else if (it == valley.startPoint || it == valley.endPoint) { append ('.') } else { append (blizzards (it)) } }) } "up" -> valley.positions[0] = pos.move (Direction.UP) "down" -> valley.positions[0] = pos.move (Direction.DOWN) "left" -> valley.positions[0] = pos.move (Direction.LEFT) "right" -> valley.positions[0] = pos.move (Direction.RIGHT) "dirs" -> Direction.values().forEach { println ("$it = !${it.invert}") } "l" -> valley.legalMoves (valley.possibleMoves (pos)).forEach { println (it) } "ld" -> { val ps = valley.possibleMoves(pos) val ls = valley.legalMoves (ps) println (valley.render { if (ls.contains (it)) { append ('L') } else if (ps.contains(it)) { append ('P') } else if (it== valley.startPoint || it == valley.endPoint) { append ('.') } else { append (blizzards (it)) } }) } "alt" -> { val alternate = input.split (" ") val index = alternate[1].toInt () valley = Valley.parse (ALTERNATES[index]) } "b?" -> { for (i in valley.blizzards.indices) { println ("${valley.toPoint (i)}: ${valley.blizzards[i]}") } } "example" -> valley = loadValley(true) "actual" -> valley = loadValley (false) "?" -> { valley.run { println ("width=$width, height=$height") println ("start=$start, end=$end") println ("startPoint=$startPoint") println ("endPoint=$endPoint") println ("pos=$pos") } } "r" -> valley.round () "rd" -> { valley.round () valley.dump () } "run1" -> { while (! valley.positions.contains (valley.endPoint)) { valley.round () } println (valley.time) } "b" -> { valley.blizzards.forEach { println (it) } } else -> println ("Unrecognized: $input") } // NOT REACHED } } private val ALTERNATES = listOf<String> ( """ #.## #>^# #v<# ##.# """.trimIndent(), """ #.##### #.....# #>....# #.....# #...v.# #.....# #####.# """.trimIndent() ) // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
4,012
advent_of_code_2022
Apache License 2.0
app/src/main/java/com/stocksexchange/android/model/Option.kt
nscoincommunity
277,168,471
true
{"Kotlin": 2814235}
package com.stocksexchange.android.model data class Option( val id: Int, val iconDrawableId: Int, val title: String, val status: Status = Status.DEFAULT ) { enum class Status { DEFAULT, HIGHLIGHTED } }
0
null
0
0
52766afab4f96506a2d9ed34bf3564b6de7af8c3
248
Android-app
MIT License
src/main/kotlin/com/target/nativememoryallocator/buffer/OnHeapMemoryBuffer.kt
target
489,390,330
false
{"Kotlin": 211151}
package com.target.nativememoryallocator.buffer import java.nio.ByteBuffer /** * An onheap memory buffer that expands on demand when setReadableBytes is called. * * Backed by a [ByteArray]. * * OnHeapMemoryBuffer is not synchronized - each instance should be used in a single thread, or the user must provide synchronization. */ interface OnHeapMemoryBuffer { /** * The [ByteArray] backing this buffer. */ val array: ByteArray /** * Get readable bytes. * * @return readable bytes. */ fun getReadableBytes(): Int /** * Set readable bytes to [newReadableBytes]. * * This buffer will expand on demand when this method is called. * * @param newReadableBytes new readable bytes. */ fun setReadableBytes(newReadableBytes: Int) /** * Return a view of this buffer as a [ByteBuffer]. * * This method does not copy the contents of this buffer. * * @return [ByteBuffer] view of this buffer. */ fun asByteBuffer(): ByteBuffer /** * Return a copy of this buffer as a [ByteArray]. * * @return a copy of this buffer as a [ByteArray]. */ fun toTrimmedArray(): ByteArray }
0
Kotlin
4
7
9244efc1a54d6c6ee9a850f93a7edb0e10b60e88
1,219
native_memory_allocator
Apache License 2.0
app/src/main/java/kr/ac/gachon/sw/safenoisecanceling/models/Sound.kt
Aftermoon-dev
436,584,571
false
null
package kr.ac.gachon.sw.safenoisecanceling.models import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Sound( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(name="type") val soundType: String, @ColumnInfo(name="score") val score: Float, @ColumnInfo(name="time") val time: Long )
0
Kotlin
0
0
3ae6a01d73d482523cc02f2e8996f67474c9cdbe
371
SafeNoiseCanceling
Apache License 2.0
domain/src/main/java/com/example/domain/reposImpl/LinkRepoImpl.kt
City-Zouitel
576,223,915
false
null
package com.example.domain.reposImpl import com.example.domain.repos.LinkRepo import com.example.local.daos.LinkDao import com.example.local.model.Link import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.scopes.ViewModelScoped import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import javax.inject.Inject @ViewModelScoped class LinkRepoImpl @Inject constructor( private val dao: LinkDao ): LinkRepo { override val getAllLinks: Flow<List<Link>> get() = dao.getAllLinks() override suspend fun addLink(link: Link) { coroutineScope { launch { dao.addLink(link) } } } override suspend fun deleteLink(link: Link) { coroutineScope { launch { dao.deleteLink(link) } } } }
27
Kotlin
6
43
07734f993db841e6ad56f484379ea399e30dc55e
800
JetNote
Apache License 2.0
app/src/main/java/com/realtomjoney/pyxlmoose/listeners/ColorPalettesFragmentListener.kt
realtomjoney
419,545,692
false
null
package com.realtomjoney.pyxlmoose.listeners import com.realtomjoney.pyxlmoose.models.ColorPalette interface ColorPalettesFragmentListener { fun onColorPaletteTapped(selectedColorPalette: ColorPalette) }
15
Kotlin
2
30
ecea3c6d807483c31fa61fbf8d127e9ed92d1258
209
PyxlMoose
MIT License
app/src/main/java/com/apolloclinicmalda/features/chat/presentation/AddGroupFragment.kt
DebashisINT
592,683,732
false
null
package com.apolloclinicmalda.features.chat.presentation import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.os.Bundle import android.speech.RecognizerIntent import androidx.appcompat.widget.AppCompatImageView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import com.apolloclinicmalda.R import com.apolloclinicmalda.app.MaterialSearchView import com.apolloclinicmalda.app.NetworkConstant import com.apolloclinicmalda.app.Pref import com.apolloclinicmalda.app.SearchListener import com.apolloclinicmalda.app.utils.AppUtils import com.apolloclinicmalda.base.BaseResponse import com.apolloclinicmalda.base.presentation.BaseActivity import com.apolloclinicmalda.base.presentation.BaseFragment import com.apolloclinicmalda.features.chat.api.ChatRepoProvider import com.apolloclinicmalda.features.chat.model.ChatUserResponseModel import com.apolloclinicmalda.features.chat.model.GroupUserDataModel import com.apolloclinicmalda.features.chat.model.GroupUserResponseModel import com.apolloclinicmalda.features.dashboard.presentation.DashboardActivity import com.apolloclinicmalda.widgets.AppCustomEditText import com.apolloclinicmalda.widgets.AppCustomTextView import com.pnikosis.materialishprogress.ProgressWheel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber import java.lang.Exception import java.util.* import kotlin.collections.ArrayList // Revision History // 1.0 AddGroupFragment saheli 24-02-2032 AppV 4.0.7 mantis 0025683 class AddGroupFragment : BaseFragment() { private lateinit var mContext: Context private lateinit var progress_wheel: ProgressWheel private lateinit var tv_no_data: AppCustomTextView private lateinit var et_grp_name: AppCustomEditText private lateinit var iv_done_btn: AppCompatImageView private lateinit var rv_selected_list: RecyclerView private lateinit var rv_user_list: RecyclerView private lateinit var rl_add_group: RelativeLayout private var grpUserAdapter: GroupUserListAdapter?= null private var selectedUserAdapter: SelectedUserListAdapter?= null private var groupUserList: ArrayList<GroupUserDataModel>?= null override fun onAttach(context: Context) { super.onAttach(context) mContext = context } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_add_group, container, false) initView(view) getChatUserListApi() (mContext as DashboardActivity).setSearchListener(object : SearchListener { override fun onSearchQueryListener(query: String) { if (query.isBlank()) { grpUserAdapter?.refreshList(groupUserList!!) } else { grpUserAdapter?.filter?.filter(query) } } }) // 1.0 MicroLearningListFragment AppV 4.0.7 mantis 0025683 start (mContext as DashboardActivity).searchView.setVoiceIcon(R.drawable.ic_mic) (mContext as DashboardActivity).searchView.setOnVoiceClickedListener({ startVoiceInput() }) // 1.0 MicroLearningListFragment AppV 4.0.7 mantis 0025683 end return view } // 1.0 MicroLearningListFragment AppV 4.0.7 mantis 0025683 start private fun startVoiceInput() { try { val intent: Intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM ) //intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,"hi") intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH) intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?") try { startActivityForResult(intent, MaterialSearchView.REQUEST_VOICE) } catch (a: ActivityNotFoundException) { a.printStackTrace() } } catch (ex: Exception) { ex.printStackTrace() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){ super.onActivityResult(requestCode, resultCode, data) if(requestCode == MaterialSearchView.REQUEST_VOICE){ try { val result = data!!.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) var t= result!![0] (mContext as DashboardActivity).searchView.setQuery(t,false) } catch (ex: Exception) { ex.printStackTrace() } // tv_search_frag_order_type_list.setText(t) // tv_search_frag_order_type_list.setSelection(t.length); } } // 1.0 MicroLearningListFragment AppV 4.0.7 mantis 0025683 end private fun initView(view: View) { view.apply { progress_wheel = findViewById(R.id.progress_wheel) tv_no_data = findViewById(R.id.tv_no_data) et_grp_name = findViewById(R.id.et_grp_name) iv_done_btn = findViewById(R.id.iv_done_btn) rv_selected_list = findViewById(R.id.rv_selected_list) rv_user_list = findViewById(R.id.rv_user_list) rl_add_group = findViewById(R.id.rl_add_group) } progress_wheel.stopSpinning() rv_user_list.layoutManager = LinearLayoutManager(mContext) rv_selected_list.layoutManager = LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false) selectedUserAdapter = SelectedUserListAdapter(mContext) { it, position -> for (i in groupUserList?.indices!!) { if (groupUserList?.get(i)?.id == it.id) { groupUserList?.get(i)?.isSelected = false grpUserAdapter?.refreshList(groupUserList!!) selectedUserAdapter?.removeItem(position) break } } } rv_selected_list.adapter = selectedUserAdapter rl_add_group.setOnClickListener(null) iv_done_btn.setOnClickListener { when { TextUtils.isEmpty(et_grp_name.text.toString().trim()) -> (mContext as DashboardActivity).showSnackMessage(getString(R.string.error_enter_grp_name)) selectedUserAdapter?.selectedUserList!!.isEmpty() -> (mContext as DashboardActivity).showSnackMessage(getString(R.string.error_select_user)) else -> callAddGrpApi() } } } private fun getChatUserListApi() { if (!AppUtils.isOnline(mContext)) { (mContext as DashboardActivity).showSnackMessage(getString(R.string.no_internet)) return } progress_wheel.spin() val repository = ChatRepoProvider.provideChatRepository() BaseActivity.compositeDisposable.add( repository.getGroupUserList() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ result -> val response = result as GroupUserResponseModel Timber.d("Get Group User List STATUS: " + response.status) if (response.status == NetworkConstant.SUCCESS) { progress_wheel.stopSpinning() tv_no_data.visibility = View.GONE groupUserList = response.group_user_list setAdapter() } else { progress_wheel.stopSpinning() (mContext as DashboardActivity).showSnackMessage(response.message!!) } }, { error -> error.printStackTrace() progress_wheel.stopSpinning() if (error != null) Timber.d("Get Group User List ERROR: " + error.localizedMessage) (mContext as DashboardActivity).showSnackMessage(getString(R.string.something_went_wrong)) }) ) } private fun callAddGrpApi() { if (!AppUtils.isOnline(mContext)) { (mContext as DashboardActivity).showSnackMessage(getString(R.string.no_internet)) return } var ids = "" selectedUserAdapter?.selectedUserList?.forEachIndexed { i, it -> if (i == selectedUserAdapter?.selectedUserList?.size!! - 1) ids += it.id else ids = ids + it.id + "," } ids = ids + "," + Pref.user_id progress_wheel.spin() val repository = ChatRepoProvider.provideChatRepository() BaseActivity.compositeDisposable.add( repository.addGroup(AppUtils.encodeEmojiAndText(et_grp_name.text.toString().trim()), ids) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ result -> val response = result as BaseResponse Timber.d("Add Group STATUS: " + response.status) progress_wheel.stopSpinning() (mContext as DashboardActivity).showSnackMessage(response.message!!) if (response.status == NetworkConstant.SUCCESS) { (mContext as DashboardActivity).isRefreshChatUserList = true (mContext as DashboardActivity).onBackPressed() } }, { error -> error.printStackTrace() progress_wheel.stopSpinning() if (error != null) Timber.d("Add Group ERROR: " + error.localizedMessage) (mContext as DashboardActivity).showSnackMessage(getString(R.string.something_went_wrong)) }) ) } private fun setAdapter() { grpUserAdapter = GroupUserListAdapter(mContext, groupUserList) { for (i in groupUserList?.indices!!) { if (groupUserList?.get(i)?.id == it.id) { if (groupUserList?.get(i)?.isSelected!!) { groupUserList?.get(i)?.isSelected = false for (j in selectedUserAdapter?.selectedUserList!!.indices) { if (it.id == selectedUserAdapter?.selectedUserList?.get(j)?.id) { selectedUserAdapter?.removeItem(j) break } } } else { groupUserList?.get(i)?.isSelected = true selectedUserAdapter?.addItem(groupUserList?.get(i)!!) } break } } /*if (groupUserList?.get(it)?.isSelected!!) { groupUserList?.get(it)?.isSelected = false for (i in selectedUserAdapter?.selectedUserList!!.indices) { if (groupUserList?.get(it)?.id == selectedUserAdapter?.selectedUserList?.get(i)?.id) { selectedUserAdapter?.removeItem(i) break } } } else { groupUserList?.get(it)?.isSelected = true selectedUserAdapter?.addItem(groupUserList?.get(it)!!) }*/ grpUserAdapter?.refreshList(groupUserList!!) } rv_user_list.adapter = grpUserAdapter } }
0
Kotlin
0
0
f34844a556c5651f8e49b786918b06c3b5cce9db
12,349
ApolloClinic_Malda
Apache License 2.0
app/src/main/java/com/adishakti/repohunt/components/NoData.kt
Sharma-Prince
801,077,283
false
{"Kotlin": 68948}
package com.adishakti.repohunt.components 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.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun NoData( message: String, modifier: Modifier = Modifier, icon: ImageVector? = null, iconContentDescription: String? = null ) { Column( modifier = modifier .fillMaxSize() .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { if (icon != null) { Icon( imageVector = icon, contentDescription = iconContentDescription, modifier = Modifier.size(48.dp), tint = MaterialTheme.colorScheme.secondary ) Spacer(modifier = Modifier.height(16.dp)) } Text( text = message, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() ) } }
0
Kotlin
0
1
70fc082bacf8b11581a2f03a3fe588a6da61d2a8
1,797
RepoHunt
MIT License
app/src/main/java/com/zigis/paleontologas/application/data/BaseDao.kt
edgar-zigis
240,962,785
false
null
package com.zigis.paleontologas.application.data import androidx.room.* import androidx.sqlite.db.SupportSQLiteQuery @Dao interface BaseDao<T> { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertAll(list: List<T>) @RawQuery suspend fun findOne(query: SupportSQLiteQuery): T @RawQuery suspend fun findAll(query: SupportSQLiteQuery): List<T> @RawQuery suspend fun deleteAll(query: SupportSQLiteQuery): Int }
0
Kotlin
16
126
4ee09d3c6f29278aa1762e71f7db6a84d0ca3dea
458
Paleontologas
Apache License 2.0
translatorCompiler/src/main/kotlin/net/earthcomputer/multiconnect/compiler/CompileException.kt
LostLuma
504,882,998
true
{"Java Properties": 2, "Batchfile": 2, "Gradle": 5, "Shell": 3, "Text": 26, "Markdown": 3, "Ignore List": 1, "JSON": 61, "Java": 808, "Gradle Kotlin DSL": 6, "Kotlin": 67, "XML": 3, "YAML": 3, "Groovy": 1, "Graphviz (DOT)": 3, "SVG": 3, "INI": 1, "Python": 3, "JavaScript": 1}
package net.earthcomputer.multiconnect.compiler class CompileException(desc: String) : RuntimeException(desc) { }
0
null
0
0
ee5cbf489d9d03e9cd12b43e26d75e367666d973
115
multiconnect
MIT License
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonProjectIndexingHistoryTimes.kt
gaiazov
269,263,276
false
{"Text": 4081, "XML": 4715, "Ant Build System": 13, "Shell": 533, "Markdown": 309, "Ignore List": 80, "Git Attributes": 9, "Batchfile": 30, "SVG": 2073, "Java": 66131, "C++": 20, "HTML": 2399, "Kotlin": 5911, "DTrace": 1, "Gradle": 58, "Java Properties": 109, "INI": 279, "JFlex": 27, "CSS": 53, "Objective-C": 19, "Groovy": 3387, "XSLT": 112, "JavaScript": 158, "JSON": 1103, "desktop": 1, "Python": 10683, "JAR Manifest": 14, "PHP": 46, "YAML": 387, "C#": 37, "Smalltalk": 17, "Diff": 129, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "CoffeeScript": 3, "JSON with Comments": 59, "Vue": 16, "OpenStep Property List": 42, "PlantUML": 3, "Protocol Buffer": 2, "fish": 1, "EditorConfig": 212, "Dockerfile": 2, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 80, "Starlark": 2, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "GraphQL": 37, "C": 42, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 6, "Microsoft Visual Studio Solution": 6, "VBScript": 1, "NSIS": 6, "TOML": 2, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.diagnostic.dto @Suppress("unused", "used for JSON") data class JsonProjectIndexingHistoryTimes( val indexingTime: JsonTime, val scanFilesTime: JsonTime, val pushPropertiesTime: JsonTime, val indexExtensionsTime: JsonTime, val indexingStart: PresentableTime, val indexingEnd: PresentableTime, val pushPropertiesStart: PresentableTime, val pushPropertiesEnd: PresentableTime, val indexExtensionsStart: PresentableTime, val indexExtensionsEnd: PresentableTime, val scanFilesStart: PresentableTime, val scanFilesEnd: PresentableTime )
1
null
1
1
494310d2ec94e226e915efda681d20ee92fbe412
732
intellij-community
Apache License 2.0
play-default-fallback/src/main/kotlin/org/example/df/demos/interfaces/ACFIKotlinInterfaceKotlinDemo.kt
dowenliu-xyz
808,693,582
false
{"Gradle Kotlin DSL": 13, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java": 399, "YAML": 4, "INI": 6, "Kotlin": 354, "Java Properties": 1}
package org.example.df.demos.interfaces import com.alibaba.csp.sentinel.annotation.SentinelResource import org.example.df.biz.Greeting.doGreeting import org.springframework.stereotype.Component /** * case impl: Annotation in Class and Fallback in Interface * <br/> * Aspect takes effect, but CAN NOT find fallback method. */ @Component class ACFIKotlinInterfaceKotlinDemo : ACFIKotlinInterfaceForKotlin { @SentinelResource(value = "demo", defaultFallback = "defaultFallback") override fun greeting(name: String?): String { return doGreeting(name) } }
0
Java
0
1
8b6df6f693a0c7efa25c3a7d634823d7b8ec4915
577
sentinel-plays
Apache License 2.0
libnavui-dropin/src/main/java/com/mapbox/navigation/dropin/map/longpress/RoutePreviewLongPressMapComponent.kt
mapbox
87,455,763
false
null
package com.mapbox.navigation.dropin.map.longpress import com.mapbox.maps.MapView import com.mapbox.maps.plugin.gestures.OnMapLongClickListener import com.mapbox.maps.plugin.gestures.gestures import com.mapbox.navigation.core.MapboxNavigation import com.mapbox.navigation.dropin.navigationview.NavigationViewContext import com.mapbox.navigation.dropin.util.HapticFeedback import com.mapbox.navigation.ui.app.internal.Store import com.mapbox.navigation.ui.app.internal.destination.Destination import com.mapbox.navigation.ui.app.internal.destination.DestinationAction import com.mapbox.navigation.ui.app.internal.routefetch.RoutePreviewAction import com.mapbox.navigation.ui.base.lifecycle.UIComponent import com.mapbox.navigation.utils.internal.logW internal class RoutePreviewLongPressMapComponent( private val store: Store, private val mapView: MapView, private val context: NavigationViewContext ) : UIComponent() { private var hapticFeedback: HapticFeedback? = null override fun onAttached(mapboxNavigation: MapboxNavigation) { super.onAttached(mapboxNavigation) hapticFeedback = HapticFeedback.create(mapboxNavigation.navigationOptions.applicationContext) mapView.gestures.addOnMapLongClickListener(longClickListener) } override fun onDetached(mapboxNavigation: MapboxNavigation) { super.onDetached(mapboxNavigation) mapView.gestures.removeOnMapLongClickListener(longClickListener) hapticFeedback = null } private val longClickListener = OnMapLongClickListener { point -> if (context.options.enableMapLongClickIntercept.value) { if (store.state.value.location != null) { store.dispatch(DestinationAction.SetDestination(Destination(point))) store.dispatch(RoutePreviewAction.FetchRoute) hapticFeedback?.tick() } else { logW(TAG, "Current location is unknown so map long press does nothing") } } false } private companion object { private val TAG = this::class.java.simpleName } }
505
null
319
621
ad73c6011348cb9b24b92a369024ca06f48845ab
2,131
mapbox-navigation-android
Apache License 2.0
leetcode/p0791/20240311/Solution.kt
suhwanhwang
199,259,343
false
{"Text": 138, "Ignore List": 2, "Markdown": 1, "Makefile": 2, "Java": 638, "C++": 118, "YAML": 15, "JSON": 311, "Shell": 56, "Gradle": 12, "Python": 6, "Jupyter Notebook": 10, "XML": 4, "Kotlin": 232, "Swift": 67, "INI": 1}
class Solution { fun customSortString(order: String, s: String): String { val map = IntArray(26) {0} for(c in s) { map[c - 'a']++ } val sb = StringBuilder() for (c in order) { for(i in 0 until map[c - 'a']) sb.append(c) map[c - 'a'] = 0 } for (i in 0 until map.size) { for(j in 0 until map[i]) sb.append('a' + i) } return sb.toString() } }
0
Java
0
0
0cc37fd7b9350a2a9f01f4828e3f4a22cf2121e5
486
problem-solving
MIT License
src/main/kotlin/cn/yiiguxing/plugin/translate/action/TitleBarActionRegistrar.kt
holiday-toby
107,372,591
true
{"Gradle Kotlin DSL": 2, "SVG": 81, "Markdown": 8, "Java Properties": 5, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 5, "Kotlin": 215, "Java": 7, "XML": 33, "YAML": 7, "JSON": 1}
package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.util.IdeVersion import cn.yiiguxing.plugin.translate.util.Plugin import com.intellij.ide.AppLifecycleListener import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.Constraints import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.ActionManagerImpl class TitleBarActionRegistrar : AppLifecycleListener, DynamicPluginListener { override fun appFrameCreated(commandLineArgs: MutableList<String>) { if (IdeVersion >= IdeVersion.IDE2022_2) { registerAction() } } override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) { if (IdeVersion >= IdeVersion.IDE2022_2 && pluginDescriptor.pluginId.idString == Plugin.PLUGIN_ID) { registerAction() } } private fun registerAction() { val actionManager = ActionManager.getInstance() as ActionManagerImpl val group = actionManager.getAction(TITLE_BAR_ACTION_GROUP_ID) as? DefaultActionGroup ?: return val action = actionManager.getAction(TRANSLATION_TITLE_BAR_ACTION_ID) ?: return if (!group.containsAction(action)) { actionManager.addToGroup(group, action, Constraints.FIRST) } } companion object { private const val TRANSLATION_TITLE_BAR_ACTION_ID = "TranslationTitleBar" private const val TITLE_BAR_ACTION_GROUP_ID = "ExperimentalToolbarActions" } }
0
Kotlin
0
0
8714eeb23eebe0391d99a71b6649e2439360d833
1,640
TranslationPlugin
MIT License
src/commonMain/kotlin/money/terra/client/lcd/api/TreasuryApi.kt
buzlinklabs
260,423,602
false
{"Gradle Kotlin DSL": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 72, "Java": 3}
package money.terra.client.lcd.api import money.terra.client.HttpClient import money.terra.model.ResultWrapper class TreasuryApi( private val client: HttpClient ) { suspend fun getTaxRate(): ResultWrapper<String> { return client.get("/treasury/tax_rate") } suspend fun getTaxCapacity(denom: String): ResultWrapper<String> { return client.get("/treasury/tax_cap/$denom") } }
1
null
1
1
82a47540c4dded49989c71d9743834051dfbfc32
413
terra-sdk
Apache License 2.0
src/main/kotlin/com/demonwav/mcdev/nbt/lang/format/NbttParameterNameHints.kt
robertizotov-zz
101,105,621
false
{"Gradle": 1, "Markdown": 1, "Gradle Kotlin DSL": 1, "Text": 15, "Java Properties": 3, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "XML": 37, "YAML": 2, "INI": 12, "Java": 3, "Groovy": 4, "HAProxy": 2, "Kotlin": 450, "HTML": 28, "JFlex": 2}
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.gen.psi.NbttByteArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttCompound import com.demonwav.mcdev.nbt.lang.gen.psi.NbttIntArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttList import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.InlayParameterHintsProvider import com.intellij.psi.PsiElement class NbttParameterNameHints : InlayParameterHintsProvider { override fun getParameterHints(element: PsiElement): MutableList<InlayInfo> { val list = mutableListOf<InlayInfo>() if (element is NbttCompound) { val size = element.getNamedTagList().size list.add(InlayInfo("$size ${if (size == 1) "child" else "children"}", element.textRange.startOffset + 1)) } else if (element is NbttList) { val size = element.getListParams()?.tagList?.size ?: 0 list.add(InlayInfo("$size ${if (size == 1) "child" else "children"}", element.textRange.startOffset + 1)) } else if (element is NbttByteArray) { val size = element.getByteParams()?.byteList?.size ?: 0 list.add(InlayInfo( "$size ${if (size == 1) "child" else "children"}", element.node.getChildren(null)[1].textRange.startOffset + 1 )) } else if (element is NbttIntArray) { val size = element.getIntParams()?.intList?.size ?: 0 list.add(InlayInfo( "$size ${if (size == 1) "child" else "children"}", element.node.getChildren(null)[1].textRange.startOffset + 1 )) } return list } override fun getHintInfo(element: PsiElement) = null override fun getDefaultBlackList() = mutableSetOf<String>() }
1
null
1
1
9b91deed668fce98cd21474b9135ec9b92212c2b
1,907
MinecraftDevIntelliJ
MIT License
chapter5-Translator/app/src/main/java/me/adswt518/translator/MainActivity.kt
ADSWT518
420,092,466
false
null
package me.adswt518.translator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Message import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.TextView import com.google.gson.GsonBuilder import me.adswt518.translator.api.YoudaoBean import me.adswt518.translator.interceptor.TimeConsumeInterceptor import okhttp3.* import java.io.IOException class MainActivity : AppCompatActivity() { var requestBtn: Button? = null var inputText: EditText? = null var outputText: TextView? = null val okhttpListener = object : EventListener() { override fun dnsStart(call: Call, domainName: String) { super.dnsStart(call, domainName) Log.i("Translator", "Dns Search: $domainName") } override fun responseBodyStart(call: Call) { super.responseBodyStart(call) Log.i("Translator", "Response Start") } } val client: OkHttpClient = OkHttpClient .Builder() .addInterceptor(TimeConsumeInterceptor()) .eventListener(okhttpListener).build() val gson = GsonBuilder().create() companion object { const val STATUS_FINISH_TRANSLATION = 0 const val RESULT = "result" } val handler: Handler = Handler(Looper.getMainLooper()) { msg -> when (msg.what) { STATUS_FINISH_TRANSLATION -> { outputText?.text = "${msg.data[RESULT]}" } } true } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) requestBtn = findViewById(R.id.trBtn) inputText = findViewById(R.id.trText) outputText = findViewById(R.id.trResult) requestBtn?.setOnClickListener { outputText?.text = "" val translationThread = TranslationThread() translationThread.start() } } fun request(url: String, callback: Callback) { val request: Request = Request.Builder() .url(url) .header("User-Agent", "My-translator") .build() client.newCall(request).enqueue(callback) } fun click(text: String) { val url = "https://dict.youdao.com/jsonapi?q=$text" request(url, object : Callback { override fun onFailure(call: Call, e: IOException) { outputText?.text = e.message } override fun onResponse(call: Call, response: Response) { val bodyString = response.body?.string() val youdaoBean = gson.fromJson(bodyString, YoudaoBean::class.java) val tranList = youdaoBean.web_trans.web_translation[0].trans println(tranList) var output: String? = "" for (trans in tranList) { output += (trans.value + ";") } output = output?.substring(0, output?.length - 1) val msg = Message.obtain() msg.what = STATUS_FINISH_TRANSLATION msg.data = Bundle().apply { putString(RESULT, output) } handler.sendMessage(msg) } }) } inner class TranslationThread : Thread() { override fun run() { super.run() transition() } private fun transition() { click(inputText?.text.toString()) } } }
1
null
1
4
96bbb24da5146157e3550deaf08f87c5b4084327
3,615
android-develop-bytedance
MIT License
extensions/intellij/intellij_generator_plugin/src/main/java/com/bloc/intellij_generator_plugin/generator/Generator.kt
noahmateen
183,264,134
false
{"Markdown": 59, "Text": 5, "Ignore List": 19, "YAML": 26, "CODEOWNERS": 1, "Dart": 199, "Gradle": 35, "XML": 114, "INI": 22, "Java Properties": 12, "Java": 12, "OpenStep Property List": 23, "Objective-C": 33, "JSON": 25, "JSON with Comments": 2, "Shell": 3, "Batchfile": 2, "Kotlin": 7, "Ruby": 3, "HTML": 10, "CSS": 4, "JavaScript": 1}
package com.bloc.intellij_generator_plugin.generator import com.google.common.base.CaseFormat import com.google.common.io.CharStreams import org.apache.commons.lang.text.StrSubstitutor import java.io.InputStreamReader import java.lang.RuntimeException abstract class Generator(private val blocName: String, blocShouldUseEquatable: Boolean, templateName: String) { private val TEMPLATE_BLOC_CAMEL_CASE = "bloc_camel_case" private val TEMPLATE_BLOC_SNAKE_CASE = "bloc_snake_case" private val templateString: String private val templateValues: MutableMap<String, String> init { templateValues = mutableMapOf( TEMPLATE_BLOC_CAMEL_CASE to camelCase(), TEMPLATE_BLOC_SNAKE_CASE to snakeCase() ) try { val templateFolder = if (blocShouldUseEquatable) "with_equatable" else "without_equatable" val resource = "/templates/$templateFolder/$templateName.dart.template" val resourceAsStream = Generator::class.java.getResourceAsStream(resource) templateString = CharStreams.toString(InputStreamReader(resourceAsStream, Charsets.UTF_8)) } catch (e: Exception) { throw RuntimeException(e) } } abstract fun fileName(): String fun generate(): String { val substitutor = StrSubstitutor(templateValues) return substitutor.replace(templateString) } fun camelCase(): String = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, blocName) fun snakeCase() = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE, blocName) fun fileExtension() = "dart" }
1
null
1
1
300f6b6d28b9427a15ea336b78ae9799c73b087e
1,687
bloc
MIT License
gradle-plugin/src/main/kotlin/com/alecstrong/cocoapods/gradle/plugin/CocoapodsCompileTask.kt
jrocharodrigues
167,940,603
true
{"Kotlin": 19221, "Shell": 937, "Objective-C": 464}
package com.alecstrong.cocoapods.gradle.plugin import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType import org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink import org.jetbrains.kotlin.konan.target.Architecture import java.io.File open class CocoapodsCompileTask : DefaultTask() { internal lateinit var buildType: NativeBuildType internal lateinit var compilations: Collection<KotlinNativeLink> @TaskAction fun compileFatFramework() { compileFatBinary( binaryPath = project.name, bundleName = "${project.name}.framework" ) } @TaskAction fun compileFatDsym() { compileFatBinary( binaryPath = "Contents/Resources/DWARF/${project.name}", bundleName = "${project.name}.framework.dSYM" ) } private fun compileFatBinary( binaryPath: String, bundleName: String ) { val finalContainerPath = "${project.buildDir.path}/$bundleName" val finalOutputPath = "$finalContainerPath/$binaryPath" var deviceParentDir: String? = null project.exec { exec -> File(finalOutputPath).parentFile.mkdirs() val args = mutableListOf("-create") compilations.forEach { compilation -> val output = compilation.outputFile.get().parentFile.absolutePath val target = compilation.binary.target.konanTarget if (target.architecture == Architecture.ARM64) { deviceParentDir = output } args.addAll(listOf( "-arch", target.architecture(), "$output/$bundleName/$binaryPath" )) } args.addAll(listOf( "-output", finalOutputPath )) exec.executable = "lipo" exec.args = args exec.isIgnoreExitValue = true } if (deviceParentDir == null) { throw IllegalStateException("You need to have a compilation target for X64") } val initialContainer = "$deviceParentDir/$bundleName" project.copy { copy -> copy.from(initialContainer) { from -> from.exclude(binaryPath) } copy.into(finalContainerPath) } // clean plist (only works for frameworks) val plistPath = "$finalContainerPath/Info.plist" if (File(plistPath).exists()) { project.exec { exec -> exec.executable = "/usr/libexec/PlistBuddy" exec.args = listOf("-c", "Delete :UIRequiredDeviceCapabilities", plistPath) exec.isIgnoreExitValue = true } project.exec { exec -> exec.executable = "/usr/libexec/PlistBuddy" exec.args = listOf("-c", "Add :CFBundleSupportedPlatforms:1 string iPhoneSimulator", plistPath) exec.isIgnoreExitValue = true } } } }
0
Kotlin
0
0
4c6dda39341d10e0c586d432405f6c8682305c02
2,716
kotlin-native-cocoapods
Apache License 2.0
src/main/kotlin/com/clprunner/runnertalkchat/domain/chatroom/ChatRoom.kt
clp-runner
740,936,919
false
{"Kotlin": 5897}
package com.clprunner.runnertalkchat.chatroom import com.clprunner.runnertalkchat.global.document.MongoBaseDocument import lombok.AccessLevel import lombok.AllArgsConstructor import lombok.Builder import lombok.NoArgsConstructor import org.springframework.data.mongodb.core.mapping.Document import java.time.ZonedDateTime @Document(collection = "ChatRooms") @AllArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor @Builder class ChatRoom( private var name: String, private var description: String?, private var creatorId: String, private var participants: Array<String>, private var lastMessage: LastMessage? = null ) : MongoBaseDocument() { fun updateLastMessage(content: String, timestamp: ZonedDateTime) { this.lastMessage = LastMessage(content, timestamp) this.updatedAt = ZonedDateTime.now() } data class LastMessage( val content: String, val timestamp: ZonedDateTime ) }
2
Kotlin
0
0
53421b9d5adf2834c2959e98e43ce346cb0d9351
961
runner-talk-chat
Apache License 2.0
core/src/test/kotlin/no/ntnu/ihb/vico/util/ExtensionsKtTest.kt
NTNU-IHB
284,521,287
false
null
package no.ntnu.ihb.vico.util import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class ExtensionsKtTest { @Test fun insert() { val original = "Hello, pants!" val insert = "smarty" val modified = original.insert(original.indexOf(' '), insert) assertEquals("Hello, smartypants!", modified) } }
4
Kotlin
1
8
997c708656c274cbcab94cb4375ebfdf46d5e1ad
389
Vico
MIT License
sdk-scrapper/src/main/kotlin/io/github/wulkanowy/sdk/scrapper/register/Permission.kt
wulkanowy
138,756,468
false
null
package io.github.wulkanowy.sdk.scrapper.register import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Permission( @Json(name = "AuthInfos") val authInfos: List<AuthInfo>, @Json(name = "Units") val units: List<Unit> ) @JsonClass(generateAdapter = true) data class AuthInfo( @Json(name = "JednostkaSprawozdawczaId") val unitId: Int, @Json(name = "LinkedAccountUids") val linkedAccountUids: List<Int>, @Json(name = "LoginId") val loginId: Int, @Json(name = "LoginValue") val loginValue: String, @Json(name = "OpiekunIds") val parentIds: List<Int>, @Json(name = "PracownikIds") val employeeIds: List<Int>, @Json(name = "Roles") val roles: List<Int>, @Json(name = "UczenIds") val studentIds: List<Int> ) @JsonClass(generateAdapter = true) data class Unit( @Json(name = "Id") val id: Int, @Json(name = "Nazwa") val name: String, @Json(name = "Skrot") val short: String, @Json(name = "Symbol") val symbol: String )
9
Kotlin
4
18
57680ecb3fa0ddf352ab1c5c53a00f260e5d6c9c
1,097
sdk
Apache License 2.0
app/src/main/java/com/example/dapurmamatur/di/NetworkModule.kt
MFaisal00359
792,108,953
false
{"Kotlin": 59155}
package com.example.dapurmamatur.di import android.content.Context import android.net.ConnectivityManager object NetworkModule { fun provideConnectivityManager(context: Context): ConnectivityManager { return context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager } }
3
Kotlin
0
2
333c3cecb0e11e182b70fc8f925d23774103fa1f
308
Recipe-Meals-Dapur-Mama-Tur
MIT License
src/main/kotlin/com/intellij/ml/llm/template/utils/EFCandidateFactory.kt
JetBrains-Research
616,565,282
false
null
package com.intellij.ml.llm.template.utils import com.intellij.ml.llm.template.extractfunction.EFCandidate import com.intellij.ml.llm.template.extractfunction.EFSuggestion import com.intellij.ml.llm.template.extractfunction.EfCandidateType import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import org.jetbrains.kotlin.idea.base.psi.getLineNumber class EFCandidateFactory { fun buildCandidates(efSuggestion: EFSuggestion, editor: Editor, file: PsiFile): HashSet<EFCandidate> { val candidates = HashSet<EFCandidate>() if (!isValid(efSuggestion)) { buildInvalidCandidate(efSuggestion).let { candidates.add(it) } return candidates } buildCandidateAsIs(efSuggestion, editor, file)?.let { candidates.add(it) } buildCandidateWithAdjustment(efSuggestion, editor, file)?.let { candidates.add(it) } return candidates } private fun buildCandidateAsIs(efSuggestion: EFSuggestion, editor: Editor, file: PsiFile): EFCandidate? { val psiElementStart = getLeftmostPsiElement(efSuggestion.lineStart, editor, file) val psiElementEnd = getLeftmostPsiElement(efSuggestion.lineEnd, editor, file) if (psiElementStart == null || psiElementEnd == null) { return null } return EFCandidate( functionName = efSuggestion.functionName, offsetStart = psiElementStart.startOffset, offsetEnd = psiElementEnd.endOffset, lineStart = editor.document.getLineNumber(psiElementStart.startOffset) + 1, lineEnd = editor.document.getLineNumber(psiElementEnd.endOffset) + 1, ).also { it.efSuggestion = efSuggestion it.type = EfCandidateType.AS_IS } } private fun buildCandidateWithAdjustment(efSuggestion: EFSuggestion, editor: Editor, file: PsiFile): EFCandidate? { val psiElementStart = getLeftmostPsiElement(efSuggestion.lineStart, editor, file) val psiElementEnd = getLeftmostPsiElement(efSuggestion.lineEnd, editor, file) if (psiElementStart == null || psiElementEnd == null) { return null } val adjustedRegion = adjustRegion(psiElementStart, psiElementEnd) ?: return null return EFCandidate( functionName = efSuggestion.functionName, offsetStart = adjustedRegion.first.startOffset, offsetEnd = adjustedRegion.second.endOffset, lineStart = editor.document.getLineNumber(adjustedRegion.first.startOffset) + 1, lineEnd = editor.document.getLineNumber(adjustedRegion.second.endOffset) + 1, ).also { it.efSuggestion = efSuggestion it.type = EfCandidateType.ADJUSTED } } /** * Selected region is adjusted by enlarging it to the top-most PsiElement, either start or end */ private fun adjustRegion(psiElementStart: PsiElement, psiElementEnd: PsiElement): Pair<PsiElement, PsiElement>? { var commonParent = PsiTreeUtil.findCommonParent(psiElementStart, psiElementEnd) var start = psiElementStart var end = psiElementEnd if (commonParent == start || commonParent == end) { start = commonParent end = commonParent } if (start == end) { commonParent = start.parent } if (commonParent == null) { return null } start = bubbleUp(start, commonParent) end = bubbleUp(end, commonParent) return start to end } private fun bubbleUp(element: PsiElement, stopElement: PsiElement): PsiElement { var result = element while (result.parent != stopElement && result.parent != null) { result = result.parent } return result } private fun getLeftmostPsiElement(lineNumber: Int, editor: Editor, file: PsiFile): PsiElement? { // get the PsiElement on the given lineNumber var psiElement = file.findElementAt(editor.document.getLineStartOffset(lineNumber)) ?: return null // if there are multiple sibling PsiElements on the same line, look for the first one while (psiElement.getLineNumber(true) == psiElement.prevSibling?.getLineNumber(true)) { psiElement = psiElement.prevSibling } // if there are multiple parent PsiElements on the same line, look for the top one while (psiElement.getLineNumber(true) == psiElement.parent?.getLineNumber(true)) { psiElement = psiElement.parent } if (psiElement is PsiWhiteSpace) { psiElement = psiElement.prevSibling } return psiElement } private fun isValid(efSuggestion: EFSuggestion): Boolean { return efSuggestion.lineStart > 0 && efSuggestion.lineEnd > 0 } private fun buildInvalidCandidate(efSuggestion: EFSuggestion): EFCandidate { return EFCandidate( functionName = efSuggestion.functionName, lineStart = 0, lineEnd = 0, offsetStart = -1, offsetEnd = -1, ).also { it.efSuggestion = efSuggestion it.type = EfCandidateType.INVALID } } }
1
Kotlin
0
0
e07bad76788d74e67a7b599c5db2ff01bafad7bd
5,473
llm-guide-refactorings
MIT License
2021/src/main/kotlin/aoc/day2.kt
daf276
433,385,608
false
null
package aoc.day2 sealed class Instruction { data class FORWARD(val value: Int) : Instruction() data class DOWN(val value: Int) : Instruction() data class UP(val value: Int) : Instruction() } fun parseInstructions(input: List<String>): List<Instruction> = input.map { it.split(" ") }.map { (instruction, value) -> when (instruction) { "forward" -> Instruction.FORWARD(value.toInt()) "down" -> Instruction.DOWN(value.toInt()) "up" -> Instruction.UP(value.toInt()) else -> throw Exception("This when is exhaustive") } } fun part1(input: List<Instruction>): Int { val (pos, depth) = input.fold(Pair(0, 0)) { sum, add -> when (add) { is Instruction.FORWARD -> sum.copy(first = sum.first + add.value) is Instruction.DOWN -> sum.copy(second = sum.second + add.value) is Instruction.UP -> sum.copy(second = sum.second - add.value) } } return pos * depth } fun part2(input: List<Instruction>): Int { val (pos, depth, aim) = input.fold(Triple(0, 0, 0)) { sum, add -> when (add) { is Instruction.FORWARD -> sum.copy( first = sum.first + add.value, second = sum.second + sum.third * add.value ) is Instruction.DOWN -> sum.copy(third = sum.third + add.value) is Instruction.UP -> sum.copy(third = sum.third - add.value) } } return pos * depth }
0
Rust
0
0
d397cfe0daab24604615d551cbdb7c6ae145ae74
1,495
AdventOfCode
MIT License
src/main/kotlin/io/zerobase/smarttracing/Router.kt
knorrium
253,064,461
true
{"Kotlin": 47971, "Python": 2823, "CSS": 2778, "HTML": 2333, "Dockerfile": 218, "Shell": 158}
package io.zerobase.smarttracing import com.fasterxml.jackson.annotation.JsonProperty import io.zerobase.smarttracing.models.DeviceId import io.zerobase.smarttracing.models.Fingerprint import javax.ws.rs.Consumes import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.MediaType open class ApiResponse(val success: Boolean, val session: Boolean = false, val message: String? = null ) data class DeviceCreatedResponse(@JsonProperty("dvid") val id: String): ApiResponse(success = true) data class ScanRecordedResponse(@JsonProperty("scan") val id: String): ApiResponse(success = true) data class LegacyCreateDeviceRequest(val fingerprint: String?, val ip: String?) data class PeerToPeerCheckIn(@JsonProperty("dvid") val scanningDevice: String, @JsonProperty("sdvid") val scannedDevice: String) @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) class Router(val dao: GraphDao) { @Path("/c/{unused: .+?}") @POST fun createDevice(req: LegacyCreateDeviceRequest): ApiResponse { try { return dao.createDevice(req.fingerprint?.let(::Fingerprint)).let { DeviceCreatedResponse(it.value) } } catch (_: Exception) { return ApiResponse(success = false, message = "Sorry, there was an error processing your account, please try again.") } } @Path("/s-id/{deviceId}") @POST fun recordCheckIn(req: PeerToPeerCheckIn): ApiResponse { val id = dao.recordPeerToPeerScan(DeviceId(req.scanningDevice), DeviceId(req.scannedDevice), null) return when (id) { null -> ApiResponse(success = false, message = "At least one provided ID is not valid.") else -> ScanRecordedResponse(id.value) } } }
0
null
0
0
4fa295b3eed6a06c31605e705aa026734e473a6c
1,828
smart-tracing-api
Apache License 2.0
cbor-processor/src/main/kotlin/com/android/identity/cbor/annotation/CborSerializable.kt
openwallet-foundation-labs
248,844,077
false
{"Kotlin": 2822892, "Java": 682870, "Python": 85755, "JavaScript": 28064, "HTML": 841, "CSS": 286, "Dockerfile": 267}
package com.android.identity.cbor.annotation @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.SOURCE) annotation class CborSerializable( /** * Optional parameter for sealed class hierarchies to define the key that carries type id. * * This parameter should be used on the root (sealed) class. */ val typeKey: String = "", /** * Optional parameter for sealed class hierarchies to define the type id for this class. * * This parameter should be used on the leaf (data) class. */ val typeId: String = "" )
97
Kotlin
69
135
a39789f8d2b2c35a2eaa032f7827a3aa3ecda758
574
identity-credential
Apache License 2.0
src/main/kotlin/com/ferum_bot/quotesapi/models/create_entities/CreateTagModel.kt
Ferum-bot
378,502,194
false
null
package com.ferum_bot.quotesapi.models.create_entities data class CreateTagModel( val text: String )
0
Kotlin
0
0
ad69f72ca5d87f819085ef396eabae35ebbd3a0e
108
QuotesAPI
Apache License 2.0
src/ext/kotlin/slatekit-providers-kafka/src/main/kotlin/slatekit/providers/kafka/KafkaConfig.kt
slatekit
55,942,000
false
null
package slatekit.providers.kafka import slatekit.common.conf.Conf import org.apache.kafka.clients.CommonClientConfigs import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.common.config.SaslConfigs import org.apache.kafka.common.security.auth.SecurityProtocol import org.apache.kafka.common.serialization.StringSerializer import java.util.* data class KafkaConfig(val host:String, val user:String, val pswd:String, val saslEnabled:Boolean, val isProducer:Boolean) { private val jass:String = """org.apache.kafka.common.security.plain.PlainLoginModule required username="$user" password="$pswd";""" fun props(): Properties { val props = Properties() props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host) if (saslEnabled) { props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_SSL) props.put(SaslConfigs.SASL_MECHANISM, "PLAIN") props.put(SaslConfigs.SASL_JAAS_CONFIG, jass) } if(isProducer){ props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer::class.qualifiedName) props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer::class.qualifiedName) } return props } companion object { fun load(conf: Conf, isProducer: Boolean): KafkaConfig { return KafkaConfig( host = conf.getString(KafkaConstants.KAFKA_HOST), user = conf.getString(KafkaConstants.KAFKA_USERNAME), pswd = conf.getString(KafkaConstants.KAFKA_PASSWORD), saslEnabled = conf.getBool(KafkaConstants.SASL_ENABLED), isProducer = isProducer ) } } }
6
Kotlin
12
107
f8ae048bc7d19704a2558e1d02374e98782e7b47
1,800
slatekit
Apache License 2.0
src/test/kotlin/me/stockingd/current/operators/FlatMapConcatKtTest.kt
dmstocking
375,025,377
false
null
package me.stockingd.current.operators import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe import kotlinx.coroutines.delay import me.stockingd.current.current import me.stockingd.current.currentOf internal class FlatMapConcatKtTest : DescribeSpec({ describe("map") { it("should collect each flow in order") { currentOf(1, 2, 3) .flatMapConcat { value -> current { repeat(value) { emit(value) } } } .toList() .shouldBe(listOf(1, 2, 2, 3, 3, 3)) } it("should not collect in parallel") { currentOf(1, 2, 3) .flatMapConcat { value -> current { delay(3L - value) emit(value) } } .toList() .shouldBe(listOf(1, 2, 3)) } } })
0
Kotlin
0
0
6e4b04e47038b0a402a5732adfbc70c52347243d
1,047
current
MIT License
chatlibrary/src/main/java/com/zaeem/myapplication/adapters/ConversationListAdapter.kt
ZaeemSattar
432,133,401
false
null
package com.zaeem.myapplication.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.zaeem.myapplication.data.models.ConversationListViewItem import com.zaeem.myapplication.databinding.RowConversationItemBinding import kotlin.properties.Delegates class ConversationListAdapter(private val callback: OnConversationEvent) : RecyclerView.Adapter<ConversationListAdapter.ViewHolder>() { var conversations: List<ConversationListViewItem> by Delegates.observable(emptyList()) { _, old, new -> DiffUtil.calculateDiff(ConversationDiff(old, new)).dispatchUpdatesTo(this) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = RowConversationItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun getItemCount(): Int = conversations.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.binding.conversation = conversations[position] holder.binding.conversationItem.setOnClickListener { holder.binding.conversation?.sid?.let { callback.onConversationClicked(it) } } } fun isMuted(position: Int) = conversations[position].isMuted class ViewHolder(val binding: RowConversationItemBinding) : RecyclerView.ViewHolder(binding.root) class ConversationDiff(private val oldItems: List<ConversationListViewItem>, private val newItems: List<ConversationListViewItem> ) : DiffUtil.Callback() { override fun getOldListSize() = oldItems.size override fun getNewListSize() = newItems.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItems[oldItemPosition].sid == newItems[newItemPosition].sid } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItems[oldItemPosition] == newItems[newItemPosition] } } } interface OnConversationEvent { fun onConversationClicked(conversationSid: String) }
0
Kotlin
0
0
546b9e73e8c1f7843cc98ce9a9767d41cac52f00
2,239
TwilioChat
MIT License
script/src/main/java/ru/flowernetes/script/domain/usecase/ValidateSourceScriptUseCaseImpl.kt
b1nd
252,335,785
false
null
package ru.flowernetes.script.domain.usecase import org.apache.commons.io.FilenameUtils import org.springframework.stereotype.Component import ru.flowernetes.script.api.domain.dto.SourceScriptDto import ru.flowernetes.script.api.domain.entity.SourceScriptValidationException import ru.flowernetes.script.api.domain.usecase.GetSourceScriptTypeByPathUseCase import ru.flowernetes.script.api.domain.usecase.ValidateSourceScriptUseCase import java.nio.file.Paths @Component class ValidateSourceScriptUseCaseImpl( private val getSourceScriptTypeByPathUseCase: GetSourceScriptTypeByPathUseCase ) : ValidateSourceScriptUseCase { override fun exec(sourceScript: SourceScriptDto) { checkSourceScriptExtension(sourceScript) checkRunFilePath(sourceScript) } private fun checkSourceScriptExtension(sourceScript: SourceScriptDto) { val extension = FilenameUtils.getExtension(sourceScript.filename) if (!extension.equals("zip", true)) { throw SourceScriptValidationException("Source script should be a zip archive!") } } private fun checkRunFilePath(sourceScript: SourceScriptDto) { Paths.get(sourceScript.runFilePath) getSourceScriptTypeByPathUseCase.exec(sourceScript.runFilePath) } }
0
Kotlin
1
2
8eef7e3324642fa4b26a69be69525d79a4873ea4
1,271
flowernetes
MIT License
src/main/kotlin/fr/ziedelth/jais/countries/FranceCountry.kt
Ziedelth
371,147,884
false
null
/* * Copyright (c) 2021. Ziedelth */ package fr.ziedelth.jais.countries import fr.ziedelth.jais.platforms.AnimeDigitalNetworkPlatform import fr.ziedelth.jais.platforms.CrunchyrollPlatform import fr.ziedelth.jais.platforms.NetflixPlatform import fr.ziedelth.jais.platforms.WakanimPlatform import fr.ziedelth.jais.utils.animes.countries.Country import fr.ziedelth.jais.utils.animes.countries.CountryHandler import fr.ziedelth.jais.utils.animes.platforms.Platform @CountryHandler( tag = "fr", name = "France", flag = "\uD83C\uDDEB\uD83C\uDDF7", season = "Saison" ) class FranceCountry : Country { /** * When the platform is AnimeDigitalNetworkPlatform, return "frFR". Otherwise, return null * * @param platform Platform? -> The platform that the URL is being checked on. * @return The language code for the platform. */ override fun checkOnNewsURL(platform: Platform?): String? { return when (platform?.javaClass) { AnimeDigitalNetworkPlatform::class.java -> "frFR" else -> null } } /** * When the platform is either Anime Digital Network, Netflix, or Wakanim, return "fr" * * @param platform Platform? -> The platform that the URL is being checked for. * @return The language code for the platform. */ override fun checkOnEpisodesURL(platform: Platform?): String? { return when (platform?.javaClass) { AnimeDigitalNetworkPlatform::class.java, NetflixPlatform::class.java, WakanimPlatform::class.java -> "fr" CrunchyrollPlatform::class.java -> "frFR" else -> null } } /** * "When the platform is Crunchyroll, return the French language." * * The `when` statement is a replacement for the `if` statement. It's a little more readable than the `if` statement, * and it's also more powerful * * @param platform The platform to check. * @return The string "fr" */ override fun restrictionEpisodes(platform: Platform?): String? { return when (platform?.javaClass) { CrunchyrollPlatform::class.java -> "fr" else -> null } } /** * "When the platform is AnimeDigitalNetworkPlatform, return vostf. When the platform is CrunchyrollPlatform, return fr * - fr." * * The function above is a good example of a function that returns a value based on the value of a variable * * @param platform Platform? * @return The value of the `subtitlesEpisodes` method is being returned. */ override fun subtitlesEpisodes(platform: Platform?): String? { return when (platform?.javaClass) { AnimeDigitalNetworkPlatform::class.java -> "vostf" CrunchyrollPlatform::class.java -> "fr - fr" else -> null } } /** * When the platform is AnimeDigitalNetworkPlatform, return "vf". Otherwise, return null * * @param platform Platform? * @return The dubbed episodes for the given platform. */ override fun dubbedEpisodes(platform: Platform?): String? { return when (platform?.javaClass) { AnimeDigitalNetworkPlatform::class.java -> "vf" else -> null } } }
0
Kotlin
0
1
08e122a2858d73f6afe5e8bf0433101b65313202
3,278
Jais
MIT License
src/main/kotlin/Visibilidade_Heranca/Cliente.kt
original-carreira
391,493,690
false
null
package Visibilidade_Heranca open class Cliente (var numeroCodigo:Long,var nome:String,var sobreNome:String)
0
Kotlin
0
0
a0c21bd46cdcdc9535f85e66b98dbbc1401850e9
109
Digita_House
MIT License
src/main/java/com/nextdevv/kgui/utils/Alignment.kt
NextDevv
684,177,399
false
{"Kotlin": 58170}
package com.nextdevv.kgui.utils enum class Alignment { TOP_LEFT, TOP_CENTER, TOP_RIGHT, CENTER_LEFT, CENTER, CENTER_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT; companion object { fun getIndex(alignment: Alignment, rows: Int): Int { when(alignment) { TOP_LEFT -> return 0 TOP_CENTER -> return 4 TOP_RIGHT -> return 8 CENTER_LEFT -> { val size = rows * 9 val centerIndex = (size / 2) - 5 return centerIndex - 4 } CENTER -> { val size = rows * 9 return (size / 2) - 5 } CENTER_RIGHT -> { val size = rows * 9 val centerIndex = (size / 2) - 5 return centerIndex + 4 } BOTTOM_LEFT -> { val size = rows * 9 return size - 9 } BOTTOM_CENTER -> { val size = rows * 9 return (size - 9) + 4 } BOTTOM_RIGHT -> { val size = rows * 9 return (size - 9) + 8 } } } } }
0
Kotlin
0
2
985c776175291262f91c8ba988a7767bac6a5a43
1,361
KGui
MIT License
tests/src/main/kotlin/se/ansman/dagger/auto/ktorfit/KtorfitModule.kt
ansman
565,464,998
false
{"Kotlin": 269874, "Java": 4602, "Shell": 503}
package se.ansman.dagger.auto.ktorfit import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import de.jensklingenberg.ktorfit.Ktorfit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object KtorfitModule { @Provides @Singleton fun provideKtorfit(): Ktorfit = Ktorfit.Builder() .baseUrl("https://jsonplaceholder.typicode.com") .build() }
6
Kotlin
3
69
10c439594cea772cdc90e5e89c0847061d7a26e9
477
auto-dagger
Apache License 2.0
source-code/starter-project/app/src/main/java/com/droidcon/easyinvoice/ui/home/nav/InvoiceNav.kt
droidcon-academy
731,477,787
false
{"Kotlin": 1511048}
/* * Copyright (c) 2022. Droidcon * * 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.droidcon.easyinvoice.ui.home.nav import android.app.Activity import androidx.compose.runtime.collectAsState import androidx.compose.ui.platform.LocalContext import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import androidx.navigation.navigation import com.droidcon.easyinvoice.ui.AppScreen import com.droidcon.easyinvoice.ui.home.HomeActivity import com.droidcon.easyinvoice.ui.home.invoices.InvoiceItemViewModel import com.droidcon.easyinvoice.ui.home.invoices.InvoicesScreen import com.droidcon.easyinvoice.ui.home.invoices.InvoicesViewModel import com.droidcon.easyinvoice.ui.home.invoices.detail.InvoiceDetail import com.droidcon.easyinvoice.ui.home.invoices.manage.AddInvoiceItem import com.droidcon.easyinvoice.ui.home.invoices.manage.PickBusinessScreen import com.droidcon.easyinvoice.ui.home.invoices.manage.PickCustomerScreen import com.droidcon.easyinvoice.ui.home.invoices.manage.PickTaxScreen import com.droidcon.easyinvoice.ui.utils.getViewModelInstance import dagger.hilt.android.EntryPointAccessors fun NavGraphBuilder.invoiceNav(navController: NavController) { navigation( startDestination = AppScreen.Invoices.Home.route, route = AppScreen.Invoices.route ) { composable(AppScreen.Invoices.Home.route) { val vm = navController.getViewModelInstance<InvoicesViewModel>(it, AppScreen.Invoices.route) InvoicesScreen(vm, navController) } composable(AppScreen.Invoices.InvoiceDetail.route) { val vm = navController.getViewModelInstance<InvoicesViewModel>(it, AppScreen.Invoices.route) InvoiceDetail(vm, navController) } navigation( startDestination = AppScreen.Invoices.ManageInvoice.PickBusiness.route, route = AppScreen.Invoices.ManageInvoice.route ) { composable(AppScreen.Invoices.ManageInvoice.PickBusiness.route) { val vm = navController.getViewModelInstance<InvoicesViewModel>(it, AppScreen.Invoices.route) PickBusinessScreen(vm, navController) } composable(AppScreen.Invoices.ManageInvoice.PickCustomer.route) { val vm = navController.getViewModelInstance<InvoicesViewModel>(it, AppScreen.Invoices.route) PickCustomerScreen(vm, navController) } composable(AppScreen.Invoices.ManageInvoice.PickTax.route) { val vm = navController.getViewModelInstance<InvoicesViewModel>(it, AppScreen.Invoices.route) PickTaxScreen(vm, navController) } composable(AppScreen.Invoices.ManageInvoice.AddItems.route) { val invoiceViewModel = navController.getViewModelInstance<InvoicesViewModel>(it, AppScreen.Invoices.route) val invoiceId = invoiceViewModel.invoiceId.collectAsState() val factory = EntryPointAccessors.fromActivity( LocalContext.current as Activity, HomeActivity.ViewModelFactoryProvider::class.java ).invoiceItemViewModelFactory() invoiceId.value?.let { id -> val invoiceItemViewModel: InvoiceItemViewModel = viewModel(factory = InvoiceItemViewModel.provideInvoiceItemViewModelFactory(factory, id.toInt())) AddInvoiceItem(invoiceItemViewModel, navController) } } } } }
0
Kotlin
1
0
ce943998fb00f7df6e83465c75abde4e6c7e542f
4,213
android-room-database-course-materials
Apache License 2.0
app/src/main/java/com/example/skycast/data/model/dailyforcast/Sun.kt
pavannamepalli
683,812,643
false
{"Kotlin": 46045}
package com.example.skycast.data.model.dailyforcast data class Sun( val EpochRise: Int, val EpochSet: Int, val Rise: String, val Set: String )
0
Kotlin
0
0
e0fc2c35610b961948281f29756b714a2c24c0ee
159
SkyCast
MIT License
konsist/src/test/kotlin/com/timplifier/boilerplate/konsist/data/assertions/architecture/DataLayerArchitectureTest.kt
timplifier
699,749,494
false
{"Kotlin": 41055}
package com.timplifier.rickandmortyremastered.konsist.data.assertions.architecture import com.lemonappdev.konsist.api.Konsist import com.lemonappdev.konsist.api.architecture.KoArchitectureCreator.assertArchitecture import com.lemonappdev.konsist.api.architecture.Layer import org.junit.Test internal class DataLayerArchitectureTest { @Test internal fun `ensure that data layer depends only on core and domain`() { val coreData = Layer("Core Data", "com.timplifier.rickandmortyremastered.core.data..") Konsist.scopeFromProject() .assertArchitecture { listOf( "com.timplifier.rickandmortyremastered.authentication.data..", "com.timplifier.rickandmortyremastered.main.data.." ).forEach { definedBy -> val data = Layer(definedBy, definedBy) val domain = Layer( definedBy.replace("data", "domain"), definedBy.replace("data", "domain") ) data.dependsOn(coreData) data.dependsOn(domain) } } } }
0
Kotlin
0
0
e3b78301d47e39a4d897aa533f21d178adaa6149
1,214
RickAndMortyRemastered
Apache License 2.0
src/main/kotlin/androidstudio/tools/missed/missedtoolwindow/model/MissedToolsWindowStateUi.kt
rasoulmiri
668,869,188
false
{"Kotlin": 440329}
package androidstudio.tools.missed.missedtoolwindow.model sealed class MissedToolsWindowStateUi { object Loading : MissedToolsWindowStateUi() object Success : MissedToolsWindowStateUi() object NeedToConnectDevice : MissedToolsWindowStateUi() object Error : MissedToolsWindowStateUi() }
0
Kotlin
0
2
fb33080fef3289880a4efdaf92bb9826c322cfc4
303
AndroidStudioToolsMissed
Apache License 2.0
src/main/java/com/denis/morozov/retrobot/core/database/condition/ConditionDescriptor.kt
dmoroz0v
151,746,932
false
null
package com.denis.morozov.retrobot.core.database.condition sealed class ConditionDescriptor class Equal(val field: String, val value: Any): ConditionDescriptor() class Relationship(val field1: String, val field2: String): ConditionDescriptor() class And(vararg val elements: ConditionDescriptor): ConditionDescriptor() class Or(vararg val elements: ConditionDescriptor): ConditionDescriptor() class Not(val element: ConditionDescriptor): ConditionDescriptor()
0
Kotlin
0
0
e22c3587034d4147d5dd4a32e252863cce942b0b
461
retrobot
MIT License
bilimiao-compose/src/main/java/cn/a10miaomiao/bilimiao/compose/pages/BlankPage.kt
10miaomiao
142,169,120
false
{"Kotlin": 1671460, "Java": 664642, "HTML": 601}
package cn.a10miaomiao.bilimiao.compose.pages import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import cn.a10miaomiao.bilimiao.compose.comm.diViewModel import cn.a10miaomiao.bilimiao.compose.comm.localContainerView import cn.a10miaomiao.bilimiao.compose.comm.mypage.PageConfig import com.a10miaomiao.bilimiao.store.WindowStore import org.kodein.di.DI import org.kodein.di.DIAware import org.kodein.di.compose.rememberInstance import org.kodein.di.instance class BlankPageViewModel( override val di: DI, ) : ViewModel(), DIAware { private val fragment by instance<Fragment>() } @Composable fun BlankPage() { PageConfig( title = "空白页" ) val viewModel: BlankPageViewModel = diViewModel() val windowStore: WindowStore by rememberInstance() val windowState = windowStore.stateFlow.collectAsState().value val windowInsets = windowState.getContentInsets(localContainerView()) }
44
Kotlin
38
977
1d59b82ba30b4c2e83c781479d09c48c3a82cd47
1,030
bilimiao2
Apache License 2.0