path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/np/retrofit/MainActivity.kt
|
nirajphutane
| 795,627,485 | false |
{"Kotlin": 72999}
|
package com.np.retrofit
import android.os.Bundle
import androidx.activity.viewModels
import com.np.retrofit.utils.base_pkgs.MainActivityViewModel
import com.np.retrofit.utils.base_pkgs.WrapperActivity
import com.np.retrofit.utils.base_pkgs.viewBinding
import com.np.retrofit.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : WrapperActivity() {
private val viewModel: MainActivityViewModel by viewModels()
private val binding by viewBinding(ActivityMainBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
}
}
| 0 |
Kotlin
|
0
| 0 |
691b996a47b539398ec6909fbc9c7136d477dd0d
| 694 |
Android-Retrofit
|
MIT License
|
mobile-development/NerdLauncher/app/src/main/java/com/gebeto/nerdlauncher/NerdLauncherActivity.kt
|
gebeto
| 152,408,643 | false |
{"C": 7905992, "Assembly": 1950118, "HTML": 943877, "C++": 108425, "Makefile": 102933, "C#": 92763, "Kotlin": 46409, "TypeScript": 26461, "JavaScript": 23905, "Python": 10681, "CSS": 927, "PLpgSQL": 408, "Dockerfile": 363, "Shell": 324}
|
package com.gebeto.nerdlauncher
import android.support.v4.app.Fragment
class NerdLauncherActivity : SingleFragmentActivity() {
override fun createFragment(): Fragment {
return NerdLauncherFragment.newInstance()
}
}
| 35 |
C
|
0
| 0 |
ef42707ff96f582d5fedc2b8e466a812d1d4b53b
| 237 |
nulp
|
MIT License
|
app/src/main/java/com/boarderscore/boarderscore/fragments/ComputeFragment.kt
|
Z3nk
| 163,185,028 | false | null |
package com.boarderscore.boarderscore.fragments
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.boarderscore.boarderscore.R
import com.boarderscore.boarderscore.models.Players
import kotlinx.android.synthetic.main.fragment_compute.*
import java.io.Serializable
class ComputeFragment : Fragment() {
companion object {
const val TAG = "ComputeFragment"
const val RESULT_COMPUTE_ADD_POINTS = 1337
const val RESULT_COMPUTE_EDIT = 1338
const val RESULT_COMPUTE_KO = -1
const val BUNDLE_PLAYER = "BUNDLE_PLAYER"
const val BUNDLE_NEW_SCORE = "BUNDLE_NEW_SCORE"
const val BUNDLE_NEW_PSEUDO = "BUNDLE_NEW_PSEUDO"
fun newInstance(player: Serializable?): ComputeFragment {
return ComputeFragment().apply {
arguments = Bundle().apply {
putSerializable(BUNDLE_PLAYER, player)
}
}
}
}
private var player: Players? = null
private var finalScore = 0
private var currentScoreLD: MutableLiveData<Int> = MutableLiveData<Int>().apply {
postValue(0)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_compute, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Common tab
setTabLayoutListener()
setEditListener()
// Specific gaming tab
initPeanutClubCalculator()
}
private fun initPeanutClubCalculator() {
currentScoreLD.observe(viewLifecycleOwner, Observer {
var scoreCollector = et_collector.text.toString().toIntOrNull() ?: 0
var scoreLux = et_lux_or_antiq.text.toString().toIntOrNull() ?: 0
var scoreTrio = et_trio.text.toString().toIntOrNull() ?: 0
finalScore = scoreCollector * 2 + scoreLux * 2 + scoreTrio * 3
tv_actuel_score.text = getString(R.string.Xpoints, finalScore)
})
currentScoreLD.postValue(0)
et_collector.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
currentScoreLD.postValue(1)
}
})
et_lux_or_antiq.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
currentScoreLD.postValue(1)
}
})
et_trio.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
currentScoreLD.postValue(1)
}
})
btn_compute.setOnClickListener {
val bundle = Bundle()
bundle.putInt(BUNDLE_NEW_SCORE, player!!.score + finalScore)
activity?.setResult(RESULT_COMPUTE_ADD_POINTS, Intent().apply { putExtras(bundle) })
activity?.finish()
}
}
private fun setEditListener() {
player = arguments?.getSerializable(BUNDLE_PLAYER) as? Players
et_total_score.setText(player?.score.toString())
et_pseudo.setText(player?.pseudo.toString())
btn_finish_edit.setOnClickListener {
val bundle = Bundle()
bundle.putInt(BUNDLE_NEW_SCORE, et_total_score.text.toString().toInt())
bundle.putString(BUNDLE_NEW_PSEUDO, et_pseudo.text.toString())
activity?.setResult(RESULT_COMPUTE_EDIT, Intent().apply { putExtras(bundle) })
activity?.finish()
}
}
private fun setTabLayoutListener() {
tab_layout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
when (tab?.text) {
getString(R.string.add_points) -> {
layout_add_points.visibility = View.VISIBLE
layout_edit.visibility = View.GONE
}
getString(R.string.edit) -> {
layout_add_points.visibility = View.GONE
layout_edit.visibility = View.VISIBLE
}
}
val i = tab
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabReselected(tab: TabLayout.Tab?) {
}
})
}
}
| 0 |
Kotlin
|
0
| 0 |
16ffdf1df75faf21964a499aafe30644f9b361f9
| 5,512 |
BoarderScore
|
MIT License
|
core/src/main/kotlin/org/springframework/samples/petclinic/rest/coroutine/CoroutineOwnerController.kt
|
kotoant
| 612,221,740 | false |
{"Kotlin": 230920, "JavaScript": 102019, "Mustache": 10054, "PLpgSQL": 2929, "Shell": 1403, "Dockerfile": 709}
|
package org.springframework.samples.petclinic.rest.coroutine
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.samples.petclinic.mapper.OwnerMapper
import org.springframework.samples.petclinic.mapper.PetMapper
import org.springframework.samples.petclinic.mapper.VisitMapper
import org.springframework.samples.petclinic.rest.api.coroutine.OwnersCoroutineApi
import org.springframework.samples.petclinic.rest.dto.OwnerDto
import org.springframework.samples.petclinic.rest.dto.OwnerFieldsDto
import org.springframework.samples.petclinic.rest.dto.PetDto
import org.springframework.samples.petclinic.rest.dto.PetFieldsDto
import org.springframework.samples.petclinic.rest.dto.VisitDto
import org.springframework.samples.petclinic.rest.dto.VisitFieldsDto
import org.springframework.samples.petclinic.service.coroutine.CoroutineClinicService
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.util.UriComponentsBuilder
@RestController
@Profile("coroutine")
class CoroutineOwnerController(
private val clinicService: CoroutineClinicService,
private val ownerMapper: OwnerMapper,
private val petMapper: PetMapper,
private val visitMapper: VisitMapper
) : OwnersCoroutineApi {
override suspend fun addOwner(ownerDto: OwnerDto): ResponseEntity<OwnerDto> {
val owner = clinicService.saveOwner(ownerMapper.toOwner(ownerDto))
val headers = HttpHeaders()
headers.location = UriComponentsBuilder.newInstance().path("/api/owners/{id}").buildAndExpand(owner.id).toUri()
return ResponseEntity(ownerMapper.toOwnerDto(owner), headers, HttpStatus.CREATED)
}
override suspend fun deleteOwner(ownerId: Int): ResponseEntity<OwnerDto> {
return if (clinicService.deleteOwner(ownerId)) {
ResponseEntity(HttpStatus.NO_CONTENT)
} else {
ResponseEntity(HttpStatus.NOT_FOUND)
}
}
override suspend fun getOwner(ownerId: Int): ResponseEntity<OwnerDto> {
val owner = clinicService.findOwnerById(ownerId) ?: return ResponseEntity(HttpStatus.NOT_FOUND)
return ResponseEntity(ownerMapper.toOwnerDto(owner), HttpStatus.OK)
}
override suspend fun listOwners(lastName: String?, lastId: Int?, pageSize: Int?): ResponseEntity<List<OwnerDto>> {
val owners = if (lastName != null) {
clinicService.findOwnerByLastName(lastName, lastId, pageSize)
} else {
clinicService.findAllOwners(lastId, pageSize)
}
return if (owners.isEmpty()) {
ResponseEntity(HttpStatus.NOT_FOUND)
} else ResponseEntity(ownerMapper.toOwnersDto(owners), HttpStatus.OK)
}
override suspend fun updateOwner(ownerId: Int, ownerFieldsDto: OwnerFieldsDto): ResponseEntity<OwnerDto> {
val currentOwner = clinicService.findOwnerById(ownerId) ?: return ResponseEntity(HttpStatus.NOT_FOUND)
val owner = clinicService.saveOwner(
currentOwner.copy(
firstName = ownerFieldsDto.firstName,
lastName = ownerFieldsDto.lastName,
address = ownerFieldsDto.address,
city = ownerFieldsDto.city,
telephone = ownerFieldsDto.telephone
)
)
return ResponseEntity(ownerMapper.toOwnerDto(owner), HttpStatus.OK)
}
override suspend fun addPetToOwner(ownerId: Int, petFieldsDto: PetFieldsDto): ResponseEntity<PetDto> {
val pet = clinicService.savePet(petMapper.toPet(petFieldsDto).copy(ownerId = ownerId))
val headers = HttpHeaders()
headers.location = UriComponentsBuilder.newInstance().path("/api/pets/{id}").buildAndExpand(pet.id).toUri()
return ResponseEntity<PetDto>(petMapper.toPetDto(pet), headers, HttpStatus.CREATED)
}
override suspend fun addVisitToOwner(
ownerId: Int, petId: Int, visitFieldsDto: VisitFieldsDto
): ResponseEntity<VisitDto> {
val visit = clinicService.saveVisit(visitMapper.toVisit(visitFieldsDto).copy(petId = petId))
val headers = HttpHeaders()
headers.location = UriComponentsBuilder.newInstance().path("/api/visits/{id}").buildAndExpand(visit.id).toUri()
return ResponseEntity<VisitDto>(visitMapper.toVisitDto(visit), headers, HttpStatus.CREATED)
}
}
| 0 |
Kotlin
|
0
| 2 |
365b0ce4d9eaacee8c888511915c404f414cbd8c
| 4,448 |
spring-petclinic-rest
|
Apache License 2.0
|
src/main/java/io/github/lcriadof/atrevete/kotlin/capitulo4/c4p4.kt
|
lcriadof
| 344,240,788 | false | null |
/*
Atrévete con Kotlin
(un libro para programadores de back end)
ISBN: 9798596367164
Autor: http://luis.criado.online/index.html
*/
package io.github.lcriadof.atrevete.kotlin.capitulo4
import java.io.File
// programa c4p4.kt: lee un fichero de texto y lo muestra por pantalla
fun main() {
// primera versión
val lines = File("/tmp/kotlin/f3.txt").readLines() // [2] codigo equivalente
for (item in lines) {
println("linea: $item")
}
/*
// segunda versión
val lines = File("/tmp/kotlin/f3.txt").readLines() // [2] codigo equivalente
lines.forEach { println(it) }
// tercera versión
File("/tmp/kotlin/f3.txt").forEachLine { println(it) } // [1]
// cuarta versión
try {
File("/tmp/kotlin/f3.txt").forEachLine { println(it) } // [1]
}catch (e: Exception){
println(e)
}
*/
} // fin del programa
| 0 |
Kotlin
|
0
| 0 |
403586f25f549590efb1bfd7e28cb0678f5c90b5
| 879 |
AtreveteConKotlin
|
MIT License
|
src/main/kotlin/build/buf/intellij/model/BufModuleCoordinates.kt
|
bufbuild
| 467,643,829 | false |
{"Kotlin": 95920, "HTML": 140}
|
// Copyright 2022-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buf.intellij.model
data class BufModuleCoordinates(
val lockFileURL: String,
val remote: String,
val owner: String,
val repository: String,
val commit: String,
)
| 4 |
Kotlin
|
2
| 15 |
6f99300c13aac043ccb9b1408156480a278c7040
| 803 |
intellij-buf
|
Apache License 2.0
|
Kotlin/kotlin-android/app/src/main/java/com/nsz/kotlin/aac/architecture/navigation/Fragment2.kt
|
entrealist
| 389,325,711 | false | null |
package com.nsz.kotlin.aac.architecture.navigation
import androidx.fragment.app.Fragment
class Fragment2 : Fragment() {
}
| 1 | null |
1
| 1 |
5a23991a94e3fe6eaaa49263b7b78f4954edda7a
| 123 |
ReadingNote
|
MIT License
|
app/src/main/java/com/example/cosafareincitt/pagina14.kt
|
Eduardo98c
| 423,841,090 | false |
{"Kotlin": 134766}
|
package com.example.cosafareincitt
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import com.example.cosafareincitt.databinding.ActivityPagina10Binding
import com.example.cosafareincitt.databinding.ActivityPagina11Binding
import com.example.cosafareincitt.databinding.ActivityPagina13Binding
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.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.example.cosafareincitt.databinding.ActivityPagina14Binding
import java.util.*
class pagina14 : GenericPage(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private lateinit var binding: ActivityPagina14Binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pagina14)
binding = ActivityPagina14Binding.inflate(layoutInflater)
//APRI UNA PAGINA CASUALE
activityList = generatelistOfRandomPage(num_page)
val button = findViewById<Button>(R.id.button3)
openRandomPage(activityList,button,this)
setActionBar()
setMapFragment(this,R.id.map)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
//40.82466091968241, 14.329617418187794
val francesco = LatLng(40.82466091968241, 14.329617418187794)
mMap.addMarker(MarkerOptions().position(francesco).title("Paninoteca Da Francesco"))
gestisci_mappa(mMap,francesco,"Paninoteca Da Francesco",this)
}
}
| 0 |
Kotlin
|
0
| 0 |
e92dcd74a9831b315971e087d159230867d6ca1e
| 1,805 |
Iosvago
|
Apache License 2.0
|
app/src/main/java/pisal/me/learn/bankui/data/model/entity/Bank.kt
|
pisalcoding
| 762,790,403 | false |
{"Kotlin": 30259, "Java": 9663}
|
package pisal.me.learn.bankui.data.model.entity
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import java.io.Serializable
data class Bank(
val id: Int,
val name: String,
val description: String,
val logo: String,
val active: Int,
val github: String? = null,
) : Serializable
object BankDiff : ItemCallback<Bank>() {
override fun areItemsTheSame(oldItem: Bank, newItem: Bank): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Bank, newItem: Bank): Boolean {
return oldItem.id == newItem.id && oldItem.name == newItem.name
}
}
| 0 |
Kotlin
|
0
| 0 |
cda42674200a5f310b75d04e65ddebea2890b9d9
| 634 |
bank-ui-android
|
Apache License 2.0
|
plot-config-portable/src/commonMain/kotlin/jetbrains/datalore/plot/config/OptionsAccessor.kt
|
b7w
| 229,423,563 | true |
{"Kotlin": 4342986, "Python": 257583, "CSS": 1842, "C": 1638, "Shell": 1590, "JavaScript": 1584}
|
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.config
import jetbrains.datalore.base.gcommon.collect.ClosedRange
import jetbrains.datalore.base.values.Color
import jetbrains.datalore.plot.base.Aes
import jetbrains.datalore.plot.base.render.point.PointShape
import jetbrains.datalore.plot.config.aes.AesOptionConversion
import kotlin.jvm.JvmOverloads
open class OptionsAccessor protected constructor(private val myOptions: Map<*, *>, defaultOptions: Map<*, *>) {
private val myDefaultOptions: Map<*, *>
val mergedOptions: Map<*, *>
get() {
val mergedOptions = HashMap(myDefaultOptions)
mergedOptions.putAll(myOptions)
return mergedOptions
}
val isEmpty: Boolean
get() = myOptions.isEmpty() && myDefaultOptions.isEmpty()
constructor(options: Map<*, *>) : this(options, emptyMap<Any, Any>())
init {
myDefaultOptions = HashMap(defaultOptions)
}
fun update(key: String, value: Any) {
@Suppress("UNCHECKED_CAST")
(myOptions as MutableMap<String, Any>)[key] = value
}
protected fun update(otherOptions: Map<Any, Any>) {
@Suppress("UNCHECKED_CAST")
(myOptions as MutableMap<Any, Any>).putAll(otherOptions)
}
fun has(option: String): Boolean {
return hasOwn(option) || myDefaultOptions[option] != null
}
fun hasOwn(option: String): Boolean {
return myOptions[option] != null
}
operator fun get(option: String): Any? {
return if (hasOwn(option)) {
myOptions[option]
} else myDefaultOptions[option]
}
fun getString(option: String): String? {
return if (has(option)) {
get(option).toString()
} else null
}
fun getList(option: String): List<*> {
val v = get(option) ?: return ArrayList<Any>()
if (v is List<*>) {
return v
}
throw IllegalArgumentException("Not a List: " + option + ": " + v::class.simpleName)
}
fun getDoubleList(option: String): List<Double> {
val list = getList(option)
val predicate: (Any?) -> Boolean = { v -> v != null && v is Double }
if (list.all(predicate)) {
@Suppress("UNCHECKED_CAST")
return list as List<Double>
}
throw IllegalArgumentException("Expected numeric value but was : ${list.find(predicate)}")
}
fun getStringList(option: String): List<String> {
val list = getList(option)
val predicate: (Any?) -> Boolean = { v -> v != null && v is String }
if (list.all(predicate)) {
@Suppress("UNCHECKED_CAST")
return list as List<String>
}
throw IllegalArgumentException("Expected string value but was : ${list.find(predicate)}")
}
internal fun getRange(option: String): ClosedRange<Double> {
val error =
{ v: Any? -> throw IllegalArgumentException("'range' value is expected in form: [min, max] but was: $v") }
val v = get(option)
if (v is List<*> && v.isNotEmpty()) {
val lower = asDouble(v[0]) ?: error(v)
var upper = lower
if (v.size > 1) {
upper = asDouble(v[1]) ?: error(v)
}
return ClosedRange.closed(lower, upper)
}
throw IllegalArgumentException("'Range' value is expected in form: [min, max]")
}
fun getMap(option: String): Map<*, *> {
val v = get(option) ?: return emptyMap<Any, Any>()
if (v is Map<*, *>) {
return v
}
throw IllegalArgumentException("Not a Map: " + option + ": " + v::class.simpleName)
}
@JvmOverloads
fun getBoolean(option: String, def: Boolean = false): Boolean {
val v = get(option)
return v as? Boolean ?: def
}
fun getDouble(option: String): Double? {
return getValueOrNull(option) { asDouble(it) }
}
fun getInteger(option: String): Int? {
return getValueOrNull(option) { v -> (v as? Number)?.toInt() }
}
fun getLong(option: String): Long? {
return getValueOrNull(option) { v -> (v as? Number)?.toLong() }
}
private fun <T> getValueOrNull(option: String, mapper: (Any?) -> T?): T? {
val v = get(option) ?: return null
return mapper(v)
}
fun getColor(option: String): Color? {
return getValue(Aes.COLOR, option)
}
fun getShape(option: String): PointShape? {
return getValue(Aes.SHAPE, option)
}
protected fun <T> getValue(aes: Aes<T>, option: String): T? {
val v = get(option) ?: return null
return AesOptionConversion.apply(aes, v)
}
companion object {
fun over(map: Map<*, *>): OptionsAccessor {
return OptionsAccessor(map, emptyMap<Any, Any>())
}
private fun asDouble(value: Any?): Double? {
return (value as? Number)?.toDouble()
}
}
}
| 0 | null |
0
| 0 |
811327d17d6af2669d22355ee031eaa2cf5da7bc
| 5,092 |
lets-plot
|
MIT License
|
src/main/kotlin/io/jvaas/dsl/html/attribute/AttrOnOpstate.kt
|
JVAAS
| 304,887,456 | false | null |
package io.jvaas.dsl.html.attribute
// generated by HtmlDslGenerator.kt
interface AttrOnOpstate : Attr {
var onopstate: String?
get() = attributes["onopstate"]
set(value) {
value?.let {
attributes["onopstate"] = it
}
}
}
| 0 |
Kotlin
|
2
| 3 |
e6e17b834673e8755ed4cbabacabf9df2a0ffbae
| 241 |
jvaas-html
|
Apache License 2.0
|
composeApp/src/iosMain/kotlin/authentication/JwtParser.ios.kt
|
KevinMeneses
| 869,799,686 | false |
{"Kotlin": 112521, "Ruby": 2671, "Swift": 1225}
|
package authentication
import common.KotlinClass
actual fun getJwtParser(): JwtParser {
return KotlinClass.jwtParser
}
| 0 |
Kotlin
|
0
| 0 |
d26b3cd2936e99e8cb74a88a58e8935d8a5f2b40
| 124 |
PosgradosAppMultiplatform
|
Apache License 2.0
|
server/src/main/kotlin/com/thoughtworks/archguard/change/controller/response/GitHotFileDTO.kt
|
archguard
| 460,910,110 | false |
{"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32}
|
package com.thoughtworks.archguard.change.controller.response
import com.thoughtworks.archguard.change.domain.model.GitHotFilePO
import org.archguard.model.vos.JClassVO
class GitHotFileDTO(private val gitHotFilePO: GitHotFilePO) {
val jclassId: String
get() = gitHotFilePO.jclassId!!
val systemId: Long
get() = gitHotFilePO.systemId
val moduleName: String
get() {
return if (gitHotFilePO.moduleName != null) return gitHotFilePO.moduleName else ""
}
val packageName: String
get() = JClassVO(gitHotFilePO.className!!, moduleName).getPackageName()
val typeName: String
get() = JClassVO(gitHotFilePO.className!!, moduleName).getTypeName()
val modifiedCount: Int
get() = gitHotFilePO.modifiedCount
}
| 1 |
Kotlin
|
89
| 575 |
049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8
| 794 |
archguard
|
MIT License
|
shared/src/commonMain/kotlin/com/kaushalvasava/apps/instagram/models/Chat.kt
|
KaushalVasava
| 726,410,594 | false |
{"Kotlin": 173109, "Swift": 342}
|
package com.kaushalvasava.apps.instagram.models
import kotlinx.serialization.Serializable
@Serializable
data class Chat(
val senderImage: String,
val receiverImage: String,
val msgs: List<Message>,
)
| 0 |
Kotlin
|
6
| 21 |
4d42da9067004807d8a6d559201f1228f961207d
| 214 |
XPhotogram_KMP
|
The Unlicense
|
project/skyway_android_sdk/core/src/main/java/com/ntt/skyway/core/content/sink/AudioDestination.kt
|
skyway
| 594,002,280 | false |
{"Kotlin": 483484, "C++": 153735, "CMake": 7003, "Shell": 5090}
|
/*
* Copyright © 2023 NTT Communications. All rights reserved.
*/
package com.ntt.skyway.core.content.sink
import android.media.AudioTrack
import java.nio.ByteBuffer
object AudioDestination {
@Deprecated("This API is deprecated.", ReplaceWith("", ""))
var onAudioBufferHandler: ((buffer: ByteBuffer) -> Unit)? = null
@Deprecated("This API is deprecated.", ReplaceWith("", ""))
val audioTrack
get() = null
@Deprecated("This API is deprecated.", ReplaceWith("", ""))
fun changeTrack(audioTrack: AudioTrack) { }
}
| 0 |
Kotlin
|
0
| 4 |
bddfec30f132510622bcddae9b6c345647bdfbbb
| 550 |
android-sdk
|
MIT License
|
clientprotocol/src/commonMain/generated/org/inthewaves/kotlinsignald/clientprotocol/v1/requests/Trust.kt
|
inthewaves
| 398,221,861 | false | null |
// File is generated by ./gradlew generateSignaldClasses --- do not edit unless reformatting
package org.inthewaves.kotlinsignald.clientprotocol.v1.requests
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.inthewaves.kotlinsignald.clientprotocol.v1.structures.EmptyResponse
/**
* This class only represents the response from signald for the request. Make a request by creating
* an instance of [org.inthewaves.kotlinsignald.clientprotocol.v1.structures.TrustRequest] and then
* calling its `submit` function.
*/
@Serializable
@SerialName("trust")
internal data class Trust private constructor(
public override val data: EmptyResponse? = null
) : JsonMessageWrapper<EmptyResponse>()
| 12 |
Kotlin
|
1
| 2 |
9259e3f41e87f32b4bf2e6f88179489e4f36d8ca
| 736 |
kotlin-signald
|
MIT License
|
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/LayoutKanban.kt
|
DevSrSouza
| 311,134,756 | false |
{"Kotlin": 36719092}
|
package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.TablerIcons
public val TablerIcons.LayoutKanban: ImageVector
get() {
if (_layoutKanban != null) {
return _layoutKanban!!
}
_layoutKanban = Builder(name = "LayoutKanban", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 4.0f)
lineTo(10.0f, 4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.0f, 4.0f)
lineTo(20.0f, 4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 8.0f)
lineTo(8.0f, 8.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 10.0f, 10.0f)
lineTo(10.0f, 18.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 8.0f, 20.0f)
lineTo(6.0f, 20.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 4.0f, 18.0f)
lineTo(4.0f, 10.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 6.0f, 8.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.0f, 8.0f)
lineTo(18.0f, 8.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 20.0f, 10.0f)
lineTo(20.0f, 12.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 18.0f, 14.0f)
lineTo(16.0f, 14.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 14.0f, 12.0f)
lineTo(14.0f, 10.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 16.0f, 8.0f)
close()
}
}
.build()
return _layoutKanban!!
}
private var _layoutKanban: ImageVector? = null
| 17 |
Kotlin
|
25
| 571 |
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,308 |
compose-icons
|
MIT License
|
app/src/main/java/pl/vemu/zsme/ui/more/ContactItem.kt
|
xVemu
| 231,614,467 | false |
{"Kotlin": 186224, "JavaScript": 1607, "Java": 385}
|
package pl.vemu.zsme.ui.more
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.AssistantDirection
import androidx.compose.material.icons.rounded.Call
import androidx.compose.material.icons.rounded.Email
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.core.net.toUri
import pl.vemu.zsme.R
import pl.vemu.zsme.launchCustomTabs
enum class ContactItem(
val icon: ImageVector?,
@StringRes val headerText: Int,
@StringRes val text: Int,
@StringRes private val action: Int,
) {
NAME(null, R.string.school_name, R.string.school_name_text, 0),
ADDRESS(
Icons.AutoMirrored.Rounded.AssistantDirection,
R.string.school_address,
R.string.school_address_text,
R.string.school_address_action
),
OPEN(null, R.string.open_hours, R.string.open_hours_text, 0),
PHONE(
Icons.Rounded.Call,
R.string.school_phone,
R.string.school_phone_text,
R.string.school_phone_text
),
FAX(
Icons.Rounded.Call,
R.string.school_phone_fax,
R.string.school_phone_fax_text,
R.string.school_phone_fax_text
),
SECRETARY(
Icons.Rounded.Email,
R.string.secretariat_email,
R.string.secretariat_email_text,
R.string.secretariat_email_text
),
RECRUITMENT(
Icons.Rounded.Email,
R.string.recruitment_email,
R.string.recruitment_email_text,
R.string.recruitment_email_text
),
ACCOUNTANCY(
Icons.Rounded.Email,
R.string.accountancy_email,
R.string.accountancy_email_text,
R.string.accountancy_email_text
),
HEADMASTER(
Icons.Rounded.Email,
R.string.school_principal,
R.string.school_principal_text,
R.string.school_principal_action
),
VICE_HEADMASTER_1(
Icons.Rounded.Email,
R.string.school_vice_principal,
R.string.school_vice1_text,
R.string.school_vice1_action
),
VICE_HEADMASTER_2(
Icons.Rounded.Email,
R.string.school_vice_principal,
R.string.school_vice2_text,
R.string.school_vice2_action
),
SOURCE_CODE(
Icons.Rounded.Github,
R.string.source_code,
R.string.source_code_text,
R.string.github_url
);
fun onClick(context: Context) {
val actionString = context.getString(action)
try {
when (icon) {
Icons.Rounded.Call -> context.startActivity(
Intent(
Intent.ACTION_DIAL,
"tel:$actionString".toUri()
)
)
Icons.Rounded.Email -> context.startActivity(
Intent(
Intent.ACTION_SENDTO,
"mailto:$actionString".toUri()
)
)
else -> context.launchCustomTabs(actionString)
}
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.no_app, Toast.LENGTH_LONG).show()
}
}
}
| 0 |
Kotlin
|
0
| 3 |
b36f9958b13395ca00af2bc651b9ff9fa33d2666
| 3,346 |
zsme
|
MIT License
|
core/src/main/java/api/openevent/auth/AuthToken.kt
|
iamareebjamal
| 123,676,070 | false |
{"Gradle": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 1, "Kotlin": 26, "INI": 1}
|
package api.openevent.auth
import com.fasterxml.jackson.annotation.JsonProperty
data class AuthToken(@JsonProperty("access_token") val accessToken: String)
| 0 |
Kotlin
|
0
| 0 |
c38fe0877ba53aec9581e9995f0a71c7a2f2025f
| 157 |
openevent-java
|
Apache License 2.0
|
noiseview/src/main/kotlin/pl/hypeapp/noiseview/RandomNoise.kt
|
rostopira
| 108,474,518 | true |
{"Kotlin": 8396, "RenderScript": 636}
|
package pl.hypeapp.noiseview
import android.content.Context
import android.graphics.*
import android.support.v8.renderscript.Allocation
import android.support.v8.renderscript.RenderScript
/** Noise drawable based on RenderScript **/
internal class RandomNoise(ctx: Context): NoiseRenderable {
private val rs = RenderScript.create(ctx)
private val script = ScriptC_noise(rs)
private val paint = Paint().apply {
color = Color.WHITE
xfermode = PorterDuffXfermode(PorterDuff.Mode.SCREEN)
}
private var matrix = Matrix()
private var width = 0
get() = Math.round(field * scale)
set(value) { // TODO: rewrite repeating setter with delegate
if (field != value)
destroy()
field = value
}
private var height = 0
get() = Math.round(field * scale)
set(value) {
if (field != value)
destroy()
field = value
}
override var bitmap: Bitmap? = null
/** Here - probability of noise dot appearing **/
override var noiseIntensity = 1f
set(value) {
if (value !in 0f..1f)
throw IllegalArgumentException("Intensity must be in 0f..1f")
field = value / 10
script._intensity = Math.round(25.5f * value).toShort()
}
private var lastGrainOffset = System.currentTimeMillis()
override var grainFps = 0
/** That's obvious **/
var colored = false
set(value) {
if (field != value)
destroy()
field = value
}
override var scale = 1f
set(value) {
if (field != value)
destroy()
field = value
matrix.setScale(1f / value, 1f / value)
}
override fun draw(canvas: Canvas) {
width = canvas.width
height = canvas.height
if (bitmap == null)
update()
canvas.drawBitmap(bitmap, matrix, paint)
}
//TODO: check for race-condition issues
override fun update() {
if (bitmap != null && lastGrainOffset + grainFps > System.currentTimeMillis())
return
val b = bitmap ?: Bitmap.createBitmap(width, height,
if (colored)
Bitmap.Config.ARGB_8888
else
Bitmap.Config.ALPHA_8
)
bitmap = b
val alloc = Allocation.createFromBitmap(rs, b)
if (colored)
script.forEach_color(alloc, alloc)
else
script.forEach_mono(alloc, alloc)
alloc.copyTo(b)
lastGrainOffset = System.currentTimeMillis()
}
}
| 0 |
Kotlin
|
0
| 1 |
a1fd7b1216aad8ba41685617d78e5eb02206b30c
| 2,662 |
NoiseView
|
MIT License
|
src/main/kotlin/io/github/dqualizer/dqlang/types/rqa/definition/resilience/stimulus/UnavailablilityStimulus.kt
|
dqualizer
| 610,310,524 | false |
{"Kotlin": 110854, "HTML": 3542, "Python": 3352}
|
package io.github.dqualizer.dqlang.types.rqa.definition.resilience.stimulus
data class UnavailabilityStimulus(
override val pauseBeforeTriggeringSeconds: Int,
override val experimentDurationSeconds: Int
) : ResilienceStimulus()
| 6 |
Kotlin
|
0
| 0 |
938543c2fd0602879492bd9183c668d98d631f3c
| 233 |
dqlang
|
Apache License 2.0
|
vclib/src/commonMain/kotlin/at/asitplus/wallet/lib/agent/IssuerCredentialDataProvider.kt
|
a-sit-plus
| 602,578,639 | false |
{"Kotlin": 697410}
|
package at.asitplus.wallet.lib.agent
import at.asitplus.KmmResult
import at.asitplus.crypto.datatypes.CryptoPublicKey
import at.asitplus.wallet.lib.data.ConstantIndex
import at.asitplus.wallet.lib.data.CredentialSubject
import at.asitplus.wallet.lib.iso.IssuerSignedItem
import kotlinx.datetime.Instant
/**
* Provides data for credentials to be issued.
*/
interface IssuerCredentialDataProvider {
/**
* Gets called with a resolved [credentialScheme], the holder key in [subjectPublicKey] and the requested
* credential [representation].
* Callers may optionally define some attribute names from [ConstantIndex.CredentialScheme.claimNames] in
* [claimNames] to request only some claims (if supported by the representation).
*/
fun getCredential(
subjectPublicKey: CryptoPublicKey,
credentialScheme: ConstantIndex.CredentialScheme,
representation: ConstantIndex.CredentialRepresentation,
claimNames: Collection<String>? = null,
): KmmResult<CredentialToBeIssued>
}
sealed class CredentialToBeIssued {
data class VcJwt(
val subject: CredentialSubject,
val expiration: Instant,
) : CredentialToBeIssued()
data class VcSd(
val claims: Collection<ClaimToBeIssued>,
val expiration: Instant,
) : CredentialToBeIssued()
data class Iso(
val issuerSignedItems: List<IssuerSignedItem>,
val expiration: Instant,
) : CredentialToBeIssued()
}
data class ClaimToBeIssued(val name: String, val value: Any)
| 7 |
Kotlin
|
2
| 9 |
cd329850e8ccd735cd2b8f43624059b60dbd0008
| 1,538 |
kmm-vc-library
|
Apache License 2.0
|
task-core/src/main/kotlin/i/task/ITaskRollbackInfo.kt
|
OpenEdgn
| 408,372,997 | false |
{"Kotlin": 19269, "Java": 725}
|
package i.task
/**
* 日志错误回滚原因信息
*/
interface ITaskRollbackInfo {
/**
* 回滚触发原因
*/
val type: TaskRollbackType
/**
* 回滚触发详情
*/
val error: TaskException
}
| 0 |
Kotlin
|
1
| 0 |
8e873b51c29ff159e8d3048e7e02a8f24d17892f
| 193 |
TaskManager
|
MIT License
|
app/src/main/java/com/mexator/petfinder_client/ui/activity/LoginActivity.kt
|
Mexator
| 261,837,159 | false | null |
package com.mexator.petfinder_client.ui.activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.mexator.petfinder_client.R
import com.mexator.petfinder_client.mvvm.viewmodel.LoginViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
private lateinit var viewModel: LoginViewModel
private val compositeDisposable = CompositeDisposable()
private val TAG = "LoginActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
setupProgressSubscription()
button_submit.setOnClickListener { onConfirmButtonClicked() }
button_sign_up.setOnClickListener { onSignUpButtonClicked() }
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.dispose()
}
private fun onConfirmButtonClicked() {
val login = login_edit.editText!!.text.toString()
val pass = password_edit.editText!!.text.toString()
val job = viewModel.isCredentialDataValid(login, pass)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { value -> onCheckFinished(value) }
compositeDisposable.add(job)
}
private fun onCheckFinished(checkResult: Boolean) {
if (checkResult)
onSuccessfulLogin()
else
Toast.makeText(this, R.string.text_error_login, Toast.LENGTH_SHORT).show()
}
private fun onSuccessfulLogin() {
val mainIntent = Intent(this, MainActivity::class.java)
mainIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(mainIntent)
finish()
}
private fun onSignUpButtonClicked() {
val signUpUrl = "https://www.petfinder.com/"
val browserIntent = Intent(Intent.ACTION_VIEW)
browserIntent.data = Uri.parse(signUpUrl)
startActivity(browserIntent)
}
private fun setupProgressSubscription() {
val job =
viewModel.getProgressIndicator()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
progress.visibility = if (it) View.VISIBLE else View.GONE
button_submit.isEnabled = !it
}
compositeDisposable.add(job)
}
}
| 0 |
Kotlin
|
0
| 0 |
703ef76b8274b5776cbc69e931298a589cd131d2
| 2,817 |
Petfinder-mobile-client
|
MIT License
|
src/main/kotlin/br/com/zup/pix/lista/ListaChavesEndpoint.kt
|
taissasantos
| 347,969,608 | true |
{"Kotlin": 27555}
|
package br.com.zup.pix.lista
import br.com.zup.*
import br.com.zup.pix.repository.ChavePixRespository
import br.com.zup.shared.ErrorHandler
import com.google.protobuf.Timestamp
import io.grpc.stub.StreamObserver
import java.time.ZoneId
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@ErrorHandler
@Singleton
class ListaChavesEndpoint(@Inject private val repository: ChavePixRespository)
: ListaChavePixServiceGrpc.ListaChavePixServiceImplBase() {
override fun lista(request: ListaChavePixRequest,
responseObserver: StreamObserver<ListaChavePixResponse>) {
if(request.clientId.isNullOrBlank())
throw IllegalArgumentException("Cliente ID não pode ser nulo, ou vazio")
val clientId = UUID.fromString(request.clientId)
val chaves = repository.findAllByClientId(clientId).map {
ListaChavePixResponse.ChavePix.newBuilder()
.setPixId(it.id.toString())
.setTipo(TipoDeChave.valueOf(it.tipo.name))
.setChave(it.chave)
.setTipoDeConta(TipoDeConta.valueOf(it.tipoDeConta.name))
.setCriadaEm(it.registradaEm.let {
val createdAt = it.atZone(ZoneId.of("UTC")).toInstant()
Timestamp.newBuilder()
.setSeconds(createdAt.epochSecond)
.setNanos(createdAt.nano)
.build()
})
.build()
}
responseObserver.onNext(ListaChavePixResponse.newBuilder()
.setClientId(clientId.toString())
.addAllChaves(chaves)
.build())
responseObserver.onCompleted()
}
}
| 0 |
Kotlin
|
0
| 0 |
16ad65e58d9e265566f3bcf6ac338808c9d30076
| 1,794 |
orange-talents-01-template-pix-keymanager-grpc
|
Apache License 2.0
|
src/tecrys/svc/plugins/substanceabuse/makeRecipeItem.kt
|
DesperatePeter
| 646,942,220 | false |
{"Kotlin": 186711, "Java": 120549}
|
package tecrys.svc.plugins.substanceabuse
import com.fs.starfarer.api.campaign.impl.items.GenericSpecialItemPlugin
import tecrys.svc.modintegration.isSubstanceAbuseEnabled
fun makeRecipeItem(): GenericSpecialItemPlugin?{
if (isSubstanceAbuseEnabled()) {
return try {
com.fs.starfarer.api.alcoholism.itemPlugins.RecipeItemPlugin()
} catch (e: NoClassDefFoundError) {
null
}
}
return null
}
| 3 |
Kotlin
|
0
| 3 |
01ef18c2906a5c39983967ca58956ce7d646286e
| 450 |
starsector-symbiotic-void-creatures
|
MIT License
|
src/main/kotlin/no/nav/fo/veilarbregistrering/config/filters/AuthStatsFilter.kt
|
navikt
| 131,013,336 | false | null |
package no.nav.fo.veilarbregistrering.config.filters
import com.nimbusds.jwt.JWT
import com.nimbusds.jwt.JWTParser
import io.micrometer.core.instrument.Tag
import no.nav.common.auth.Constants
import no.nav.fo.veilarbregistrering.log.loggerFor
import no.nav.fo.veilarbregistrering.log.secureLogger
import no.nav.fo.veilarbregistrering.metrics.Events
import no.nav.fo.veilarbregistrering.metrics.MetricsService
import org.slf4j.MDC
import org.springframework.http.HttpHeaders
import java.text.ParseException
import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
class AuthStatsFilter(private val metricsService: MetricsService) : Filter {
private val ID_PORTEN = "ID-PORTEN"
private val AAD = "AAD"
private val TOKEN_X = "TOKENX"
private val STS = "STS"
override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, chain: FilterChain) {
val request: HttpServletRequest = servletRequest as HttpServletRequest
val consumerId = getConsumerId(request)
val cookieNames = request.cookies?.map { it.name } ?: emptyList()
val headerValue = request.getHeader(HttpHeaders.AUTHORIZATION)
val bearerToken = headerValue?.substring("Bearer ".length)
val selvbetjeningToken =
request.cookies?.filter { it.name == Constants.AZURE_AD_B2C_ID_TOKEN_COOKIE_NAME }?.map { it.value }
?.firstOrNull()
val type = when {
Constants.AZURE_AD_B2C_ID_TOKEN_COOKIE_NAME in cookieNames -> selvbetjeningToken?.let { checkTokenForType(it) }
?: ID_PORTEN
Constants.AZURE_AD_ID_TOKEN_COOKIE_NAME in cookieNames -> AAD
!bearerToken.isNullOrBlank() -> checkTokenForType(bearerToken)
else -> null
}
try {
type?.let {
MDC.put(TOKEN_TYPE, type)
metricsService.registrer(Events.REGISTRERING_TOKEN, Tag.of("type", type), Tag.of("consumerId", consumerId))
log.info("Authentication with: [$it] request path: [${request.servletPath}] consumer: [$consumerId]")
if (type == STS) {
secureLogger.info("Bruk av STS-token mot $consumerId. Token fra cookie: $selvbetjeningToken Token fra Auth-header: $bearerToken")
}
}
chain.doFilter(servletRequest, servletResponse)
} finally {
MDC.remove(TOKEN_TYPE)
}
}
private fun checkTokenForType(token: String): String =
try {
val jwt = JWTParser.parse(token)
when {
jwt.erAzureAdToken() -> AAD
jwt.erIdPortenToken() -> ID_PORTEN
jwt.erTokenXToken() -> TOKEN_X
else -> STS
}
} catch (e: ParseException) {
log.warn("Couldn't parse token $token")
when {
token.contains("microsoftonline.com") -> AAD
token.contains("difi.no") -> ID_PORTEN
token.contains("tokendings") -> TOKEN_X
else -> STS
}
}
companion object {
private const val TOKEN_TYPE = "tokenType"
private val log = loggerFor<AuthStatsFilter>()
private fun getConsumerId(request: HttpServletRequest): String = request.getHeader("Nav-Consumer-Id") ?: "UKJENT"
}
}
fun JWT.erAzureAdToken(): Boolean = this.jwtClaimsSet.issuer.contains("microsoftonline.com")
fun JWT.erIdPortenToken(): Boolean = this.jwtClaimsSet.issuer.contains("difi.no")
fun JWT.erTokenXToken(): Boolean = this.jwtClaimsSet.issuer.contains("tokendings")
| 18 | null |
5
| 6 |
b608c00bb1a2d1fce4fa7703b24f51e692ad5860
| 3,737 |
veilarbregistrering
|
MIT License
|
compiler/testData/ir/irText/firProblems/FlushFromAnonymous.kt
|
JetBrains
| 3,432,266 | false | null |
// TARGET_BACKEND: JVM_IR
// DUMP_LOCAL_DECLARATION_SIGNATURES
// SKIP_KLIB_TEST
// MUTE_SIGNATURE_COMPARISON_K2: ANY
// ^ KT-57430
// FILE: Collector.java
public class Collector {
public void flush() {}
}
// FILE: FlushFromAnonymous.kt
class Serializer() {
fun serialize() {
val messageCollector = createMessageCollector()
try {
} catch (e: Throwable) {
messageCollector.flush()
}
}
private fun createMessageCollector() = object : Collector() {}
}
| 163 | null |
5686
| 46,039 |
f98451e38169a833f60b87618db4602133e02cf2
| 516 |
kotlin
|
Apache License 2.0
|
app/src/main/java/com/kotlin/mvvm/boilerplate/util/TimeUtil.kt
|
cuongpm
| 159,537,503 | false | null |
package com.kotlin.mvvm.boilerplate.util
import android.text.format.DateUtils
/**
* Created by cuongpm on 1/2/19.
*/
fun getRelativeTime(time: Long): String {
return DateUtils.getRelativeTimeSpanString(
time * 1000,
System.currentTimeMillis(),
DateUtils.DAY_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL
).toString()
}
| 1 |
Kotlin
|
9
| 34 |
bfb85ba2405dd65964362745ee2c0d76ef912ee4
| 356 |
kotlin-mvvm-boilerplate
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppscontactsapi/integration/resource/CountryIntegrationTest.kt
|
ministryofjustice
| 835,306,273 | false |
{"Kotlin": 382666, "Shell": 2356, "Dockerfile": 1483}
|
package uk.gov.justice.digital.hmpps.hmppscontactsapi.integration.resource
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.http.MediaType
import org.springframework.test.web.reactive.server.WebTestClient
import uk.gov.justice.digital.hmpps.hmppscontactsapi.integration.H2IntegrationTestBase
import uk.gov.justice.digital.hmpps.hmppscontactsapi.model.response.Country
class CountryIntegrationTest : H2IntegrationTestBase() {
companion object {
private const val GET_COUNTRY_REFERENCE_DATA = "/country-reference"
}
@Nested
inner class GetCountryByCountryId {
@Test
fun `should return unauthorized if no token`() {
webTestClient.get()
.uri("/country-reference/001")
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return forbidden if no role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/001")
.headers(setAuthorisation())
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return forbidden if wrong role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/001")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG")))
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return not found if no country found`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/999")
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `should return country reference data when using the id`() {
val countryReferences = webTestClient.getCountryReferenceData("$GET_COUNTRY_REFERENCE_DATA/264")
assertThat(countryReferences).extracting("nomisDescription").contains("Yugoslavia")
assertThat(countryReferences).extracting("nomisCode").contains("YU")
assertThat(countryReferences).hasSize(1)
}
private fun WebTestClient.getCountryReferenceData(url: String): MutableList<Country> =
get()
.uri(url)
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isOk
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(Country::class.java)
.returnResult().responseBody!!
}
@Nested
inner class GetCountryByNomisCode {
@Test
fun `should return unauthorized if no token`() {
webTestClient.get()
.uri("/country-reference/nomis-code/YU")
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return forbidden if no role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/nomis-code/YU")
.headers(setAuthorisation())
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return forbidden if wrong role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/nomis-code/YU")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG")))
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return not found if no country found`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/nomis-code/YY")
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `should return country reference data when using the nomis code`() {
val countryReferences = webTestClient.getCountryReferenceData("$GET_COUNTRY_REFERENCE_DATA/nomis-code/YU")
assertThat(countryReferences).extracting("nomisDescription").contains("Yugoslavia")
assertThat(countryReferences).extracting("nomisCode").contains("YU")
assertThat(countryReferences).hasSize(1)
}
private fun WebTestClient.getCountryReferenceData(url: String): MutableList<Country> =
get()
.uri(url)
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isOk
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(Country::class.java)
.returnResult().responseBody!!
}
@Nested
inner class GetCountryByIsoAlpha2 {
@Test
fun `should return unauthorized if no token`() {
webTestClient.get()
.uri("/country-reference/iso-alpha2/b6")
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return forbidden if no role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/iso-alpha2/b6")
.headers(setAuthorisation())
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return forbidden if wrong role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/iso-alpha2/b6")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG")))
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return not found if no country found`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/iso-alpha2/z6")
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `should return country reference data when using the iso alpha code 2`() {
val countryReferences = webTestClient.getCountryReferenceData("$GET_COUNTRY_REFERENCE_DATA/iso-alpha2/b6")
assertThat(countryReferences).extracting("nomisDescription").contains("Yugoslavia")
assertThat(countryReferences).extracting("nomisCode").contains("YU")
assertThat(countryReferences).hasSize(1)
}
private fun WebTestClient.getCountryReferenceData(url: String): MutableList<Country> =
get()
.uri(url)
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isOk
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(Country::class.java)
.returnResult().responseBody!!
}
@Nested
inner class GetCountryByIsoAlpha3 {
@Test
fun `should return unauthorized if no token`() {
webTestClient.get()
.uri("/country-reference/iso-alpha3/bn6")
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return forbidden if no role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/iso-alpha3/bn6")
.headers(setAuthorisation())
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return forbidden if wrong role`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/iso-alpha3/bn6")
.headers(setAuthorisation(roles = listOf("ROLE_WRONG")))
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return not found if no country found`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/iso-alpha3/z6")
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `should return country reference data when using the iso alpha code 3`() {
val countryReferences = webTestClient.getCountryReferenceData("$GET_COUNTRY_REFERENCE_DATA/iso-alpha3/bn6")
assertThat(countryReferences).extracting("nomisDescription").contains("Yugoslavia")
assertThat(countryReferences).extracting("nomisCode").contains("YU")
assertThat(countryReferences).hasSize(1)
}
private fun WebTestClient.getCountryReferenceData(url: String): MutableList<Country> =
get()
.uri(url)
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isOk
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(Country::class.java)
.returnResult().responseBody!!
}
@Nested
inner class GetAllCountries {
@Test
fun `should return unauthorized if no token`() {
webTestClient.get()
.uri(GET_COUNTRY_REFERENCE_DATA)
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return forbidden if no role`() {
webTestClient.get()
.uri(GET_COUNTRY_REFERENCE_DATA)
.headers(setAuthorisation())
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return forbidden if wrong role`() {
webTestClient.get()
.uri(GET_COUNTRY_REFERENCE_DATA)
.headers(setAuthorisation(roles = listOf("ROLE_WRONG")))
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return not found if no country found`() {
webTestClient.get()
.uri("$GET_COUNTRY_REFERENCE_DATA/10001")
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `should return country reference data when get all countries`() {
val countryReferences = webTestClient.getCountryReferenceData(GET_COUNTRY_REFERENCE_DATA)
val country = Country(
countryId = 1L,
nomisCode = "ZWE",
nomisDescription = "Zimbabwe",
isoNumeric = 716,
isoAlpha2 = "ZW",
isoAlpha3 = "ZWE",
isoCountryDesc = "Zimbabwe",
displaySequence = 99,
)
assertThat(countryReferences.contains(country))
assertThat(countryReferences).hasSizeGreaterThan(10)
}
private fun WebTestClient.getCountryReferenceData(url: String): MutableList<Country> =
get()
.uri(url)
.headers(setAuthorisation(roles = listOf("ROLE_CONTACTS_ADMIN")))
.exchange()
.expectStatus()
.isOk
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(Country::class.java)
.returnResult().responseBody!!
}
}
| 5 |
Kotlin
|
0
| 0 |
fe2bc21a1af8b410366013188382a38fa7d95b1b
| 10,281 |
hmpps-contacts-api
|
MIT License
|
app/src/main/java/com/fmt/compose/news/ui/music/db/MusicDao.kt
|
fmtjava
| 376,556,406 | false | null |
package com.fmt.compose.news.ui.music.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface MusicDao {
@Query("select * from music")
fun getMusicList(): LiveData<List<Music>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(musicList: List<Music>)
}
| 1 |
Kotlin
|
13
| 66 |
ef94d98ab385cbb02891d8ed9d9c65d4879524aa
| 411 |
Jetpack_Compose_News
|
MIT License
|
tachikoma-internal-api/src/main/kotlin/com/sourceforgery/tachikoma/common/Utils.kt
|
SourceForgery
| 112,076,342 | false |
{"Kotlin": 752156, "HTML": 63351, "Shell": 15119, "Go": 9381, "Java": 7057, "Batchfile": 6874, "Dockerfile": 2036, "Procfile": 111}
|
package com.sourceforgery.tachikoma.common
import com.google.protobuf.Timestamp
import java.time.Clock
import java.time.Instant
import java.util.concurrent.ThreadLocalRandom
inline fun randomDelay(
millis: LongRange,
alwaysRun: () -> Unit,
) {
try {
val randomMillis = ThreadLocalRandom.current().nextLong(millis.first, millis.last)
Thread.sleep(randomMillis)
} finally {
alwaysRun()
}
}
fun Instant.toTimestamp(): Timestamp =
Timestamp.newBuilder()
.setSeconds(this.epochSecond)
.setNanos(this.nano)
.build()
fun Timestamp.toInstant(): Instant = Instant.ofEpochSecond(this.seconds, this.nanos.toLong())
fun Clock.timestamp() = this.instant().toTimestamp()
fun Timestamp.before(other: Timestamp) =
if (this.seconds == other.seconds) {
this.nanos < other.nanos
} else {
this.seconds < other.seconds
}
| 8 |
Kotlin
|
3
| 4 |
b746488c154a53033e237be80b5ae4bdedb85a70
| 906 |
tachikoma
|
Apache License 2.0
|
server/world/src/main/kotlin/EngineTemplateLoader.kt
|
Guthix
| 270,323,476 | false |
{"Kotlin": 667208}
|
/*
* Copyright 2018-2021 Guthix
*
* 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.guthix.oldscape.server
import io.guthix.oldscape.server.plugin.Script
import io.guthix.oldscape.server.template.ObjTemplate
import io.guthix.oldscape.server.template.loadTemplates
import io.guthix.oldscape.server.world.entity.interest.bodyGear
import io.guthix.oldscape.server.world.entity.interest.headGear
import io.guthix.oldscape.server.world.entity.interest.weapon
class EngineTemplateLoader : Script() {
init {
loadTemplates("/template/BodyGear.yaml", ServerContext.objTemplates, ObjTemplate::bodyGear)
loadTemplates("/template/HeadGear.yaml", ServerContext.objTemplates, ObjTemplate::headGear)
loadTemplates("/template/Weapons.yaml", ServerContext.objTemplates, ObjTemplate::weapon)
}
}
| 2 |
Kotlin
|
9
| 43 |
bbf40d18940a12155a33341a1c99ba47289b8e2a
| 1,330 |
OldScape
|
Apache License 2.0
|
src/kotlin/de/monticore/lang/montisecarc/psi/impl/mixin/MSAComponentInstanceImplMixin.kt
|
MontiSecArc
| 82,662,403 | false | null |
package de.monticore.lang.montisecarc.psi.impl.mixin
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import de.monticore.lang.montisecarc.psi.MSAComponentInstanceDeclaration
import de.monticore.lang.montisecarc.psi.impl.MSAStubbedNamedElementImpl
import de.monticore.lang.montisecarc.stubs.elements.MSAComponentInstanceStub
/**
* Copyright 2017 thomasbuning
*
* 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.
*/
abstract class MSAComponentInstanceImplMixin: MSAStubbedNamedElementImpl<MSAComponentInstanceStub>, MSAComponentInstanceDeclaration {
constructor(node: ASTNode) : super(node)
constructor(stub: MSAComponentInstanceStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
private val foundPolicyViolations = mutableListOf<String>()
override fun addPolicyViolation(violation: String) {
foundPolicyViolations.add(violation)
}
override fun getPolicyViolations(): List<String> {
return foundPolicyViolations
}
}
| 0 |
Kotlin
|
2
| 1 |
82d80a3d587a3f47e961034cf7e496f7149fd912
| 1,504 |
intellij_msa_language_plugin
|
Apache License 2.0
|
algorithm/src/main/kotlin/com/alexvanyo/composelife/util/BoundsExtensions.kt
|
alexvanyo
| 375,146,193 | false | null |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alexvanyo.composelife.util
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import kotlin.math.floor
/**
* Returns all [IntOffset]s that are contained in the [IntRect].
*
* This includes all [IntOffset] on the border of the [IntRect] ([IntRect.topLeft], [IntRect.bottomRight], etc.).
*
* The points are returned in row-major order.
*/
fun IntRect.containedPoints(): List<IntOffset> =
(top..bottom).flatMap { row ->
(left..right).map { column ->
IntOffset(column, row)
}
}
/**
* Converts a pair of [Int] to an [IntOffset].
*/
fun Pair<Int, Int>.toIntOffset() = IntOffset(first, second)
/**
* Converts an [IntOffset] to a pair of [Int].
*/
fun IntOffset.toPair() = x to y
/**
* Returns the 8 diagonal and orthogonal neighbors to the [IntOffset].
*/
fun IntOffset.getNeighbors(): Set<IntOffset> = neighborOffsets.map { it + this }.toSet()
private val neighborOffsets = listOf(
IntOffset(-1, -1),
IntOffset(0, -1),
IntOffset(1, -1),
IntOffset(-1, 0),
IntOffset(1, 0),
IntOffset(-1, 1),
IntOffset(0, 1),
IntOffset(1, 1),
)
/**
* Floors an [Offset] into an [IntOffset], taking the [floor] of both coordinates.
*/
fun floor(offset: Offset): IntOffset = IntOffset(floor(offset.x).toInt(), floor(offset.y).toInt())
| 5 |
Kotlin
|
0
| 3 |
4e1703b484c6cd622149792b3477eeeae9c0f98c
| 2,001 |
composelife
|
Apache License 2.0
|
src/main/kotlin/com/alipay/sofa/koupleless/kouplelessidea/parser/visitor/xml/XmlVisitor.kt
|
koupleless
| 783,180,038 | false |
{"Kotlin": 840464, "Java": 26198, "Shell": 3994}
|
package com.alipay.sofa.koupleless.kouplelessidea.parser.visitor.xml
import org.apache.commons.configuration2.XMLConfiguration
/**
* @description: Xml 解析的 Visitor抽象类,用于处理 XMLConfiguration
* @author lipeng
* @date 2023/8/14 18:14
*/
abstract class XmlVisitor<A> {
fun parse(absolutePath:String,xmlConfig: XMLConfiguration,arg:A?){
try {
if(!checkPreCondition(absolutePath,xmlConfig,arg)) return
doParse(absolutePath,xmlConfig,arg)
}catch (e:Exception){
throw RuntimeException("ERROR, XmlVisitor for absolutePath: $absolutePath", e)
}
}
abstract fun doParse(absolutePath:String,xmlConfig: XMLConfiguration,arg:A?)
/**
* 符合前置条件才执行
* @param
* @return
*/
open fun checkPreCondition(absolutePath:String,xmlConfig: XMLConfiguration,arg:A?):Boolean{
return true
}
}
| 1 |
Kotlin
|
1
| 2 |
371a738491d60019d9c25a131fab484ad8064fc2
| 881 |
koupleless-idea
|
Apache License 2.0
|
app/src/main/kotlin/network/Api.kt
|
dybarsky
| 321,612,283 | false |
{"Kotlin": 12994}
|
package network
import domain.Current
import domain.Version
import retrofit2.Response
import retrofit2.http.GET
interface Api {
@GET("api/version")
suspend fun version(): Response<Version>
@GET("api/job")
suspend fun job(): Response<Current>
}
| 0 |
Kotlin
|
0
| 1 |
4522dd1581f6307db5afcde141134806af760ce3
| 264 |
octo-print-tui
|
MIT License
|
src/main/kotlin/com/tang/hwplib/reader/bodytext/paragraph/control/gso/pack/Package.kt
|
accforaus
| 169,677,219 | false | null |
package com.tang.hwplib.reader.bodytext.paragraph.control.gso.pack
import com.tang.hwplib.objects.bodytext.control.bookmark.HWPParameterSet
import com.tang.hwplib.objects.bodytext.control.bookmark.HWPParameterType
import com.tang.hwplib.objects.bodytext.control.ctrlheader.HWPCtrlHeaderGso
import com.tang.hwplib.objects.bodytext.control.gso.HWPGsoControl
import com.tang.hwplib.objects.bodytext.control.gso.HWPGsoControlType
import com.tang.hwplib.objects.bodytext.control.gso.caption.HWPCaption
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.HWPShapeComponent
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.HWPShapeComponentContainer
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.HWPShapeComponentNormal
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.line.HWPOutlineStyle
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.picture.HWPColorWithEffect
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.picture.HWPPictureEffect
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.render.HWPMatrix
import com.tang.hwplib.objects.bodytext.control.gso.shapecomponent.shadow.HWPShadowType
import com.tang.hwplib.objects.bodytext.control.gso.textbox.HWPTextBox
import com.tang.hwplib.objects.docinfo.HWPDocInfo
import com.tang.hwplib.reader.bodytext.paragraph.forParagraphList
import com.tang.hwplib.reader.docinfo.borderfill.forFillInfo
import com.tang.hwplib.util.binary.get
import com.tang.hwplib.reader.util.StreamReader
import com.tang.hwplib.objects.etc.*
import com.tang.hwplib.reader.bodytext.paragraph.control.bookmark.ForParameterSet
/**
* 캡션 [HWPCaption]을 읽는 함수
*
* @author accforaus
*
* @param [caption] [HWPCaption], 빈 캡션 객체
* @param [sr] [StreamReader], 스트림 리더 객체
*/
internal fun forCaption(caption: HWPCaption, sr: StreamReader, docInfo : HWPDocInfo) {
caption.listHeaderForCaption.run {
paraCount = sr.readInt32()
property.value = sr.readUInt32()
captionProperty.value = sr.readUInt32()
captionWidth = sr.readHwpUnit()
spaceBetweenCaptionAndFrame = sr.readUInt16()
textWidth = sr.readHwpUnit()
sr.skip(8)
}
forParagraphList(caption.paragraphList, sr, docInfo)
}
/**
* 개체 컨트롤 헤더 [HWPCtrlHeaderGso]를 읽는 함수
* 개체 공통 속성을 읽는다.
*
* @author accforaus
*
* @param [header] [HWPCtrlHeaderGso], 빈 개체 컨트롤 헤더
* @param [sr] [StreamReader], 스트림 리더 객체
*/
internal fun forCtrlHeaderGso(header: HWPCtrlHeaderGso, sr: StreamReader) {
header.run {
property.value = sr.readUInt32()
yOffset = sr.readHwpUnit()
xOffset = sr.readHwpUnit()
width = sr.readHwpUnit()
height = sr.readHwpUnit()
zOrder = sr.readInt32()
outerMarginLeft = sr.readUInt16()
outerMarginRight = sr.readUInt16()
outerMarginTop = sr.readUInt16()
outerMarginBottom = sr.readUInt16()
instanceId = sr.readUInt32()
if (sr.header.size > sr.readAfterHeader)
preventPageDivide = get(sr.readInt32(), 0)
if (sr.header.size > sr.readAfterHeader)
explanation = sr.readUTF16LEString()
}
}
/**
* 그림 효과 [HWPPictureEffect]를 읽는 함수
*
* @author accforaus
*
* @param [pe] [HWPPictureEffect], 빈 그림 효과 객체
* @param [sr] [StreamReader], 스트림 리더 객
*/
internal fun forPictureEffect(pe: HWPPictureEffect, sr: StreamReader) {
fun colorProperty(cp: HWPColorWithEffect) {
cp.run {
type = sr.readInt32()
if (type == 0) {
val color: ByteArray = ByteArray(4)
sr.readBytes(color)
this.color = color
} else throw Exception("Not supported Color type !!!")
val colorEffectCount: Int = sr.readUInt32().toInt()
for (index in 0 until colorEffectCount) {
addNewColorEffect().also {
it.sort = sr.readInt32()
it.value = sr.readFloat()
}
}
}
}
pe.property.value = sr.readUInt32()
if (pe.property.hasShadowEffect()) {
pe.createShadowEffect()
pe.shadowEffect?.run {
style = sr.readInt32()
transparency = sr.readFloat()
cloudy = sr.readFloat()
direction = sr.readFloat()
distance = sr.readFloat()
sort = sr.readInt32()
tiltAngleX = sr.readFloat()
tiltAngleY = sr.readFloat()
zoomRateX = sr.readFloat()
zoomRateY = sr.readFloat()
rotateWithShape = sr.readInt32()
colorProperty(color)
}
}
if (pe.property.hasNeonEffect()) {
pe.createNeonEffect()
pe.neonEffect?.run {
transparency = sr.readFloat()
radius = sr.readFloat()
colorProperty(color)
}
}
if (pe.property.hasSoftBorderEffect()) {
pe.createSoftEdgeEffect()
pe.softEdgeEffect?.run {
radius = sr.readFloat()
}
}
if (pe.property.hasReflectionEffect()) {
pe.createReflectionEffect()
pe.reflectionEffect?.run {
style = sr.readInt32()
radius = sr.readFloat()
direction = sr.readFloat()
distance = sr.readFloat()
tiltAngleX = sr.readFloat()
tiltAngleY = sr.readFloat()
zoomRateX = sr.readFloat()
zoomRateY = sr.readFloat()
rotationStyle = sr.readInt32()
startTransparency = sr.readFloat()
startPosition = sr.readFloat()
endTransparency = sr.readFloat()
endPosition = sr.readFloat()
offsetDirection = sr.readFloat()
}
}
}
/**
* 개체 요소 [HWPShapeComponent]를 읽는 함수
* Tag ID: [SHAPE_COMPONENT]
*
* @author accforaus
*
* @param [gsoControl] [HWPGsoControl], 개체 컨트롤 헤더 객체
* @param [sr] [StreamReader], 스트림 리더 객체
*/
internal fun forShapeComponent(gsoControl: HWPGsoControl, sr: StreamReader) {
/**
* matrix [HWPMatrix]를 읽는 함수
*
* @param [m] [HWPMatrix], 빈 matrix 객체
*/
fun matrix(m: HWPMatrix) {
for (index in 0 until 6)
m.setValue(index, sr.readDouble())
}
/**
* 공통 요소를 읽는 함수
*
* @param [sc] [HWPShapeComponent], 빈 개체 요소 객체
*/
fun commonPart(sc: HWPShapeComponent) {
sc.run {
offsetX = sr.readInt32()
offsetY = sr.readInt32()
groupingCount = sr.readWord()
localFileVersion = sr.readWord()
widthAtCreate = sr.readUInt32()
heightAtCreate = sr.readUInt32()
widthAtCurrent = sr.readUInt32()
heightAtCurrent = sr.readUInt32()
property = sr.readUInt32()
rotateAngle = sr.readUInt16()
rotateXCenter = sr.readInt32()
rotateYCenter = sr.readInt32()
renderingInfo.let {
val scaleRotateMatrixCount: Int = sr.readWord()
matrix(it.translationMatrix)
for (index in 0 until scaleRotateMatrixCount) {
it.addNewScaleRotateMatrixPair().apply {
matrix(this.scaleMatrix)
matrix(this.rotateMatrix)
}
}
}
}
}
/**
* 그리기 개체용 개체 요소 [HWPShapeComponentNormal]를 읽는 함수
*
* @param [scn] [HWPShapeComponentNormal], 그리기 개체용 개체 요소 객체
*/
fun forShapeComponentNormal(scn: HWPShapeComponentNormal) {
scn.run {
commonPart(this)
if (sr.isEndOfRecord()) return
createLineInfo()
lineInfo?.run {
color.value = sr.readColorRef()
thickness = sr.readInt32()
property.value = sr.readUInt32()
outlineStyle = HWPOutlineStyle.valueOf(sr.readByte().toByte())
}
if (sr.isEndOfRecord()) return
createFillInfo()
forFillInfo(fillInfo!!, sr)
if (sr.isEndOfRecord()) return
createShadowInfo()
shadowInfo?.run {
type = HWPShadowType.valueOf(sr.readUInt32().toByte())
color.value = sr.readColorRef()
offsetX = sr.readInt32()
offsetY = sr.readInt32()
sr.skip(5)
transparent = sr.readUInt8()
}
}
}
/**
* 컨테이너 개체용 요소 [HWPShapeComponentContainer]를 읽는 함수
*
* @param [scc] [HWPShapeComponentContainer], 빈 컨테이녀 개체 요소 객체
*/
fun forShapeComponentContainer(scc: HWPShapeComponentContainer) {
commonPart(scc)
val count: Int = sr.readUInt16()
for (index in 0 until count)
scc.addChildControlId(sr.readUInt32())
sr.skip(4)
}
if (gsoControl.getGsoType() != HWPGsoControlType.Container) {
forShapeComponentNormal(gsoControl.shapeComponent as HWPShapeComponentNormal)
} else
forShapeComponentContainer(gsoControl.shapeComponent as HWPShapeComponentContainer)
}
/**
* 그리기 개체 글상자용 텍스트 속성 [HWPTextBox]을 읽는 함수
*
* @author accforaus
*
* @param [textBox] [HWPTextBox], 글상자 객체
* @param [sr] [StreamReader], 스트림 리더 객체
*/
internal fun forTextBox(textBox: HWPTextBox, sr: StreamReader, docInfo: HWPDocInfo) {
/**
* 문단 리스트를 읽는 함수
*/
fun forParagraph() {
forParagraphList(textBox.paragraphList, sr, docInfo)
}
textBox.listHeader.run {
paraCount = sr.readInt32()
property.value = sr.readUInt32()
leftMargin = sr.readUInt16()
rightMargin = sr.readUInt16()
topMargin = sr.readUInt16()
bottomMargin = sr.readUInt16()
textWidth = sr.readHwpUnit()
if (sr.isEndOfRecord()) {
forParagraph()
return
}
sr.skip(8)
if (!sr.isEndOfRecord()) {
val temp: Int = sr.readInt32()
val check = fun (value: Int): Boolean = value == 1
editableAtFormMode = check(temp)
if (sr.readUInt8() == 0xff.toShort()) {
val ps: HWPParameterSet = HWPParameterSet()
ForParameterSet.read(ps, sr)
if (ps.id == 0x21b) {
for (pi in ps.parameterItemList)
if (pi.id == 0x4000.toLong() && pi.type == HWPParameterType.String)
fieldName = pi.value_BSTR
}
}
}
}
forParagraph()
}
| 1 | null |
7
| 22 |
b828271f12a885dece5af5aa6281a1b2cf84d459
| 10,516 |
libhwp
|
Apache License 2.0
|
app/src/main/java/com/akoufatzis/weatherappclean/search/model/CityWeatherModel.kt
|
ra-jeev
| 111,646,630 | true |
{"Kotlin": 30144, "Java": 1563}
|
package com.akoufatzis.weatherappclean.search.model
import com.akoufatzis.weatherappclean.domain.models.City
import com.akoufatzis.weatherappclean.domain.models.Weather
/**
* The M from the MVP. This is the class that should, if required implement Parceable
*/
data class CityWeatherModel(val weather: Weather, val temp: Double, val city: City)
| 0 |
Kotlin
|
0
| 0 |
05e7bf23a95b66b48f65828f88b4ee6c0ad35dc7
| 348 |
WeatherAppClean
|
Apache License 2.0
|
src/main/kotlin/com/example/demo/api/realestate/handler/brokers/crud/update/request.kt
|
bastman
| 98,087,438 | false | null |
package com.example.demo.api.realestate.handler.brokers.crud.update
import com.example.demo.api.common.validation.annotations.EmailOrNull
import com.example.demo.api.common.validation.annotations.NotBlankOrNull
import io.swagger.annotations.ApiModel
import javax.validation.Valid
data class UpdateBrokerRequest(
@get: [EmailOrNull] val email: String?,
val companyName: String?,
val firstName: String?,
val lastName: String?,
val phoneNumber: String?,
val comment: String?,
@get: [Valid] val address: UpdateBrokerAddress?
) {
@ApiModel("UpdateBrokerRequest.BrokerAddress")
data class UpdateBrokerAddress(
@get: [NotBlankOrNull] val country: String?,
@get: [NotBlankOrNull] val city: String?,
val state: String?,
val street: String?,
val number: String?
)
}
| 0 |
Kotlin
|
5
| 8 |
cde355a9ebb110fa76abb5183b935d6b76c99348
| 885 |
kotlin-spring-jpa-examples
|
MIT License
|
sample/src/main/java/com/github/panpf/assemblyadapter/sample/item/LoadStateItemFactory.kt
|
panpf
| 42,781,599 | false | null |
/*
* Copyright (C) 2021 panpf <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.assemblyadapter.sample.item
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.paging.LoadState
import com.github.panpf.assemblyadapter.BindingItemFactory
import com.github.panpf.assemblyadapter.sample.databinding.ItemLoadStateBinding
class LoadStateItemFactory(private val activity: Activity) :
BindingItemFactory<LoadState, ItemLoadStateBinding>(LoadState::class) {
override fun createItemViewBinding(
context: Context, inflater: LayoutInflater, parent: ViewGroup
): ItemLoadStateBinding = ItemLoadStateBinding.inflate(inflater, parent, false)
override fun initItem(
context: Context,
binding: ItemLoadStateBinding,
item: BindingItem<LoadState, ItemLoadStateBinding>
) {
binding.root.setOnLongClickListener {
AlertDialog.Builder(activity).apply {
setMessage(buildString {
append("LoadState").appendLine()
appendLine()
append("bindingAdapterPosition: ${item.bindingAdapterPosition}").appendLine()
append("absoluteAdapterPosition: ${item.absoluteAdapterPosition}").appendLine()
})
}.show()
true
}
}
override fun bindItemData(
context: Context,
binding: ItemLoadStateBinding,
item: BindingItem<LoadState, ItemLoadStateBinding>,
bindingAdapterPosition: Int,
absoluteAdapterPosition: Int,
data: LoadState
) {
binding.loadStateItemLoadingLayout.isVisible = data is LoadState.Loading
binding.loadStateItemErrorText.isVisible = data is LoadState.Error
binding.loadStateItemEndText.isVisible =
data is LoadState.NotLoading && data.endOfPaginationReached
}
}
| 0 |
Kotlin
|
33
| 169 |
00cf02eb1b2be82685a2997d5473579246e256c8
| 2,562 |
assembly-adapter
|
Apache License 2.0
|
src/main/kotlin/com/haulmont/petclinic/owner/Pet.kt
|
JetBrains
| 357,083,866 | false |
{"Kotlin": 11506}
|
package com.haulmont.petclinic.owner
import com.haulmont.petclinic.model.NamedEntity
import com.haulmont.petclinic.visit.Visit
import org.springframework.format.annotation.DateTimeFormat
import java.time.LocalDate
import javax.persistence.*
@Table(name = "pets")
@Entity
class Pet : NamedEntity() {
@Column(name = "birth_date")
@DateTimeFormat(pattern = "yyyy-MM-dd")
var birthDate: LocalDate? = null
@JoinColumn(name = "type_id")
@ManyToOne
var type: PetType? = null
@JoinColumn(name = "owner_id")
@ManyToOne
var owner: Owner? = null
@Transient
var visits = mutableSetOf<Visit>()
fun addVisit(visit: Visit) {
visits.add(visit)
visit.petId = id
}
}
| 0 |
Kotlin
|
2
| 1 |
190b34e4bede3ae25f237bd799c5f3e9b28a894b
| 723 |
jpa-buddy-petclinic-flyway-kt
|
Apache License 2.0
|
screen/categories/src/main/java/ru/maksonic/rdpodcast/screen/categories/CategoryDomainToUiMapper.kt
|
maksonic
| 455,857,524 | false | null |
package ru.maksonic.rdpodcast.screen.categories
import ru.maksonic.rdpodcast.core.Mapper
import ru.maksonic.rdpodcast.domain.categories.CategoryDomain
import ru.maksonic.rdpodcast.shared.ui_model.CategoryUi
import javax.inject.Inject
/**
* @Author: maksonic on 07.02.2022
*/
class CategoryDomainToUiMapper @Inject constructor() : Mapper<CategoryDomain, CategoryUi> {
override fun from(i: CategoryDomain): CategoryUi =
CategoryUi(
id = i.id,
categoryId = i.categoryId,
name = i.name,
description = i.description,
image = i.image
)
override fun to(o: CategoryUi) =
CategoryDomain(
id = o.id,
categoryId = o.categoryId,
name = o.name,
description = o.description,
image = o.image
)
}
| 0 |
Kotlin
|
0
| 0 |
60db23bf1f7ee9f6f8cc4a1c766b7afa44e20775
| 845 |
RDPodcast
|
MIT License
|
src/test/kotlin/com/bukowiecki/weevil/generated/FactorialGeneratedTest.kt
|
marcin-bukowiecki
| 401,079,122 | false | null |
package com.bukowiecki.weevil.generated
import com.bukowiecki.weevil.GeneratedTestRunner
import org.junit.Test
/**
* GENERATED TEST
*
* @author <NAME>
*/
class FactorialGeneratedTest : GeneratedTestRunner() {
@Test
fun factorial1() {
runTest("generated/factorial/factorial1.java")
}
@Test
fun factorial2() {
runTest("generated/factorial/factorial2.java")
}
}
| 0 |
Kotlin
|
1
| 3 |
1461169f0e1cbf3e4006b71fff9a97b271f43231
| 440 |
weevil-debugger-plugin
|
Apache License 2.0
|
xsolla-login-sdk/src/main/java/com/xsolla/android/login/callback/LinkDeviceToAccountCallback.kt
|
xsolla
| 233,092,015 | false | null |
package com.xsolla.android.login.callback
interface LinkDeviceToAccountCallback {
fun onSuccess()
fun onError(throwable: Throwable?, errorMessage: String?)
}
| 1 |
Kotlin
|
5
| 9 |
cf3861e571f3ebc45490d39c40b0f2698e835b2f
| 166 |
store-android-sdk
|
Apache License 2.0
|
common/src/commonMain/kotlin/com/github/mustafaozhan/ccc/common/fake/FakeDriver.kt
|
CurrencyConverterCalculator
| 102,633,334 | false | null |
/*
* Copyright (c) 2020 <NAME>. All rights reserved.
*/
package com.github.mustafaozhan.ccc.common.fake
import com.squareup.sqldelight.Transacter
import com.squareup.sqldelight.db.SqlCursor
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.db.SqlPreparedStatement
object FakeDriver : SqlDriver {
fun getDriver(): SqlDriver = this
override fun close() = Unit
override fun currentTransaction(): Transacter.Transaction? {
TODO("Fake method Not yet implemented")
}
override fun execute(
identifier: Int?,
sql: String,
parameters: Int,
binders: (SqlPreparedStatement.() -> Unit)?
) = Unit
override fun executeQuery(
identifier: Int?,
sql: String,
parameters: Int,
binders: (SqlPreparedStatement.() -> Unit)?
): SqlCursor = FakeSqlCursor.getSqlCursor()
override fun newTransaction(): Transacter.Transaction {
TODO("Fake method Not yet implemented")
}
}
| 13 |
Kotlin
|
19
| 146 |
ef668bc3e90cf305b9090e1d0fa53bd602d91bfc
| 1,001 |
CCC
|
Apache License 2.0
|
compiler/fir/entrypoint/src/org/jetbrains/kotlin/fir/session/FirSessionFactory.kt
|
geralt-encore
| 177,396,019 | false |
{"Markdown": 134, "Gradle": 436, "Gradle Kotlin DSL": 690, "Java Properties": 18, "Kotlin": 43823, "Shell": 47, "Ignore List": 22, "Batchfile": 24, "Git Attributes": 9, "INI": 170, "Java": 2952, "XML": 672, "Text": 14507, "JavaScript": 323, "JAR Manifest": 2, "Roff": 246, "Roff Manpage": 45, "Protocol Buffer": 15, "Proguard": 14, "AsciiDoc": 1, "YAML": 9, "EditorConfig": 1, "OpenStep Property List": 11, "JSON": 187, "C": 159, "Objective-C": 80, "C++": 280, "LLVM": 1, "Swift": 75, "Pascal": 1, "Python": 5, "CMake": 3, "Objective-C++": 17, "HTML": 17, "Groovy": 20, "Dockerfile": 4, "Diff": 6, "EJS": 1, "CSS": 6, "JSON with Comments": 24, "JFlex": 2, "Ant Build System": 53, "Dotenv": 5, "Graphviz (DOT)": 88, "Maven POM": 80, "Ruby": 5, "Scala": 1}
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.session
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.checkers.registerJvmCheckers
import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
import org.jetbrains.kotlin.fir.deserialization.SingleModuleDataProvider
import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar
import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider
import org.jetbrains.kotlin.fir.java.JavaSymbolProvider
import org.jetbrains.kotlin.fir.java.deserialization.JvmClassFileBasedSymbolProvider
import org.jetbrains.kotlin.fir.java.deserialization.OptionalAnnotationClassesProvider
import org.jetbrains.kotlin.fir.resolve.providers.impl.FirBuiltinSymbolProvider
import org.jetbrains.kotlin.fir.resolve.providers.impl.FirCloneableSymbolProvider
import org.jetbrains.kotlin.fir.resolve.providers.impl.FirDependenciesSymbolProviderImpl
import org.jetbrains.kotlin.fir.resolve.scopes.wrapScopeWithJvmMapped
import org.jetbrains.kotlin.fir.scopes.FirKotlinScopeProvider
import org.jetbrains.kotlin.fir.session.environment.AbstractProjectEnvironment
import org.jetbrains.kotlin.fir.session.environment.AbstractProjectFileSearchScope
import org.jetbrains.kotlin.incremental.components.EnumWhenTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.kotlin.PackagePartProvider
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
@OptIn(PrivateSessionConstructor::class)
object FirSessionFactory : FirAbstractSessionFactory() {
inline fun createSessionWithDependencies(
moduleName: Name,
platform: TargetPlatform,
analyzerServices: PlatformDependentAnalyzerServices,
externalSessionProvider: FirProjectSessionProvider?,
projectEnvironment: AbstractProjectEnvironment,
languageVersionSettings: LanguageVersionSettings,
javaSourcesScope: AbstractProjectFileSearchScope,
librariesScope: AbstractProjectFileSearchScope,
lookupTracker: LookupTracker?,
enumWhenTracker: EnumWhenTracker?,
incrementalCompilationContext: IncrementalCompilationContext?,
extensionRegistrars: List<FirExtensionRegistrar>,
needRegisterJavaElementFinder: Boolean,
dependenciesConfigurator: DependencyListForCliModule.Builder.() -> Unit = {},
noinline sessionConfigurator: FirSessionConfigurator.() -> Unit = {},
): FirSession {
val dependencyList = DependencyListForCliModule.build(moduleName, platform, analyzerServices, dependenciesConfigurator)
val sessionProvider = externalSessionProvider ?: FirProjectSessionProvider()
val packagePartProvider = projectEnvironment.getPackagePartProvider(librariesScope)
createLibrarySession(
moduleName,
sessionProvider,
dependencyList,
projectEnvironment,
librariesScope,
packagePartProvider,
languageVersionSettings
)
val mainModuleData = FirModuleDataImpl(
moduleName,
dependencyList.regularDependencies,
dependencyList.dependsOnDependencies,
dependencyList.friendsDependencies,
dependencyList.platform,
dependencyList.analyzerServices
)
return createModuleBasedSession(
mainModuleData,
sessionProvider,
javaSourcesScope,
projectEnvironment,
incrementalCompilationContext,
extensionRegistrars,
languageVersionSettings,
lookupTracker,
enumWhenTracker,
needRegisterJavaElementFinder,
sessionConfigurator
)
}
fun createLibrarySession(
mainModuleName: Name,
sessionProvider: FirProjectSessionProvider,
dependencyList: DependencyListForCliModule,
projectEnvironment: AbstractProjectEnvironment,
scope: AbstractProjectFileSearchScope,
packagePartProvider: PackagePartProvider,
languageVersionSettings: LanguageVersionSettings,
): FirSession {
return createLibrarySession(
mainModuleName,
sessionProvider,
dependencyList.moduleDataProvider,
languageVersionSettings,
registerExtraComponents = { it.registerCommonJavaComponents(projectEnvironment.getJavaModuleResolver()) },
createKotlinScopeProvider = { FirKotlinScopeProvider(::wrapScopeWithJvmMapped) },
createProviders = { session, builtinsModuleData, kotlinScopeProvider ->
listOf(
JvmClassFileBasedSymbolProvider(
session,
dependencyList.moduleDataProvider,
kotlinScopeProvider,
packagePartProvider,
projectEnvironment.getKotlinClassFinder(scope),
projectEnvironment.getFirJavaFacade(session, dependencyList.moduleDataProvider.allModuleData.last(), scope)
),
FirBuiltinSymbolProvider(session, builtinsModuleData, kotlinScopeProvider),
FirCloneableSymbolProvider(session, builtinsModuleData, kotlinScopeProvider),
FirDependenciesSymbolProviderImpl(session),
OptionalAnnotationClassesProvider(session, dependencyList.moduleDataProvider, kotlinScopeProvider, packagePartProvider)
)
}
)
}
@OptIn(SessionConfiguration::class)
fun createModuleBasedSession(
moduleData: FirModuleData,
sessionProvider: FirProjectSessionProvider,
javaSourcesScope: AbstractProjectFileSearchScope,
projectEnvironment: AbstractProjectEnvironment,
incrementalCompilationContext: IncrementalCompilationContext?,
extensionRegistrars: List<FirExtensionRegistrar>,
languageVersionSettings: LanguageVersionSettings = LanguageVersionSettingsImpl.DEFAULT,
lookupTracker: LookupTracker? = null,
enumWhenTracker: EnumWhenTracker? = null,
needRegisterJavaElementFinder: Boolean,
init: FirSessionConfigurator.() -> Unit = {}
): FirSession {
return createModuleBasedSession(
moduleData,
sessionProvider,
extensionRegistrars,
languageVersionSettings,
lookupTracker,
enumWhenTracker,
init,
registerExtraComponents = {
it.registerCommonJavaComponents(projectEnvironment.getJavaModuleResolver())
it.registerJavaSpecificResolveComponents()
},
registerExtraCheckers = { it.registerJvmCheckers() },
createKotlinScopeProvider = { FirKotlinScopeProvider(::wrapScopeWithJvmMapped) },
createProviders = { session, kotlinScopeProvider, symbolProvider, generatedSymbolsProvider, dependenciesSymbolProvider ->
var symbolProviderForBinariesFromIncrementalCompilation: JvmClassFileBasedSymbolProvider? = null
var optionalAnnotationClassesProviderForBinariesFromIncrementalCompilation: OptionalAnnotationClassesProvider? = null
incrementalCompilationContext?.let {
if (it.precompiledBinariesPackagePartProvider != null && it.precompiledBinariesFileScope != null) {
val moduleDataProvider = SingleModuleDataProvider(moduleData)
symbolProviderForBinariesFromIncrementalCompilation =
JvmClassFileBasedSymbolProvider(
session,
moduleDataProvider,
kotlinScopeProvider,
it.precompiledBinariesPackagePartProvider,
projectEnvironment.getKotlinClassFinder(it.precompiledBinariesFileScope),
projectEnvironment.getFirJavaFacade(session, moduleData, it.precompiledBinariesFileScope),
defaultDeserializationOrigin = FirDeclarationOrigin.Precompiled
)
optionalAnnotationClassesProviderForBinariesFromIncrementalCompilation =
OptionalAnnotationClassesProvider(
session,
moduleDataProvider,
kotlinScopeProvider,
it.precompiledBinariesPackagePartProvider,
defaultDeserializationOrigin = FirDeclarationOrigin.Precompiled
)
}
}
val javaSymbolProvider = JavaSymbolProvider(session, projectEnvironment.getFirJavaFacade(session, moduleData, javaSourcesScope))
session.register(JavaSymbolProvider::class, javaSymbolProvider)
listOfNotNull(
symbolProvider,
*(incrementalCompilationContext?.previousFirSessionsSymbolProviders?.toTypedArray() ?: emptyArray()),
symbolProviderForBinariesFromIncrementalCompilation,
generatedSymbolsProvider,
javaSymbolProvider,
dependenciesSymbolProvider,
optionalAnnotationClassesProviderForBinariesFromIncrementalCompilation,
)
}
).also {
if (needRegisterJavaElementFinder) {
projectEnvironment.registerAsJavaElementFinder(it)
}
}
}
@OptIn(SessionConfiguration::class)
@TestOnly
fun createEmptySession(): FirSession {
return object : FirSession(null, Kind.Source) {}.apply {
val moduleData = FirModuleDataImpl(
Name.identifier("<stub module>"),
dependencies = emptyList(),
dependsOnDependencies = emptyList(),
friendDependencies = emptyList(),
platform = JvmPlatforms.unspecifiedJvmPlatform,
analyzerServices = JvmPlatformAnalyzerServices
)
registerModuleData(moduleData)
moduleData.bindSession(this)
// Empty stub for tests
register(FirLanguageSettingsComponent::class, FirLanguageSettingsComponent(
object : LanguageVersionSettings {
private fun stub(): Nothing = TODO(
"It does not yet have well-defined semantics for tests." +
"If you're seeing this, implement it in a test-specific way"
)
override fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State {
return LanguageFeature.State.DISABLED
}
override fun isPreRelease(): Boolean = stub()
override fun <T> getFlag(flag: AnalysisFlag<T>): T = stub()
override val apiVersion: ApiVersion
get() = stub()
override val languageVersion: LanguageVersion
get() = stub()
}
))
}
}
}
| 1 | null |
1
| 1 |
f07163125b2f0cd0c67486c77d0444a0d8b7c8d2
| 11,819 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/org/teamvoided/dusk_autumn/effect/MadnessEffect.kt
|
TeamVoided
| 737,359,498 | false |
{"Kotlin": 1129694, "Java": 28224}
|
package org.teamvoided.dusk_autumn.effect
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.attribute.AttributeContainer
import net.minecraft.entity.effect.StatusEffectInstance
import net.minecraft.entity.effect.StatusEffectType
import net.minecraft.entity.effect.StatusEffects
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.particle.ParticleEffect
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.server.world.ServerWorld
import net.minecraft.world.Difficulty
import org.teamvoided.dusk_autumn.util.pi
import kotlin.math.cos
class MadnessEffect : DnDStatusEffect {
constructor(type: StatusEffectType, color: Int) : super(type, color)
constructor(type: StatusEffectType, color: Int, particle: ParticleEffect) : super(type, color, particle)
override fun shouldApplyUpdateEffect(tick: Int, amplifier: Int): Boolean = true
override fun applyUpdateEffect(entity: LivingEntity, amplifier: Int): Boolean {
return true
}
}
| 0 |
Kotlin
|
0
| 0 |
7df0896ea35a8f1c3a2676821629ff16de72d95e
| 1,016 |
DusksAndDungeons
|
MIT License
|
planner/src/main/java/com/bibek/planner/presentation/ui/recipe_alarm_details_screen/RecipeAlarmDetailsEvent.kt
|
bibekanandan892
| 820,073,061 | false |
{"Kotlin": 148771}
|
package com.bibek.planner.presentation.ui.recipe_alarm_details_screen
sealed interface RecipeAlarmDetailsEvent {
data class GetRecipeAlarm(val recipeId: String) : RecipeAlarmDetailsEvent
data object NavigateBack : RecipeAlarmDetailsEvent
}
| 0 |
Kotlin
|
0
| 0 |
5844da2f6c85cdff4f5e2d226dc94463a8fc66de
| 249 |
Recipe-Database
|
Apache License 2.0
|
app/src/main/java/com/example/littlelemon/NavigationComposable.kt
|
Mwirigi-Carson
| 735,228,601 | false |
{"Kotlin": 18202}
|
package com.example.littlelemon
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
@Composable
fun Navigation( navController: NavController) {
val sharedPreferences = LocalContext.current.getSharedPreferences("Little Lemon", Context.MODE_PRIVATE)
NavHost(navController = navController as NavHostController, startDestination = if (sharedPreferences.getBoolean("userRegistered", true)){Destinations.OnBoarding.route} else Destinations.Home.route){
composable(Destinations.OnBoarding.route){
OnBoardingScreen(navController)
}
composable(Destinations.Home.route){
HomeScreen(navController)
}
composable(Destinations.Profile.route){
ProfileScreen(navController)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
1daf16942d696ff469e333e072bc96db5ece1c8f
| 1,012 |
Little-Lemon
|
MIT License
|
backend/src/main/kotlin/cz/loono/backend/schedule/SelfExaminationIntervalClosingTask.kt
|
cesko-digital
| 375,482,501 | false | null |
package cz.loono.backend.schedule
import cz.loono.backend.api.dto.SelfExaminationStatusDto
import cz.loono.backend.db.model.SelfExaminationRecord
import cz.loono.backend.db.repository.SelfExaminationRecordRepository
import org.springframework.stereotype.Component
import java.time.LocalDate
@Component
class SelfExaminationIntervalClosingTask(
private val selfExaminationRecordRepository: SelfExaminationRecordRepository
) : SchedulerTask {
override fun run() {
val now = LocalDate.now()
selfExaminationRecordRepository.findAllByStatus(SelfExaminationStatusDto.PLANNED).forEach {
if (it.dueDate?.isAfter(now) == true) {
selfExaminationRecordRepository.save(it.copy(status = SelfExaminationStatusDto.MISSED))
selfExaminationRecordRepository.save(
SelfExaminationRecord(
type = it.type,
status = SelfExaminationStatusDto.PLANNED,
account = it.account,
dueDate = it.dueDate.plusMonths(1)
)
)
}
}
}
}
| 0 |
Kotlin
|
4
| 0 |
2bd0e8fb4ae9181be68efcc03ec1243ba73264b6
| 1,144 |
loono-be
|
MIT License
|
idea/testData/refactoring/move/java/moveClass/moveTopToInner/moveTopLevelClassToNestedClass/after/noImports.kt
|
JakeWharton
| 99,388,807 | false | null |
fun bar() {
val t: B.C.A = B.C.A()
}
| 0 | null |
28
| 83 |
4383335168338df9bbbe2a63cb213a68d0858104
| 40 |
kotlin
|
Apache License 2.0
|
app/src/main/java/com/kasuminotes/action/ExEquipPassive.kt
|
chilbi
| 399,723,451 | false |
{"Kotlin": 869410}
|
package com.kasuminotes.action
import com.kasuminotes.R
import com.kasuminotes.data.SkillAction
fun SkillAction.getExEquipPassive(): D {
return when (actionDetail1) {
7 -> {
D.Format(
R.string.action_passive_battle_remaining_time1,
arrayOf(D.Text(actionValue3.toNumStr()))
)
}
else -> D.Format(R.string.action_passive_battle_beginning)
}
}
| 0 |
Kotlin
|
0
| 1 |
a3de288c5030cfb062abbbe7ec574ad59ccec1bf
| 430 |
KasumiNotes
|
Apache License 2.0
|
app/src/main/java/com/kasuminotes/action/ExEquipPassive.kt
|
chilbi
| 399,723,451 | false |
{"Kotlin": 869410}
|
package com.kasuminotes.action
import com.kasuminotes.R
import com.kasuminotes.data.SkillAction
fun SkillAction.getExEquipPassive(): D {
return when (actionDetail1) {
7 -> {
D.Format(
R.string.action_passive_battle_remaining_time1,
arrayOf(D.Text(actionValue3.toNumStr()))
)
}
else -> D.Format(R.string.action_passive_battle_beginning)
}
}
| 0 |
Kotlin
|
0
| 1 |
a3de288c5030cfb062abbbe7ec574ad59ccec1bf
| 430 |
KasumiNotes
|
Apache License 2.0
|
domain/src/main/java/com/wo1f/domain/repository/ExploreRepository.kt
|
adwardwolf
| 387,865,580 | false | null |
package com.wo1f.domain.repository
import com.wo1f.base.DataResource
import com.wo1f.domain.model.ExploreData
interface ExploreRepository {
suspend fun getExploreData(): DataResource<ExploreData>
suspend fun insertExploreData(exploreData: ExploreData)
}
| 0 |
Kotlin
|
0
| 2 |
ed8b079141dff5a6652ca2f811487d7cd5241c59
| 266 |
the-earth
|
Apache License 2.0
|
src/test/kotlin/no/nav/syfo/helsepersonell/PingApiTest.kt
|
navikt
| 198,372,403 | false |
{"Kotlin": 82833, "Dockerfile": 276}
|
package no.nav.syfo.helsepersonell
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.routing.routing
import io.ktor.server.testing.TestApplicationEngine
import io.ktor.server.testing.handleRequest
import io.ktor.util.*
import io.mockk.every
import io.mockk.mockk
import no.nav.syfo.helsepersonell.redis.HelsepersonellRedis
import no.nav.syfo.utils.setUpTestApplication
import no.nhn.schemas.reg.hprv2.IHPR2Service
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class PingApiTest {
val wsMock = mockk<IHPR2Service>()
val redis = mockk<HelsepersonellRedis>()
val helsePersonService = HelsepersonellService(wsMock, redis)
@BeforeAll
internal fun setup() {
every { wsMock.ping("1") } returns "pong"
every { wsMock.ping("2") } returns null
every { redis.getFromHpr(any()) } returns null
every { redis.getFromFnr(any()) } returns null
every { redis.save(any(), any()) } returns Unit
}
@InternalAPI
@Test
internal fun `Gets pong in responsee`() {
with(TestApplicationEngine()) {
setUpTestApplication()
application.routing { registerPingApi(helsePersonService) }
with(handleRequest(HttpMethod.Get, "/ping") { addHeader("requestId", "1") }) {
response.status()?.shouldBeEqualTo(io.ktor.http.HttpStatusCode.OK)
val pingResponse = response.content!!
pingResponse.shouldBeEqualTo("pong")
}
}
}
@InternalAPI
@Test
internal fun `Gets null in response`() {
with(TestApplicationEngine()) {
setUpTestApplication()
application.routing { registerPingApi(helsePersonService) }
with(handleRequest(HttpMethod.Get, "/ping") { addHeader("requestId", "2") }) {
response.status()?.shouldBeEqualTo(HttpStatusCode.InternalServerError)
val error: String = response.content!!
error.shouldBeEqualTo("Ping svarte ikkje")
}
}
}
@InternalAPI
@Test
internal fun `Should return BadRequest when requestId header is missing`() {
with(TestApplicationEngine()) {
setUpTestApplication()
application.routing { registerPingApi(helsePersonService) }
with(handleRequest(HttpMethod.Get, "/ping") {}) {
response.status()?.shouldBeEqualTo(HttpStatusCode.BadRequest)
val error: String = response.content!!
error shouldBeEqualTo "Mangler header `requestId`"
}
}
}
}
| 1 |
Kotlin
|
2
| 0 |
f34b662fe1ff25c8fe1a7a1fa0d53cdb46cd6690
| 2,777 |
syfohelsenettproxy
|
MIT License
|
revue-lib/src/test/kotlin/com/github/dmchoull/revue/util/DialogResultPromiseTest.kt
|
dmchoull
| 116,846,741 | false | null |
/*
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.dmchoull.revue.util
import com.github.dmchoull.revue.builder.DialogResult
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
internal class DialogResultPromiseTest {
private lateinit var positiveCallback: () -> Unit
private lateinit var negativeCallback: () -> Unit
private lateinit var neutralCallback: () -> Unit
private lateinit var promise: DialogResultPromise
@BeforeEach
fun setUp() {
positiveCallback = mock()
negativeCallback = mock()
neutralCallback = mock()
promise = DialogResultPromise()
promise.onPositive(positiveCallback)
promise.onNegative(negativeCallback)
promise.onNeutral(neutralCallback)
}
@Test
@DisplayName("calls positive callback when resolved with a positive result")
fun onPositive() {
promise.resolve(DialogResult.POSITIVE)
verify(positiveCallback).invoke()
verify(negativeCallback, never()).invoke()
verify(neutralCallback, never()).invoke()
}
@Test
@DisplayName("calls negative callback when resolved with a negative result")
fun onNegative() {
promise.resolve(DialogResult.NEGATIVE)
verify(positiveCallback, never()).invoke()
verify(negativeCallback).invoke()
verify(neutralCallback, never()).invoke()
}
@Test
@DisplayName("calls neutral callback when resolved with a neutral result")
fun onNeutral() {
promise.resolve(DialogResult.NEUTRAL)
verify(positiveCallback, never()).invoke()
verify(negativeCallback, never()).invoke()
verify(neutralCallback).invoke()
}
@Test
@DisplayName("does not attempt to call null callbacks")
fun nullCallbacks() {
val promise = DialogResultPromise()
promise.resolve(DialogResult.POSITIVE)
promise.resolve(DialogResult.NEGATIVE)
promise.resolve(DialogResult.NEUTRAL)
}
}
| 0 |
Kotlin
|
0
| 0 |
45d00a3f366b2a0c8200168538efbdb9066e2193
| 3,256 |
revue
|
MIT License
|
flank-scripts/src/main/kotlin/flank/scripts/cli/linter/ApplyToIdeCommand.kt
|
Flank
| 84,221,974 | false |
{"Kotlin": 1748173, "Java": 101254, "Swift": 41229, "Shell": 10674, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1183, "EJS": 1061, "Go": 159}
|
package flank.scripts.cli.linter
import com.github.ajalt.clikt.core.CliktCommand
import flank.scripts.ops.linter.applyKtlintToIdea
import kotlinx.coroutines.runBlocking
object ApplyToIdeCommand : CliktCommand(
name = "apply_to_ide",
help = "Apply Linter to IDE"
) {
override fun run(): Unit = runBlocking {
applyKtlintToIdea()
}
}
| 64 |
Kotlin
|
115
| 676 |
b40904b4e74a670cf72ee53dc666fc3a801e7a95
| 357 |
flank
|
Apache License 2.0
|
app/src/main/java/com/samokpe/gads2020/remote/RemoteDataSourceImpl.kt
|
samokpe2
| 294,919,064 | false | null |
package com.samokpe.gads2020.remote
import com.samokpe.gads2020.models.LearningLeader
import com.samokpe.gads2020.models.Resource
import com.samokpe.gads2020.models.SkillIQLeader
import timber.log.Timber
import javax.inject.Inject
class RemoteDataSourceImpl @Inject constructor(private val apiService: ApiService): RemoteDataSource {
override suspend fun getTopLearningLeaders(): Resource<List<LearningLeader>> =
try {
val result = apiService.getTopLearningLeaders()
Resource.Success(result)
}
catch (error: Throwable){
Timber.d(error.message.toString())
Resource.Error("Server error encountered!")
}
override suspend fun getTopIQLeaders(): Resource<List<SkillIQLeader>> =
try {
val result = apiService.getTopIQLeaders()
Resource.Success(result.body()!!)
}
catch (error: Throwable){
Timber.d(error.message.toString())
Resource.Error("Server error encountered!")
}
override suspend fun submitProject(
firstName: String,
lastName: String,
emailAddress: String,
projectLink: String
): Resource<Int> =
try {
val result = apiService.submitProject(
firstName = firstName, lastName = lastName,
emailAddress = emailAddress, projectLink = projectLink
).code()
Timber.d(result.toString())
if (result == 200){
Resource.Success(result)
}
else {
Timber.d(result.toString())
Resource.Error("Submission not successful", null)
}
}
catch (error: Throwable){
Resource.Error(error.message.toString(), null)
}
}
| 0 |
Kotlin
|
0
| 1 |
80cba50f6ec30250e861f9388e466d78d7c3d546
| 1,810 |
GADS-AAD-2020-PRACTICE
|
MIT License
|
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/presentation/common/rewardDestination/RewardDestinationMixin.kt
|
novasamatech
| 415,834,480 | false |
{"Kotlin": 7667438, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_staking_impl.presentation.common.rewardDestination
import androidx.lifecycle.LiveData
import io.novafoundation.nova.common.address.AddressModel
import io.novafoundation.nova.common.mixin.api.Browserable
import io.novafoundation.nova.common.utils.Event
import io.novafoundation.nova.common.utils.invoke
import io.novafoundation.nova.common.view.bottomSheet.list.dynamic.DynamicListBottomSheet
import io.novafoundation.nova.feature_staking_api.domain.model.relaychain.StakingState
import io.novafoundation.nova.feature_staking_impl.domain.rewards.RewardCalculator
import io.novafoundation.nova.feature_wallet_api.domain.model.Asset
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.amountChooser.AmountChooserMixin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import java.math.BigDecimal
interface RewardDestinationMixin : Browserable {
val rewardReturnsLiveData: LiveData<RewardDestinationEstimations>
val showDestinationChooserEvent: LiveData<Event<DynamicListBottomSheet.Payload<AddressModel>>>
val rewardDestinationModelFlow: Flow<RewardDestinationModel>
fun payoutClicked(scope: CoroutineScope)
fun payoutTargetClicked(scope: CoroutineScope)
fun payoutDestinationChanged(newDestination: AddressModel)
fun learnMoreClicked()
fun restakeClicked()
interface Presentation : RewardDestinationMixin {
val rewardDestinationChangedFlow: Flow<Boolean>
suspend fun loadActiveRewardDestination(stashState: StakingState.Stash)
suspend fun updateReturns(
rewardCalculator: RewardCalculator,
asset: Asset,
amount: BigDecimal,
)
}
}
fun RewardDestinationMixin.Presentation.connectWith(
amountChooserMixin: AmountChooserMixin.Presentation,
rewardCalculator: Deferred<RewardCalculator>
) {
amountChooserMixin.usedAssetFlow.combine(amountChooserMixin.amount) { asset, amount ->
updateReturns(rewardCalculator(), asset, amount)
}.launchIn(scope = amountChooserMixin)
}
| 13 |
Kotlin
|
6
| 9 |
dea9f1144c1cbba1d876a9bb753f8541da38ebe0
| 2,203 |
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/astrolucis/features/home/HomeActivity.kt
|
gkravas
| 127,865,201 | false | null |
package com.astrolucis.features.home
import android.content.Intent
import android.content.res.Configuration
import android.databinding.DataBindingUtil
import android.databinding.OnRebindCallback
import android.databinding.ViewDataBinding
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.transition.TransitionManager
import android.view.ViewGroup
import android.widget.Toast
import com.astrolucis.BuildConfig
import com.astrolucis.R
import com.astrolucis.core.BaseActivity
import com.astrolucis.databinding.ActivityHomeBinding
import com.astrolucis.features.dailyPredictionList.DailyPredictionListFragment
import com.astrolucis.features.login.LoginActivity
import com.astrolucis.features.natalDate.NatalDateFragment
import com.astrolucis.features.profile.ProfileFragment
import com.astrolucis.utils.routing.AppRouter
import org.koin.android.architecture.ext.viewModel
import org.koin.android.ext.android.inject
class HomeActivity: BaseActivity() {
companion object {
const val OPEN_NATAL_DATE = "OPEN_NATAL_DATE"
const val BLOG_URL = "https://www.gineastrologos.gr"
const val GOOGLE_PLAY = "https://play.google.com/store/apps/details?id=${BuildConfig.APPLICATION_ID}"
}
private lateinit var drawerToggle: ActionBarDrawerToggle
private lateinit var binding: ActivityHomeBinding
private var doubleBackToExitPressedOnce: Boolean = false
val viewModel : HomeViewModel by viewModel()
val appRouter: AppRouter by inject()
override fun getMasterContainerId(): Int {
return R.id.content_frame
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_home)
setSupportActionBar(binding.toolbar?.toolbar)
binding.viewModel = viewModel
binding.executePendingBindings()
drawerToggle = setupDrawerToggle()
binding.drawerLayout.addDrawerListener(drawerToggle)
binding.addOnRebindCallback(object : OnRebindCallback<ViewDataBinding>() {
override fun onPreBind(binding: ViewDataBinding?): Boolean {
TransitionManager.beginDelayedTransition(binding!!.root as ViewGroup)
return super.onPreBind(binding)
}
})
viewModel.viewState.observeForever( { viewState: HomeViewModel.ViewState? ->
when (viewState) {
HomeViewModel.ViewState.PROFILE -> {
pushFragment(ProfileFragment())
binding.navigation.post({ binding.navigation.setCheckedItem(R.id.profile_menu_item) })
}
HomeViewModel.ViewState.NATAL_DATE -> {
pushFragment(NatalDateFragment())
binding.navigation.post({ binding.navigation.setCheckedItem(R.id.natal_date_menu_item) })
}
HomeViewModel.ViewState.DAILY_PREDICTION_LIST -> {
pushFragment(DailyPredictionListFragment())
binding.navigation.post({ binding.navigation.setCheckedItem(R.id.daily_prediction_menu_item) })
}
HomeViewModel.ViewState.LOGOUT -> {
appRouter.goTo(LoginActivity::class, this)
}
HomeViewModel.ViewState.STAY_THERE -> {
}
}
})
binding.navigation.setNavigationItemSelectedListener({
when (it.itemId) {
R.id.logout_menu_item -> viewModel.logout()
R.id.profile_menu_item -> viewModel.goToProfile()
R.id.natal_date_menu_item -> viewModel.goToNatalDate()
R.id.daily_prediction_menu_item -> viewModel.goToDailyPrediction()
R.id.blog_menu_item -> {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(BLOG_URL))
startActivity(browserIntent)
}
R.id.share_item -> {
val share = Intent(android.content.Intent.ACTION_SEND)
share.type = "text/plain"
share.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
share.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.motto))
share.putExtra(Intent.EXTRA_TEXT, GOOGLE_PLAY)
startActivity(Intent.createChooser(share, resources.getString(R.string.drawer_menu_share)))
}
}
binding.drawerLayout.closeDrawers()
true
})
}
override fun parseState(state: Bundle) {
viewModel.viewState.value = if (state.getBoolean(OPEN_NATAL_DATE, false)) {
HomeViewModel.ViewState.NATAL_DATE
} else {
HomeViewModel.ViewState.DAILY_PREDICTION_LIST
}
}
private fun setupDrawerToggle(): ActionBarDrawerToggle {
return ActionBarDrawerToggle(this, binding.drawerLayout, binding.toolbar?.toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
}
override fun onBackPressed() {
if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
binding.drawerLayout.closeDrawer(GravityCompat.START)
} else {
if (doubleBackToExitPressedOnce) {
moveTaskToBack(true)
return
}
this.doubleBackToExitPressedOnce = true
Toast.makeText(this, R.string.back_again_to_exit, Toast.LENGTH_SHORT).show()
Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
drawerToggle.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
drawerToggle.onConfigurationChanged(newConfig)
}
}
| 0 |
Kotlin
|
0
| 0 |
871933d03934d641b9631abcb662cc656fdcf6cb
| 6,089 |
astrolucis-android
|
MIT License
|
main/java/me/aeolus/servertweaks/modules/disablenaturalspawns/DisableNaturalSpawns.kt
|
MCAeolus
| 235,486,064 | false | null |
package me.aeolus.servertweaks.modules.disablenaturalspawns
import me.aeolus.servertweaks.ServerTweaks
import me.aeolus.servertweaks.modules.Module
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.entity.EntityType
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.CreatureSpawnEvent
import org.bukkit.event.entity.EntitySpawnEvent
import org.bukkit.event.world.ChunkLoadEvent
import org.bukkit.scheduler.BukkitRunnable
import java.util.logging.Level
class DisableNaturalSpawns : Module, Listener {
companion object {
val disabledSpawnReasons = ArrayList<CreatureSpawnEvent.SpawnReason>()
val removeList = ArrayList<Block>()
init {
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.NATURAL)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.VILLAGE_INVASION)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.REINFORCEMENTS)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.BREEDING)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.DISPENSE_EGG)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.EGG)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.SILVERFISH_BLOCK)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.ENDER_PEARL)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.NETHER_PORTAL)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.OCELOT_BABY)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.TRAP)
disabledSpawnReasons.add(CreatureSpawnEvent.SpawnReason.VILLAGE_DEFENSE)
}
}
override fun create() {
ServerTweaks.plugin!!.registerAsListener(this)
Bukkit.getScheduler().scheduleSyncRepeatingTask(ServerTweaks.plugin!!, {
if(removeList.isNotEmpty()) {
ServerTweaks.plugin!!.logger.log(
Level.INFO,
"Disable Natural Spawns is now running through all spawners that need to be deleted. (size = ${removeList.size}"
)
val it = removeList.iterator()
while(it.hasNext()) {
val b = it.next()
b.type = Material.AIR
it.remove()
}
ServerTweaks.plugin!!.logger.log(Level.INFO, "All spawners successfully removed.")
}
}, 100 * 60, 100 * 60)
}
override fun close() {
ServerTweaks.plugin!!.unregisterListener(this)
}
@EventHandler
fun spawnEvent(event : CreatureSpawnEvent) {
if(disabledSpawnReasons.contains(event.spawnReason)) event.isCancelled = true
}
@EventHandler
fun chunkLoadEvent(event : ChunkLoadEvent) {
if(event.isNewChunk) {
event.chunk.entities.forEach {
it.remove()
}
event.chunk.tileEntities.forEach {
if(it.type == Material.SPAWNER) removeList.add(it.block)
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
7be411643fcab1fa5a6319ac48bc6ec5e622fd7e
| 3,171 |
ServerTweaks
|
MIT License
|
spigot/src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/commands/DropRatesCommand.kt
|
MythicDrops
| 10,021,467 | false |
{"Kotlin": 1247884}
|
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 <NAME>
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Dependency
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.Subcommand
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.strategies.DropStrategyManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager
import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicDropTracker
import com.tealcube.minecraft.bukkit.mythicdrops.sendMythicMessage
import org.bukkit.command.CommandSender
import java.math.RoundingMode
import java.text.DecimalFormat
@CommandAlias("mythicdrops|md")
internal class DropRatesCommand : BaseCommand() {
companion object {
private val decimalFormat = DecimalFormat("###.###%").apply { RoundingMode.CEILING }
}
@field:Dependency
lateinit var dropStrategyManager: DropStrategyManager
@field:Dependency
lateinit var settingsManager: SettingsManager
@Description("Prints a list of the calculated drop rate and the real drop rate being experienced")
@Subcommand("rates")
@CommandPermission("mythicdrops.command.rates")
fun debugCommand(sender: CommandSender) {
sender.sendMythicMessage("&6=== MythicDrops Drop Rates ===")
sender.sendMythicMessage("Item Type - Rate - Expected")
sender.sendMythicMessage("---------------------------")
val dropStrategy =
dropStrategyManager.getById(settingsManager.configSettings.drops.strategy)
?: return
displayRate(sender, "Tiered Items", MythicDropTracker.tieredItemRate(), dropStrategy.tieredItemChance)
displayRate(sender, "Custom Items", MythicDropTracker.customItemRate(), dropStrategy.customItemChance)
displayRate(sender, "Socket Gems", MythicDropTracker.socketGemRate(), dropStrategy.socketGemChance)
displayRate(
sender,
"Unidentified Items",
MythicDropTracker.unidentifiedItemRate(),
dropStrategy.unidentifiedItemChance
)
displayRate(sender, "Identity Tomes", MythicDropTracker.identityTomeRate(), dropStrategy.identityTomeChance)
displayRate(
sender,
"Socket Extenders",
MythicDropTracker.socketExtenderRate(),
dropStrategy.socketExtenderChance
)
}
private fun displayRate(
sender: CommandSender,
type: String,
rate: Double,
expected: Double
) {
sender.sendMythicMessage(
"$type - %rate% - %expected%",
listOf(
"%rate%" to decimalFormat.format(rate),
"%expected%" to decimalFormat.format(expected)
)
)
}
}
| 64 |
Kotlin
|
43
| 40 |
e08d2ad3befda5e18bd763b6f30f00fa4ff44c35
| 4,059 |
MythicDrops
|
MIT License
|
libs/ws/test/libs/ws/SoapTest.kt
|
navikt
| 797,896,421 | false |
{"Kotlin": 70589}
|
package libs.ws
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.http.HttpStatusCode
import io.ktor.serialization.jackson.jackson
import io.ktor.server.request.header
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows
class SoapTest {
companion object {
private val proxy = ProxyFake()
@AfterAll
@JvmStatic
fun close() = proxy.close()
}
@AfterEach
fun reset() = proxy.reset()
@Test
fun `soap fake response can be configured`() {
val sts = StsClient(proxy.config.sts)
val soap = SoapClient(proxy.config, sts)
proxy.soap.response = "sweet"
val res = runBlocking {
soap.call("nice", "<xml>hello</xml>")
}
assertEquals("sweet", res)
}
@Test
fun `can use proxy-auth`() {
val sts = StsClient(proxy.config.sts)
val soap = SoapClient(proxy.config, sts, proxyAuth = suspend {
"token for proxy"
})
proxy.soap.request = {
it.request.header("X-Proxy-Authorization") == "token for proxy"
}
assertDoesNotThrow {
runBlocking {
soap.call("action", "yo")
}
}
}
@Test
fun `aksepterer 200`() {
val sts = StsClient(proxy.config.sts)
val soap = SoapClient(proxy.config, sts)
proxy.soap.responseStatus = HttpStatusCode.OK
assertDoesNotThrow {
runBlocking {
soap.call("nice", "<xml>hello</xml>")
}
}
}
@Test
fun `aksepterer 500`() {
val sts = StsClient(proxy.config.sts)
val soap = SoapClient(proxy.config, sts, http = HttpClient(CIO) {
install(ContentNegotiation) {
jackson { }
}
})
proxy.soap.responseStatus = HttpStatusCode.InternalServerError
assertDoesNotThrow {
runBlocking {
soap.call("nice", "<xml>hello</xml>")
}
}
}
@Test
fun `kaster feil ved ukjent http statuskode`() {
val sts = StsClient(proxy.config.sts)
val soap = SoapClient(proxy.config, sts)
proxy.soap.responseStatus = HttpStatusCode(418, "I'm a teapot")
assertThrows<IllegalStateException> {
runBlocking {
soap.call("nice", "<xml>hello</xml>")
}
}
}
}
| 1 |
Kotlin
|
0
| 0 |
5aed5cfbeffb7bacd8ffa091d5b913e6b13a61cd
| 2,740 |
helved-libs
|
MIT License
|
livingdoc-engine/src/test/kotlin/org/livingdoc/engine/resources/DisabledScenarioDocument.kt
|
LivingDoc
| 85,412,044 | false | null |
package org.livingdoc.engine.resources
import org.livingdoc.api.disabled.Disabled
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.scenarios.ScenarioFixture
@ExecutableDocument("local://Calculator.html")
class DisabledScenarioDocument {
@Disabled("Disabled ScenarioFixture")
@ScenarioFixture
class DisabledScenarioFixture
}
| 34 |
Kotlin
|
16
| 14 |
f3d52b8bacbdf81905e4b4a753d75f584329b297
| 378 |
livingdoc
|
Apache License 2.0
|
mobile/src/main/java/com/google/samples/apps/iosched/ui/info/InfoModule.kt
|
kingstenbanh
| 156,424,020 | false | null |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.info
import com.google.samples.apps.iosched.ui.MainModule
import dagger.Module
import dagger.android.AndroidInjector
import dagger.android.ContributesAndroidInjector
/**
* Module where classes needed to create the [InfoFragment] are defined.
*/
@Module
internal abstract class InfoModule {
/**
* Generates an [AndroidInjector] for the [InfoFragment] as a Dagger subcomponent of the
* [MainModule].
*/
@ContributesAndroidInjector
internal abstract fun contributeInfoFragment(): InfoFragment
/**
* Generates an [AndroidInjector] for the [EventFragment] as a Dagger subcomponent of the
* [MainModule].
*/
@ContributesAndroidInjector
internal abstract fun contributeEventFragment(): EventFragment
/**
* Generates an [AndroidInjector] for the [TravelFragment] as a Dagger subcomponent of the
* [MainModule].
*/
@ContributesAndroidInjector
internal abstract fun contributeTravelFragment(): TravelFragment
/**
* Generates an [AndroidInjector] for the [FaqFragment] as a Dagger subcomponent of the
* [MainModule].
*/
@ContributesAndroidInjector
internal abstract fun contributeFaqFragment(): FaqFragment
/**
* Generates an [AndroidInjector] for the [SettingsFragment] as a Dagger subcomponent of the
* [MainModule].
*/
@ContributesAndroidInjector
internal abstract fun contributeSettingsFragment(): SettingsFragment
}
| 1 | null |
1
| 1 |
f3647a65ef817cf4ae378304c083386cce4ec398
| 2,092 |
iosched
|
Apache License 2.0
|
jdbc/src/migrator/DBMigrator.kt
|
codeborne
| 432,708,235 | false | null |
package klite.jdbc
import klite.*
import klite.jdbc.ChangeSet.On.*
import java.sql.SQLException
import javax.sql.DataSource
/**
* Applies changesets to the DB that haven't been applied yet, a simpler Liquibase replacement.
* Either provide [ChangeSet] instances in code or use [ChangeSetFileReader] for loading them from .sql files.
*/
open class DBMigrator(
private val db: DataSource = ConfigDataSource(),
private val changeSets: Sequence<ChangeSet> = ChangeSetFileReader(Config.optional("DB_MIGRATE", "db.sql")),
private val contexts: Set<String> = Config.active,
private val dropAllOnFailure: Boolean = Config.isTest
): Extension {
private val log = logger()
private val repository = ChangeSetRepository(db)
private val tx = Transaction(db)
private var history = mutableMapOf<String, ChangeSet>()
override fun install(server: Server) = migrate()
fun migrate() = try {
doMigrate()
} catch (e: MigrationException) {
if (dropAllOnFailure) {
log.error("Migration failed, dropping and retrying from scratch", e)
dropAll()
doMigrate()
} else throw e
}
private fun doMigrate() = tx.attachToThread().use {
try {
log.info("Locking"); lock()
readHistory()
changeSets.forEach(::run)
} finally {
unlock(); log.info("Unlocked")
}
}
private fun readHistory() = try {
history = repository.list().associateByTo(HashMap()) { it.id }
} catch (e: SQLException) {
log.warn(e.toString())
tx.rollback()
history = mutableMapOf()
ChangeSetFileReader("migrator/init.sql").forEach(::run)
}
open fun lock() = db.lock(javaClass.name)
open fun unlock() = db.unlock(javaClass.name)
@Suppress("NAME_SHADOWING")
open fun dropAll(schema: String? = null) = tx.attachToThread().use {
val schema = schema ?: db.withConnection { this.schema }
log.warn("Dropping and recreating schema $schema")
db.exec("drop schema $schema cascade")
db.exec("create schema $schema")
}
fun run(changeSet: ChangeSet) {
if (!changeSet.matches(contexts)) return
var run = true
history[changeSet.id]?.let {
if (it.checksum == changeSet.checksum) return
if (it.checksum == null) {
log.info("Storing new checksum for ${changeSet.id}")
return markRan(changeSet)
}
when (changeSet.onChange) {
FAIL -> throw MigrationException(changeSet, "has changed, old checksum=${it.checksum}, use onChange to override")
SKIP -> return log.warn("Skipping changed $changeSet")
MARK_RAN -> {
log.warn("$changeSet - marking as ran")
run = false
}
RUN -> {}
}
}
try {
if (run) changeSet.statements.forEach {
log.info("Running ${changeSet.copy(sql = it)}")
changeSet.rowsAffected += db.exec(it)
}
markRan(changeSet)
} catch (e: Exception) {
tx.rollback()
when (changeSet.onFail) {
SKIP -> log.warn("Skipping failed $changeSet: $e")
MARK_RAN -> {
log.warn("Marking as ran failed $changeSet: $e")
markRan(changeSet)
}
else -> throw MigrationException(changeSet, e)
}
}
if (changeSet.sql.contains(repository.table)) {
log.info(repository.table + " was accessed, re-reading history")
readHistory()
} else history[changeSet.id] = changeSet
}
private fun markRan(changeSet: ChangeSet) {
repository.save(changeSet)
tx.commit()
}
}
class MigrationException(message: String, cause: Throwable? = null): RuntimeException(message, cause) {
constructor(changeSet: ChangeSet, cause: Throwable? = null): this("Failed $changeSet", cause)
constructor(changeSet: ChangeSet, message: String): this("$changeSet\n - $message")
}
| 4 | null |
13
| 95 |
466a6f0351ef74e1295c0d46dc3b265aa3cf3eb3
| 3,771 |
klite
|
MIT License
|
zoomimage-core/src/commonTest/kotlin/com/github/panpf/zoomimage/core/common/test/util/CoreUtilsTest.kt
|
panpf
| 647,222,866 | false | null |
package com.github.panpf.zoomimage.core.common.test.util
import com.github.panpf.zoomimage.test.Platform
import com.github.panpf.zoomimage.test.current
import com.github.panpf.zoomimage.util.format
import com.github.panpf.zoomimage.util.quietClose
import com.github.panpf.zoomimage.util.toHexString
import okio.Closeable
import okio.IOException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
class CoreUtilsTest {
@Test
fun testFormat() {
assertEquals(1.2f, 1.234f.format(1), 0f)
assertEquals(1.23f, 1.234f.format(2), 0f)
assertEquals(1.24f, 1.235f.format(2), 0f)
}
@Test
fun testToHexString() {
val any1 = Any()
val any2 = Any()
assertEquals(
expected = any1.hashCode().toString(16),
actual = any1.toHexString()
)
assertEquals(
expected = any2.hashCode().toString(16),
actual = any2.toHexString()
)
assertNotEquals(
illegal = any1.toHexString(),
actual = any2.toHexString()
)
}
@Test
fun testQuietClose() {
if (Platform.current == Platform.iOS) {
// TODO Will get stuck forever in iOS test environment
return
}
val myCloseable = MyCloseable()
assertFailsWith(IOException::class) {
myCloseable.close()
}
myCloseable.quietClose()
}
private class MyCloseable : Closeable {
override fun close() {
throw IOException("Closed")
}
}
}
| 8 | null |
16
| 303 |
8627b3429ce148cccbaee751cc6793a63cb48b69
| 1,632 |
zoomimage
|
Apache License 2.0
|
app/src/main/java/com/WrapX/vcentremap/repo/retrofit/SlotFeed.kt
|
Marvel999
| 368,595,344 | false | null |
package com.WrapX.vcentremap.repo.retrofit
import com.WrapX.vcentremap.repo.model.SloatResponse
import retrofit2.Response
interface SlotFeed {
suspend fun getFeed(pincode:String,date:String): Response<SloatResponse>
}
| 0 |
Kotlin
|
1
| 1 |
a956ecac0474f69c544e6a7838286dcba974da7a
| 224 |
VCenter-Map
|
Apache License 2.0
|
src/main/kotlin/no/java/mooseheadreborn/dto/AddWorkshopDto.kt
|
javaBin
| 835,594,711 | false |
{"Kotlin": 63792, "TypeScript": 42500, "HTML": 3273, "Shell": 1428, "Procfile": 180, "CSS": 21}
|
package no.java.mooseheadreborn.dto
class AddWorkshopDto(
val id:String?,
val name:String,
val workshopType:String,
val capacity:Int,
val registrationOpens:String?,
val accessToken:String,
)
| 0 |
Kotlin
|
0
| 0 |
ae41febc3c1eb260509d0fa83394a3861de0097b
| 215 |
mooseheadreborn
|
Apache License 2.0
|
src/commonMain/kotlin/io/github/kkarnauk/parsek/token/type/TextTokenType.kt
|
kkarnauk
| 440,554,625 | false |
{"Kotlin": 111337}
|
package io.github.kkarnauk.parsek.token.type
/**
* Represents a token that tries to match [text] from an index in an input.
* If [ignoreCase] is `true` then case is ignored while matching.
* Match is considered as successful iff the whole [text] is matched.
*/
public class TextTokenType(
private val text: CharSequence,
private val ignoreCase: Boolean,
name: String,
ignored: Boolean
) : AbstractTokenType(name, ignored) {
override fun match(input: CharSequence, fromIndex: Int): Int =
if (input.startsWith(text, fromIndex, ignoreCase)) text.length else 0
}
| 0 |
Kotlin
|
0
| 17 |
7479f94b28d4fdb611f4fabf83acece597a0203c
| 592 |
parsek
|
Apache License 2.0
|
library_gradle/src/main/java/com/swensun/plugin/time/TimeTransform.kt
|
musicer
| 275,362,713 | true |
{"Kotlin": 322541, "Java": 106595}
|
package com.swensun.plugin.time
import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager.CONTENT_CLASS
import com.android.build.gradle.internal.pipeline.TransformManager.SCOPE_FULL_PROJECT
import com.android.utils.FileUtils
import org.gradle.api.Project
class TimeTransform(val project: Project) : Transform() {
override fun getName(): String {
return "TimeTransform"
}
override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> {
return CONTENT_CLASS
}
override fun isIncremental(): Boolean {
return false
}
override fun getScopes(): MutableSet<in QualifiedContent.Scope> {
return SCOPE_FULL_PROJECT
}
override fun transform(transformInvocation: TransformInvocation?) {
println(" ------- transform begin ---------")
transformInvocation?.inputs?.forEach { transformInput ->
transformInput.directoryInputs.forEach { directoryInput ->
// 注入代码
TimeInjectByJavassist.injectToast(directoryInput.file.absolutePath, project)
// 复制修改过的目录到对应的文件夹
val dest = transformInvocation.outputProvider.getContentLocation(
directoryInput.name, directoryInput.contentTypes, directoryInput.scopes,
Format.DIRECTORY
)
FileUtils.copyDirectory(directoryInput.file, dest)
}
transformInput.jarInputs.forEach { jarInput ->
val dest = transformInvocation.outputProvider.getContentLocation(
jarInput.name, jarInput.contentTypes, jarInput.scopes,
Format.JAR
)
FileUtils.copyFile(jarInput.file, dest)
}
}
println(" ------- transform end ---------")
}
}
| 0 | null |
0
| 0 |
9f8ad6ad8b902f8d0df5daa66ced419b48531ff6
| 1,886 |
Potato
|
Apache License 2.0
|
src/main/kotlin/ar/edu/utn/frba/tacs/tp/api/herocardsgame/service/DeckService.kt
|
tacs-2021-1c-tp-hero-cards
| 358,787,857 | false |
{"Gradle": 1, "YAML": 3, "Dotenv": 1, "Gradle Kotlin DSL": 1, "Dockerfile": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "JSON": 14, "Java": 1, "Kotlin": 132, "JavaScript": 1, "HTML": 1, "CSS": 1}
|
package ar.edu.utn.frba.tacs.tp.api.herocardsgame.service
import ar.edu.utn.frba.tacs.tp.api.herocardsgame.exception.InvalidPowerstatsException
import ar.edu.utn.frba.tacs.tp.api.herocardsgame.integration.CardIntegration
import ar.edu.utn.frba.tacs.tp.api.herocardsgame.integration.DeckIntegration
import ar.edu.utn.frba.tacs.tp.api.herocardsgame.models.game.Card
import ar.edu.utn.frba.tacs.tp.api.herocardsgame.models.game.deck.Deck
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
class DeckService(
private val cardIntegration: CardIntegration,
private val deckIntegration: DeckIntegration
) {
private val log: Logger = LoggerFactory.getLogger(DeckService::class.java)
fun createDeck(nameDeck: String, cardIds: List<String>): Deck {
log.info("Create deck with name: $nameDeck and cardIds: [${cardIds.joinToString(",")}]")
val cards = searchCards(cardIds)
val deck = Deck(name = nameDeck, cards = cards)
return deckIntegration.saveDeck(deck)
}
fun deleteDeck(deckId: String) {
log.info("Delete deck with id: $deckId")
deckIntegration.deleteDeck(deckId.toLong())
}
fun searchDeck(deckId: String? = null, deckName: String? = null): List<Deck> {
log.info("Search deck with id: $deckId or deckName: $deckName")
return deckIntegration.getDeckByIdOrName(deckId, deckName)
}
fun updateDeck(deckId: String, name: String?, cardIds: List<String>): Deck {
log.info("Update deck with id: $deckId with newName: $name or newCardIds: [${cardIds.joinToString(",")}]")
val deck = deckIntegration.getDeckById(deckId.toLong())
log.info("Deck to update its oldName: ${deck.name} and oldCardIds: [${deck.cards.map { it.id }.joinToString(",")}]")
val cards = searchCards(cardIds)
val newDeck = deck.updateDeck(name, cards)
return deckIntegration.saveDeck(newDeck)
}
private fun searchCards(cardIds: List<String>): List<Card> {
val cards = cardIds.map { cardIntegration.getCardById(it) }
cards.filter { it.validateInvalidPowerstats() }.map { throw InvalidPowerstatsException(it.id) }
return cards
}
}
| 20 | null |
1
| 1 |
5ddb882bfdef41c04eaca7a68afacbb2999457bb
| 2,240 |
hero-cards-game
|
MIT License
|
app/src/main/java/com/rain/currency/ui/menu/MenuType.kt
|
nongdenchet
| 128,639,036 | false | null |
package com.rain.currency.ui.menu
enum class MenuType(val value: String) {
COPY("Copy"),
PASTE("Paste"),
CUT("Cut"),
CLEAR("Clear");
}
| 1 |
Kotlin
|
1
| 4 |
a9b9d4741d0fb315cafa6297ee905fbba89fd177
| 152 |
Kurrency
|
MIT License
|
app/src/main/java/com/uramonk/androidtemplateapp/presentation/view/LicenseFragment.kt
|
uramonk
| 61,422,772 | false | null |
package com.uramonk.androidtemplateapp.presentation.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import com.trello.rxlifecycle.components.RxFragment
import com.uramonk.androidtemplateapp.R
import com.uramonk.androidtemplateapp.databinding.FragmentLicenseBinding
import com.uramonk.androidtemplateapp.presentation.viewmodel.LicenseFragmentViewModel
class LicenseFragment : RxFragment() {
private lateinit var binding: FragmentLicenseBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_license, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding = FragmentLicenseBinding.bind(view)
val licenseFragmentViewModel = LicenseFragmentViewModel(this)
binding.licenseFragmentViewModel = licenseFragmentViewModel
}
fun getWebView(): WebView {
return binding.webview
}
companion object {
fun newInstance(): LicenseFragment {
return LicenseFragment()
}
}
}
| 1 | null |
1
| 1 |
91c551439bf90ba9533b71eeadd429e8fe973110
| 1,264 |
AndroidTemplateApp
|
MIT License
|
idea/testData/quickfix/typeProjection/afterProjectionInImmediateArgumentToSupertype.kt
|
udalov
| 10,645,710 | false | null |
// "Remove 'in' modifier" "true"
trait A<T> {}
class B : A<Int> {}
| 0 | null |
1
| 6 |
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
| 68 |
kotlin-objc-diploma
|
Apache License 2.0
|
plugins/kotlin/j2k/new/tests/testData/newJ2k/typeCastExpression/byteCasts.kt
|
ingokegel
| 72,937,917 | false | null |
internal class A {
fun byteToInt() {
val a = 1.toByte().toInt()
val b: Byte = 2
val c = b.toInt()
val d = b + c
}
fun byteToChar() {
val a = Char(1.toByte().toUShort())
val b: Byte = 2
val c = Char(b.toUShort())
val d = (b + c.code.toByte()).toChar()
}
fun byteToShort() {
val a = 1.toByte().toShort()
val b: Byte = 2
val c = b.toShort()
val d = (b + c).toShort()
}
fun byteToLong() {
val a = 1.toByte().toLong()
val b: Byte = 2
val c = b.toLong()
val d = b + c
}
fun byteToFloat() {
val a = 1.toByte().toFloat()
val b: Byte = 2
val c = b.toFloat()
val d = b + c
}
fun byteToDouble() {
val a = 1.toByte().toDouble()
val b: Byte = 2
val c = b.toDouble()
val d = b + c
}
fun intToByte() {
val a: Byte = 1
val b = 2
val c = b.toByte()
val d = (b + c).toByte()
}
fun charToByte() {
val a = 'a'.code.toByte()
val b = 'b'
val c = b.code.toByte()
val d = (b.code.toByte() + c).toByte()
}
fun shortToByte() {
val a = 1.toShort().toByte()
val b: Short = 2
val c = b.toByte()
val d = (b + c).toByte()
}
fun longToByte() {
val a = 1L.toByte()
val b: Long = 2
val c = b.toByte()
val d = (b + c).toByte()
}
fun floatToByte() {
val a = 1.0f.toInt().toByte()
val b = 2f
val c = b.toInt().toByte()
val d = (b + c).toInt().toByte()
}
fun doubleToByte() {
val a = 1.0.toInt().toByte()
val b = 2.0
val c = b.toInt().toByte()
val d = (b + c).toInt().toByte()
}
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 1,834 |
intellij-community
|
Apache License 2.0
|
src/all/wpmanga/src/eu/kanade/tachiyomi/extension/all/wpmanga/WpMangaFactory.kt
|
mangacat
| 190,679,694 | false | null |
package eu.kanade.tachiyomi.extension.all.wpmanga
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
class WpMangaFactory : SourceFactory {
override fun createSources(): List<Source> = getAllWpManga()
}
fun getAllWpManga(): List<Source> {
return listOf(
TrashScanlations(),
ZeroScans()
)
}
class TrashScanlations : WpManga("Trash Scanlations", "https://trashscanlations.com/", "en")
class ZeroScans : WpManga("Zero Scans", "https://zeroscans.com/", "en")
| 0 | null |
1
| 2 |
1d538bb2fec19417c69c0799526469fb7799e33e
| 535 |
tachiyomi-extensions
|
Apache License 2.0
|
shared/src/main/kotlin/org/tools4j/fix/NonAnnotatedMessageString.kt
|
tools4j
| 124,669,693 | false | null |
package org.tools4j.fix
import java.util.ArrayList
/**
* User: ben
* Date: 13/06/2017
* Time: 6:38 AM
*/
class NonAnnotatedMessageString(private val line: String, private val delimiterRegex: String) : FieldsSource {
override val fields: Fields by lazy {
val messageAsSplitString = SplitableByRegexString(line, delimiterRegex).split()
val fields = ArrayList<Field>()
for (fieldStr in messageAsSplitString) {
val fieldAsSplitString: SplitString = SplitableByRegexString(fieldStr, "=").split()
val tag: String = fieldAsSplitString[0]
val value = fieldAsSplitString.allElementsOnwards(1, delimiterRegex)
fields.add(FieldImpl(tag, value!!))
}
FieldsImpl(fields)
}
}
| 0 |
Kotlin
|
1
| 7 |
e2cbc5b0b174f7ab462603e8ff65701501dfeae1
| 765 |
market-simulator
|
MIT License
|
src/main/kotlin/org/example/kforgepro/modules/user/endpoints/UserRegisterPostAutoBfEp.kt
|
ogrebgr
| 237,232,376 | false | null |
package org.example.kforgepro.modules.user.endpoints
import com.bolyartech.forge.server.db.DbPool
import com.bolyartech.forge.server.misc.Params
import com.bolyartech.forge.server.response.forge.ForgeResponse
import com.bolyartech.forge.server.response.forge.MissingParametersResponse
import com.bolyartech.forge.server.response.forge.OkResponse
import com.bolyartech.forge.server.route.RequestContext
import org.example.kforgepro.modules.user.UserResponseCodes
import org.example.kforgepro.modules.user.data.*
import java.lang.IllegalStateException
import java.sql.Connection
import javax.inject.Inject
class UserRegisterPostAutoBfEp @Inject constructor(
dbPool: DbPool,
private val userDbOps: UserDbOps,
private val userScreenNameDbh: UserScreenNameDbh
) : UserDbEndpoint(dbPool) {
private val PARAM_USERNAME = "username"
private val PARAM_PASSWORD = "<PASSWORD>"
private val PARAM_SCREEN_NAME = "screen_name"
override fun handle(ctx: RequestContext, dbc: Connection, user: User): ForgeResponse {
val username = ctx.getFromPost(PARAM_USERNAME)
val password = ctx.getFromPost(PARAM_PASSWORD)
val screenName = ctx.getFromPost(PARAM_SCREEN_NAME)
if (!Params.areAllPresent(username, password)) {
return MissingParametersResponse.getInstance()
}
if (!User.isValidUsername(username)) {
return ForgeResponse(UserResponseCodes.INVALID_USERNAME, "Invalid username")
}
if (!User.isValidPasswordLength(password)) {
return ForgeResponse(UserResponseCodes.INVALID_PASSWORD, "Password too short")
}
val existing = userScreenNameDbh.loadByUser(dbc, user.id)
if (existing == null) {
if (screenName == null || screenName.isEmpty()) {
return MissingParametersResponse.getInstance()
}
if (!UserScreenName.isValid(screenName)) {
return ForgeResponse(UserResponseCodes.INVALID_SCREEN_NAME, "Invalid screen name")
}
}
val rez = userDbOps.createNewNamedUserPostAuto(dbc, username, password, screenName)
if (rez is NewUserResultOK) {
return OkResponse()
} else if (rez is NewUserResultError) {
return if (rez.isUsernameTaken) {
ForgeResponse(UserResponseCodes.USERNAME_EXISTS, "Username exists")
} else {
ForgeResponse(UserResponseCodes.SCREEN_NAME_EXISTS, "screen name taken")
}
} else {
throw IllegalStateException()
}
}
}
| 1 | null |
1
| 1 |
4876b600060dae9ee48aae6550cdab42c298a2ad
| 2,589 |
kforge-server-pro-pack
|
Apache License 2.0
|
note_book/src/main/java/com/inz/z/note_book/broadcast/ClockAlarmBroadcast.kt
|
Memory-Z
| 141,771,340 | false |
{"Java": 1063423, "Kotlin": 584610}
|
package com.inz.z.note_book.broadcast
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.inz.z.base.util.L
import com.inz.z.note_book.util.Constants
/**
* 时钟 广播
*
* @author Zhenglj
* @version 1.0.0
* Create by inz in 2020/01/15 15:51.
*/
class ClockAlarmBroadcast : BroadcastReceiver() {
companion object {
private const val TAG = "AlarmBroadcast"
}
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.action
L.i(TAG, "onReceive: $action <<<<<< ")
when (action) {
Constants.CLOCK_ALARM_START_ACTION -> {
}
else -> {
}
}
}
}
| 1 |
Java
|
1
| 1 |
feff01057cf308fcbf9f1ebf880b9a114badf970
| 732 |
Z_inz
|
Apache License 2.0
|
course/src/main/java/de/hpi/android/course/domain/GetCourseDetailUseCase.kt
|
HPI-de
| 168,352,832 | false | null |
package de.hpi.android.course.domain
import de.hpi.android.core.data.Id
import de.hpi.android.core.domain.ObservableUseCase
import de.hpi.android.core.domain.Result
import de.hpi.android.core.domain.mapResult
import de.hpi.android.course.data.CourseDetailDto
import de.hpi.android.course.data.CourseDetailRepository
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
object GetCourseDetailUseCase : ObservableUseCase<Id<CourseDetailDto>, CourseDetail>() {
override val subscribeScheduler = Schedulers.io()
override fun execute(params: Id<CourseDetailDto>): Observable<Result<CourseDetail>> {
return CourseDetailRepository.get(params).mapResult { it.toCourseDetailEntity() }
}
}
| 48 | null |
1
| 7 |
65c00f511f2eff3e1c08fe67fda1bc2dac85daba
| 723 |
hpi-android
|
Apache License 2.0
|
modelapp/src/main/java/promise/modelapp/ComplexModel.kt
|
android-promise
| 204,985,526 | false | null |
/*
* Copyright 2017, <NAME>
* Licensed under the Apache License, Version 2.0, Android Promise.
* 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 promise.modelapp
import androidx.collection.ArrayMap
import promise.commons.data.log.LogUtil
import promise.commons.model.Identifiable
import promise.commons.model.List
import promise.commons.tx.Either
import promise.commons.tx.Left
import promise.commons.tx.Right
import promise.model.AbstractEitherIDataStore
import promise.model.CLASS_ARG
import promise.model.PreferenceDatabase
import promise.model.Repository
import promise.model.StoreRepository
class ComplexModel : Identifiable<Int> {
var uId = 0
var name: String = ""
var isModel = false
override fun toString(): String = "ComplexModel(id=$uId)"
override fun getId(): Int = uId
override fun setId(t: Int) {
this.uId = t
}
}
const val NUMBER_ARG = "number_arg"
const val TIMES_ARG = "times_arg"
const val ID_ARG = "id_arg"
/**
* sample store for complex models
*
*/
class SyncComplexModelStore(
private val preferenceDatabase: PreferenceDatabase<ComplexModel>) :
AbstractEitherIDataStore<ComplexModel>() {
val TAG: String = LogUtil.makeTag(SyncComplexModelStore::class.java)
override fun findAll(args: Map<String, Any?>?): Either<List<out ComplexModel>> {
if (args == null) throw IllegalArgumentException("number and times args must be passed")
val number = args[NUMBER_ARG] as Int
val times = args[TIMES_ARG] as Int
LogUtil.e(TAG, "repo args ", number, times)
val savedModels = preferenceDatabase.findAll(ArrayMap<String, Any>().apply {
put(CLASS_ARG, ComplexModel::class.java)
})
return Right(if (savedModels.isEmpty()) {
val models = List<ComplexModel>()
(0 until number * times).forEach {
models.add(ComplexModel().apply {
uId = it + 1
name = getId().toString() + "n"
isModel = getId().rem(2) == 0
})
}
preferenceDatabase.save(models)
models
} else List(savedModels))
}
override fun findOne(args: Map<String, Any?>?): Either<ComplexModel> {
if (args == null || !args.containsKey(ID_ARG)) throw IllegalArgumentException("ID_ARG must be passed in args")
val model = preferenceDatabase.findOne(args)
return if (model != null) Right(model) else
Left(Exception("model not found"))
}
}
val complexStore: Repository<ComplexModel> by lazy {
StoreRepository.of(
SyncComplexModelStore::class,
arrayOf(preferenceDatabase))
}
| 1 | null |
1
| 3 |
63187927ce65eb1085a080bfccb0662db033e86b
| 2,962 |
model
|
Apache License 2.0
|
core-legacy/src/test/java/com/dipien/core/utils/ValidationUtilsTest.kt
|
dipien
| 83,250,302 | false | null |
package com.dipien.core.utils
import org.junit.Assert
import org.junit.Test
/**
* Test for ValidationUtils
*/
class ValidationUtilsTest {
@Test
fun isValidURL() {
Assert.assertTrue(ValidationUtils.isValidURL("http://www.validUrl.com"))
Assert.assertTrue(ValidationUtils.isValidURL("http://www.validUrl.com/;kw=[service,110343]"))
Assert.assertFalse(ValidationUtils.isValidURL("invalidUrl"))
Assert.assertFalse(ValidationUtils.isValidURL("htp://invalid.com"))
}
}
| 3 | null |
1
| 3 |
755109b4b63969287b64f42973bdb287ab06c13f
| 512 |
kotlin-libraries
|
Apache License 2.0
|
app/src/main/java/me/tagavari/airmessage/util/ActivityStatusUpdate.kt
|
airmessage
| 326,065,827 | false | null |
package me.tagavari.airmessage.util
import me.tagavari.airmessage.enums.MessageState
/**
* A class for passing around data related to an activity status update
* @param messageID The ID of the message that is being updated
* @param messageState The message's new state
* @param dateRead The date the message was read
*/
data class ActivityStatusUpdate @JvmOverloads constructor(
val messageID: Long,
@field:MessageState @get:MessageState @param:MessageState val messageState: Int,
val dateRead: Long = -1
)
| 42 | null |
2
| 36 |
3c73ef5efb8248aa86eb21d7f28f5ae517720d91
| 516 |
airmessage-android
|
Apache License 2.0
|
core/sdk/src/test/java/com/mongodb/stitch/core/StitchClientConfigurationUnitTests.kt
|
mongodb
| 87,100,729 | false | null |
/*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb.stitch.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import com.mongodb.stitch.core.internal.common.BsonUtils
import com.mongodb.stitch.core.internal.common.MemoryStorage
import com.mongodb.stitch.core.internal.net.Transport
import com.mongodb.stitch.core.testutils.CustomType
import org.bson.Document
import org.bson.codecs.configuration.CodecRegistries
import org.junit.Test
import org.mockito.Mockito
class StitchAppClientConfigurationUnitTests {
@Test
fun testStitchAppClientConfigurationBuilder() {
val localAppVersion = "bar"
val localAppName = "baz"
val baseUrl = "qux"
val storage = MemoryStorage()
val transport = Mockito.mock(Transport::class.java)
val builder = StitchAppClientConfiguration.Builder()
builder.withBaseUrl(baseUrl)
builder.withStorage(storage)
builder.withTransport(transport)
builder.withDefaultRequestTimeout(1500L)
builder.withLocalAppVersion(localAppVersion)
builder.withLocalAppName(localAppName)
var config = builder.build()
assertEquals(config.localAppVersion, localAppVersion)
assertEquals(config.localAppName, localAppName)
assertEquals(config.baseUrl, baseUrl)
assertEquals(config.storage, storage)
assertEquals(config.transport, transport)
assertEquals(BsonUtils.DEFAULT_CODEC_REGISTRY, config.codecRegistry)
// With a custom codec
val customTypeCodec = CustomType.Codec()
builder.withCodecRegistry(CodecRegistries.fromCodecs(customTypeCodec))
config = builder.build()
assertEquals(config.localAppVersion, localAppVersion)
assertEquals(config.localAppName, localAppName)
assertEquals(config.baseUrl, baseUrl)
assertEquals(config.storage, storage)
assertEquals(config.transport, transport)
// Ensure that there is a codec for our custom type.
assertEquals(config.codecRegistry.get(CustomType::class.java), customTypeCodec)
// Ensure that configuring the custom codec merged with the default types.
assertNotNull(config.codecRegistry.get(Document::class.java))
}
}
| 9 |
Java
|
31
| 58 |
8ce97f847ad309cd8352c426374383faec3b929b
| 2,837 |
stitch-android-sdk
|
Apache License 2.0
|
idea-plugin/src/main/kotlin/me/danwi/sqlex/idea/util/extension/PsiElement.kt
|
sqlex
| 476,155,993 | false | null |
package me.danwi.sqlex.idea.util.extension
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
inline fun <reified T : PsiElement> PsiElement.childrenOf(): Collection<T> {
return PsiTreeUtil.findChildrenOfType(this, T::class.java)
}
inline fun <reified T : PsiElement> PsiElement.parentOf(): T? {
return PsiTreeUtil.getParentOfType(this, T::class.java)
}
inline fun <reified T> PsiElement.injectedOf(): T? {
val files = mutableListOf<T>()
InjectedLanguageManager.getInstance(project)
.enumerate(this) { file, _ ->
if (file is T)
files.add(file)
}
return files.firstOrNull()
}
| 1 | null |
5
| 33 |
9259b69471dbfdf0912b57744661026e427d1dd2
| 726 |
sqlex
|
Apache License 2.0
|
airbyte-cdk/java/airbyte-cdk/core/src/main/kotlin/io/airbyte/cdk/integrations/base/FailureTrackingAirbyteMessageConsumer.kt
|
tim-werner
| 511,419,970 | false |
{"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2}
|
/*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.cdk.integrations.base
import io.airbyte.protocol.models.v0.AirbyteMessage
import io.github.oshai.kotlinlogging.KotlinLogging
private val LOGGER = KotlinLogging.logger {}
/**
* Minimal abstract class intended to provide a consistent structure to classes seeking to implement
* the [AirbyteMessageConsumer] interface. The original interface methods are wrapped in generic
* exception handlers - any exception is caught and logged.
*
* Two methods are intended for extension:
*
* * startTracked: Wraps set up of necessary infrastructure/configuration before message
* consumption.
* * acceptTracked: Wraps actual processing of each [io.airbyte.protocol.models.v0.AirbyteMessage].
*
* Though not necessary, we highly encourage using this class when implementing destinations. See
* child classes for examples.
*/
abstract class FailureTrackingAirbyteMessageConsumer : AirbyteMessageConsumer {
private var hasFailed = false
/**
* Wraps setup of necessary infrastructure/configuration before message consumption
*
* @throws Exception
*/
@Throws(Exception::class) protected abstract fun startTracked()
@Throws(Exception::class)
override fun start() {
try {
startTracked()
} catch (e: Exception) {
LOGGER.error(e) { "Exception while starting consumer" }
hasFailed = true
throw e
}
}
/**
* Processing of AirbyteMessages with general functionality of storing STATE messages,
* serializing RECORD messages and storage within a buffer
*
* NOTE: Not all the functionality mentioned above is always true but generally applies
*
* @param msg [AirbyteMessage] to be processed
* @throws Exception
*/
@Throws(Exception::class) protected abstract fun acceptTracked(msg: AirbyteMessage)
@Throws(Exception::class)
override fun accept(message: AirbyteMessage) {
try {
acceptTracked(message)
} catch (e: Exception) {
LOGGER.error(e) { "Exception while accepting message" }
hasFailed = true
throw e
}
}
@Throws(Exception::class) protected abstract fun close(hasFailed: Boolean)
@Throws(Exception::class)
override fun close() {
if (hasFailed) {
LOGGER.warn { "Airbyte message consumer: failed." }
} else {
LOGGER.info { "Airbyte message consumer: succeeded." }
}
close(hasFailed)
}
}
| 1 | null |
1
| 1 |
b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff
| 2,584 |
airbyte
|
MIT License
|
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/GrammarChecker.kt
|
hieuprogrammer
| 284,920,751 | false | null |
// Copyright 2000-2019 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.grazie.grammar
import com.intellij.grazie.grammar.ide.GraziePsiElementProcessor
import com.intellij.grazie.grammar.ide.GraziePsiElementProcessor.ElementShift
import com.intellij.grazie.grammar.ide.GraziePsiElementProcessor.TokenInfo
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.StrategyUtils
import com.intellij.grazie.utils.length
import com.intellij.grazie.utils.toPointer
import com.intellij.psi.PsiElement
import java.util.*
import kotlin.collections.ArrayList
object GrammarChecker {
private data class ShiftInText(val start: Int, val length: Int, val totalDeleted: Int)
private fun GrammarCheckingStrategy.determineStealthyRanges(root: PsiElement, text: StringBuilder): List<IntRange> {
return getStealthyRanges(root, text).sortedWith(Comparator.comparingInt { it.start })
}
private fun determineTextShifts(root: PsiElement, text: StringBuilder, strategy: GrammarCheckingStrategy,
shifts: List<ElementShift>) = ArrayList<ShiftInText>().apply {
fun addShift(position: Int, length: Int, totalDeleted: Int) {
if (isNotEmpty() && last().start == position) {
val last = removeAt(size - 1)
// combine shifts from same position
add(ShiftInText(position, last.length + length, last.totalDeleted + length))
}
else {
add(ShiftInText(position, length, totalDeleted))
}
}
var stealthed = 0 // count of newly removed characters from text after getResultedShifts()
var total = 0 // total deleted chars from text
val iterator = shifts.listIterator()
// Iterate over ignored ranges determined by PsiElement behaviour and
// ranges determined by strategy.getStealthyRanges, which working with text
// while combining intersecting ranges
for (range in strategy.determineStealthyRanges(root, text)) {
var deleted = 0
for ((position, length) in iterator) {
if (position < range.start) { // shift before range (remains the same, just add)
addShift(position - stealthed, length, total + length)
}
else if (position in range) { // shift inside range (combine in one)
deleted += length
}
else { // shift after range - need a step back
iterator.previous()
break
}
total += length
}
// delete text from stealthy ranges (we need stealthed to track offset in text)
text.delete(range.start - stealthed, range.endInclusive + 1 - stealthed)
total += range.length
addShift(range.start - stealthed, deleted + range.length, total)
stealthed += range.length
}
// after processing all ranges there still can be shifts after them
for ((position, length) in iterator) {
total += length
addShift(position, length, total)
}
}
fun check(root: PsiElement, strategy: GrammarCheckingStrategy): Set<Typo> {
val (tokens, shifts, text) = GraziePsiElementProcessor.processElements(root, strategy)
if (tokens.isEmpty()) return emptySet()
val textShifts = determineTextShifts(root, text, strategy, shifts)
val offset = StrategyUtils.trimLeadingQuotesAndSpaces(text)
return check(root, text, textShifts, offset, tokens, strategy)
}
private fun findPositionInsideRoot(position: Int, shifts: List<ShiftInText>): Int {
val index = shifts.binarySearch { it.start.compareTo(position) }
return when {
index >= 0 -> shifts[index].totalDeleted
-(index + 1) > 0 -> shifts[-(index + 1) - 1].totalDeleted
else -> 0
} + position
}
private fun findTextRangesToDelete(rangeInRoot: IntRange, rangeInText: IntRange, shifts: List<ShiftInText>) = ArrayList<IntRange>().apply {
var start = rangeInRoot.start
// take all shifts inside typo and invert them
shifts.filter { it.start > rangeInText.start && it.start <= rangeInText.endInclusive }.forEach { shift ->
add(IntRange(start, shift.start + shift.totalDeleted - shift.length - 1))
start = shift.start + shift.totalDeleted
}
add(IntRange(start, rangeInRoot.endInclusive + 1))
}
private fun findTokensInTypoPatternRange(tokens: Collection<TokenInfo>, patternRangeInRoot: IntRange): List<TokenInfo> {
return tokens.filter { it.range.endInclusive >= patternRangeInRoot.start && it.range.start <= patternRangeInRoot.endInclusive }.also {
check(it.isNotEmpty()) { "No tokens for range in typo: $patternRangeInRoot in ${tokens.map { token -> token.range }}" }
}
}
private fun check(root: PsiElement, text: StringBuilder, shifts: List<ShiftInText>, offset: Int,
tokens: Collection<TokenInfo>, strategy: GrammarCheckingStrategy) =
GrammarEngine.getTypos(text.toString(), offset = offset).mapNotNull { typo ->
val rangeInText = typo.location.errorRange
val rangeInRoot = rangeInText.convertToRangeInRoot(shifts)
val textRangesToDelete = findTextRangesToDelete(rangeInRoot, rangeInText, shifts)
val patternRangeInRoot = typo.location.patternRange.convertToRangeInRoot(shifts)
val tokensInTypoPatternRange = findTokensInTypoPatternRange(tokens, patternRangeInRoot)
val category = typo.category
when {
!strategy.isTypoAccepted(root, rangeInRoot, patternRangeInRoot) -> null // typo not accepted by strategy
tokensInTypoPatternRange.any { token ->
token.behavior == GrammarCheckingStrategy.ElementBehavior.ABSORB || // typo pattern in absorb element
category in token.ignoredCategories || // typo rule in ignored category
typo.info.rule.id in token.ignoredGroup.rules // typo rule in ignored group
} -> null
else -> typo.copy(
location = typo.location.copy(errorRange = rangeInRoot, textRanges = textRangesToDelete, pointer = root.toPointer())
)
}
}.toSet()
private fun IntRange.convertToRangeInRoot(shifts: List<ShiftInText>): IntRange {
return IntRange(findPositionInsideRoot(start, shifts), findPositionInsideRoot(endInclusive, shifts))
}
}
| 1 | null |
2
| 2 |
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
| 6,379 |
intellij-community
|
Apache License 2.0
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/bulk/Ftxtoken.kt
|
Tlaster
| 560,394,734 | false |
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.crypto.bulk
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.crypto.BulkGroup
public val BulkGroup.Ftxtoken: ImageVector
get() {
if (_ftxtoken != null) {
return _ftxtoken!!
}
_ftxtoken = Builder(name = "Ftxtoken", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFFffffff)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(24.0f, 0.0f)
horizontalLineTo(0.0f)
verticalLineTo(24.0f)
horizontalLineTo(24.0f)
verticalLineTo(0.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 2.0f)
horizontalLineTo(9.0f)
curveTo(8.45f, 2.0f, 8.0f, 2.45f, 8.0f, 3.0f)
verticalLineTo(6.0f)
curveTo(8.0f, 6.55f, 8.45f, 7.0f, 9.0f, 7.0f)
horizontalLineTo(21.0f)
curveTo(21.55f, 7.0f, 22.0f, 6.55f, 22.0f, 6.0f)
verticalLineTo(3.0f)
curveTo(22.0f, 2.45f, 21.55f, 2.0f, 21.0f, 2.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.0f, 17.0f)
horizontalLineTo(8.0f)
curveTo(7.45f, 17.0f, 7.0f, 17.45f, 7.0f, 18.0f)
verticalLineTo(21.0f)
curveTo(7.0f, 21.55f, 7.45f, 22.0f, 8.0f, 22.0f)
horizontalLineTo(11.0f)
curveTo(11.55f, 22.0f, 12.0f, 21.55f, 12.0f, 21.0f)
verticalLineTo(18.0f)
curveTo(12.0f, 17.45f, 11.55f, 17.0f, 11.0f, 17.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha
= 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 9.5f)
horizontalLineTo(3.0f)
curveTo(2.45f, 9.5f, 2.0f, 9.95f, 2.0f, 10.5f)
verticalLineTo(13.5f)
curveTo(2.0f, 14.05f, 2.45f, 14.5f, 3.0f, 14.5f)
horizontalLineTo(6.0f)
curveTo(6.55f, 14.5f, 7.0f, 14.05f, 7.0f, 13.5f)
verticalLineTo(10.5f)
curveTo(7.0f, 9.95f, 6.55f, 9.5f, 6.0f, 9.5f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha
= 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 9.6401f)
horizontalLineTo(10.5f)
curveTo(9.95f, 9.6401f, 9.5f, 10.0901f, 9.5f, 10.6401f)
verticalLineTo(13.3601f)
curveTo(9.5f, 13.9101f, 9.95f, 14.3601f, 10.5f, 14.3601f)
horizontalLineTo(17.0f)
curveTo(17.55f, 14.3601f, 18.0f, 13.9101f, 18.0f, 13.3601f)
verticalLineTo(10.6401f)
curveTo(18.0f, 10.0901f, 17.55f, 9.6401f, 17.0f, 9.6401f)
close()
}
}
.build()
return _ftxtoken!!
}
private var _ftxtoken: ImageVector? = null
| 0 |
Kotlin
|
0
| 2 |
b8a8231e6637c2008f675ae76a3423b82ee53950
| 4,591 |
VuesaxIcons
|
MIT License
|
kmock-processor/src/test/resources/mock/expected/kmock/Common.kt
|
bitPogo
| 455,829,905 | false |
{"Kotlin": 3506361}
|
package mock.template.kmock
import kotlin.Any
import kotlin.Array
import kotlin.Boolean
import kotlin.Int
import kotlin.IntArray
import kotlin.Suppress
import tech.antibytes.kmock.KMockContract
import tech.antibytes.kmock.proxy.NoopCollector
import tech.antibytes.kmock.proxy.ProxyFactory
internal class CommonMock(
collector: KMockContract.Collector = NoopCollector,
@Suppress("UNUSED_PARAMETER")
spyOn: Common? = null,
freeze: Boolean = false,
@Suppress("unused")
private val relaxUnitFun: Boolean = false,
@Suppress("unused")
private val relaxed: Boolean = false,
) : Common {
public val _foo: KMockContract.AsyncFunProxy<Any, suspend (Int, Any) -> Any> =
ProxyFactory.createAsyncFunProxy("mock.template.kmock.CommonMock#_foo", collector = collector,
freeze = freeze)
public val _bar: KMockContract.AsyncFunProxy<Any, suspend (Int, Any) -> Any> =
ProxyFactory.createAsyncFunProxy("mock.template.kmock.CommonMock#_bar", collector = collector,
freeze = freeze)
public val _ozz: KMockContract.AsyncFunProxy<Any, suspend (IntArray) -> Any> =
ProxyFactory.createAsyncFunProxy("mock.template.kmock.CommonMock#_ozz", collector = collector,
freeze = freeze)
public val _izz: KMockContract.AsyncFunProxy<Any, suspend (Array<out Any>) -> Any> =
ProxyFactory.createAsyncFunProxy("mock.template.kmock.CommonMock#_izz", collector = collector,
freeze = freeze)
public override suspend fun foo(fuzz: Int, ozz: Any): Any = _foo.invoke(fuzz, ozz)
public override suspend fun bar(buzz: Int, bozz: Any): Any = _bar.invoke(buzz, bozz)
public override suspend fun ozz(vararg buzz: Int): Any = _ozz.invoke(buzz)
public override suspend fun izz(vararg buzz: Any): Any = _izz.invoke(buzz)
public fun _clearMock() {
_foo.clear()
_bar.clear()
_ozz.clear()
_izz.clear()
}
}
| 3 |
Kotlin
|
2
| 56 |
9a94e2842f615b08d4e2942c4987278a3d5c9f43
| 1,944 |
kmock
|
Apache License 2.0
|
src/main/kotlin/com/flohrauer/endurabackend/workouttemplate/WorkoutTemplateService.kt
|
My-Endura
| 857,694,941 | false |
{"Kotlin": 63513}
|
package com.flohrauer.endurabackend.workouttemplate
import com.flohrauer.endurabackend.exercise.ExerciseService
import com.flohrauer.endurabackend.workouttemplate.dto.AddExerciseRequest
import com.flohrauer.endurabackend.workouttemplate.dto.CreateWorkoutTemplateRequest
import com.flohrauer.endurabackend.workouttemplate.dto.UpdateWorkoutTemplateRequest
import com.flohrauer.endurabackend.workouttemplate.dto.WorkoutTemplateResponse
import com.flohrauer.endurabackend.workouttemplate.exception.ExerciseAlreadyInWorkoutTemplateException
import com.flohrauer.endurabackend.workouttemplate.exception.WorkoutTemplateAlreadyExistsException
import com.flohrauer.endurabackend.workouttemplate.exception.WorkoutTemplateNotFoundException
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.stereotype.Service
import java.util.*
@Service
class WorkoutTemplateService(
private val workoutTemplateRepository: WorkoutTemplateRepository,
private val exerciseService: ExerciseService
) {
fun getAll(): List<WorkoutTemplateResponse> {
val workoutTemplateEntities = workoutTemplateRepository.findAll()
return workoutTemplateEntities.map { it.toResponse() }
}
fun getById(id: UUID): WorkoutTemplateResponse {
return getEntityById(id).toResponse()
}
fun create(createWorkoutTemplateRequest: CreateWorkoutTemplateRequest): WorkoutTemplateResponse {
try {
val exercises = exerciseService.getAllEntitiesByIds(createWorkoutTemplateRequest.exercisesIds)
val workoutTemplateEntity = createWorkoutTemplateRequest.toEntity(exercises.toMutableSet())
val databaseTemplateEntity = workoutTemplateRepository.save(workoutTemplateEntity)
return databaseTemplateEntity.toResponse()
} catch (e: DataIntegrityViolationException) {
throw WorkoutTemplateAlreadyExistsException()
}
}
fun update(id: UUID, updateWorkoutTemplateRequest: UpdateWorkoutTemplateRequest): WorkoutTemplateResponse {
try {
val workoutTemplateEntity = getEntityById(id)
val updatedWorkoutTemplate = workoutTemplateEntity.update(updateWorkoutTemplateRequest)
val databaseWorkoutTemplate = workoutTemplateRepository.save(updatedWorkoutTemplate)
return databaseWorkoutTemplate.toResponse()
} catch (e: DataIntegrityViolationException) {
throw WorkoutTemplateAlreadyExistsException()
}
}
fun delete(id: UUID) {
val workoutTemplateEntity = getEntityById(id)
workoutTemplateRepository.delete(workoutTemplateEntity)
}
fun addExercise(id: UUID, addExerciseRequest: AddExerciseRequest): WorkoutTemplateResponse {
try {
val workoutTemplateEntity = getEntityById(id)
val exerciseEntity = exerciseService.getEntityById(addExerciseRequest.id)
workoutTemplateEntity.exercises.add(exerciseEntity)
return workoutTemplateRepository.save(workoutTemplateEntity).toResponse()
} catch (e: DataIntegrityViolationException) {
throw ExerciseAlreadyInWorkoutTemplateException()
}
}
fun removeExercise(id: UUID, exerciseId: UUID): WorkoutTemplateResponse {
val workoutTemplateEntity = getEntityById(id)
val exerciseEntity = exerciseService.getEntityById(exerciseId)
workoutTemplateEntity.exercises.remove(exerciseEntity)
return workoutTemplateRepository.save(workoutTemplateEntity).toResponse()
}
fun getEntityById(id: UUID): WorkoutTemplate {
return workoutTemplateRepository.findById(id).orElseThrow {
WorkoutTemplateNotFoundException()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
3a5a17ac84e12e518875f02a5e3c87842941ccac
| 3,730 |
endura-backend
|
MIT License
|
safeToRunInternal/src/main/kotlin/io/github/dllewellyn/safetorun/models/models/OsCheckDto.kt
|
Safetorun
| 274,838,056 | false | null |
package com.safetorun.models.models
import kotlinx.serialization.Serializable
@Serializable
/**
* DTO Containing OS information like version, model, board etc
*/
data class OsCheckDto(
var osVersion: String = "",
var manufacturer: String = "",
var model: String = "",
var board: String = "",
var bootloader: String = "",
var cpuAbi: List<String> = emptyList(),
var host: String = "",
var hardware: String = "",
var device: String = "",
)
| 9 |
Kotlin
|
0
| 8 |
501a06497485cb40c2b54f4d2a885fc34bcc1898
| 478 |
safe_to_run
|
Apache License 2.0
|
kotlin-study/src/08-data class.kt
|
tanyiqu
| 327,886,682 | false | null |
data class Person(val name: String) {
var age: Int = 0
}
fun main() {
val person1 = Person("John")
val person2 = Person("John")
person1.age = 10
person2.age = 20
// 为true 因为只会比较 name属性
println("person1 == person2: ${person1 == person2}")
println("person1 with age ${person1.age}: ${person1}")
println("person2 with age ${person2.age}: ${person2}")
val person3 = person2.copy();
println(person3)
}
| 0 |
Kotlin
|
0
| 0 |
312110a27ee47766132da0cb8874bbe6bd352403
| 445 |
study-kotlin
|
MIT License
|
src/main/kotlin/com/forum/springboot/forum3API/models/TherapySession.kt
|
BraveWorm
| 602,570,714 | false | null |
package com.forum.springboot.forum3API.models
import com.fasterxml.jackson.annotation.JsonFormat
import java.util.*
import javax.persistence.*
@Entity
class TherapySession(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false) var id: Long? = null,
@Column() var status: String? = null,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
@Column() var startOfTherapySession: Date? = null,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
@Column() var endOfTherapySession: Date? = null,
@ManyToMany(mappedBy = "userTherapySessions")
val userTherapySession: MutableList<User> = mutableListOf(),
@OneToOne
@JoinColumn private val payment: Payment?,
)
| 0 |
Kotlin
|
0
| 0 |
a88a178a723004f4641a75d55efc085a3747336b
| 811 |
Forum3Api
|
MIT License
|
app/src/main/java/com/example/polycareer/data/database/model/UsersAnswersEntity.kt
|
SummerPractice
| 375,694,632 | false |
{"Kotlin": 124251}
|
package com.example.polycareer.data.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
@Entity(
tableName = "users_answers",
primaryKeys = ["user_id", "answer_id", "try_number"],
foreignKeys = [ForeignKey(
entity = UserEntity::class,
parentColumns = ["id"],
childColumns = ["user_id"]
),
ForeignKey(
entity = AnswersEntity::class,
parentColumns = ["id"],
childColumns = ["answer_id"]
)]
)
data class UsersAnswersEntity(
@ColumnInfo(name = "user_id") val userId: Long,
@ColumnInfo(name = "answer_id", index = true) val answerId: Long,
@ColumnInfo(name = "try_number") val tryNumber: Long = 0,
@ColumnInfo val time: Long
)
| 0 |
Kotlin
|
0
| 1 |
14941023ef84eeb11dd60906c8162e163a0e8650
| 766 |
a
|
MIT License
|
libraries/stdlib/jvm/builtins/CharSequence.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin
/**
* Represents a readable sequence of [Char] values.
*/
public actual interface CharSequence {
/**
* Returns the length of this character sequence.
*/
public actual val length: Int
/**
* Returns the character at the specified [index] in this character sequence.
*
* @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this character sequence.
*
* Note that the [String] implementation of this interface in Kotlin/JS has unspecified behavior
* if the [index] is out of its bounds.
*/
public actual operator fun get(index: Int): Char
/**
* Returns a new character sequence that is a subsequence of this character sequence,
* starting at the specified [startIndex] and ending right before the specified [endIndex].
*
* @param startIndex the start index (inclusive).
* @param endIndex the end index (exclusive).
*/
public actual fun subSequence(startIndex: Int, endIndex: Int): CharSequence
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,239 |
kotlin
|
Apache License 2.0
|
app/src/main/java/soy/gabimoreno/audioclean/framework/extension/ActivityExtension.kt
|
soygabimoreno
| 266,280,006 | false |
{"Kotlin": 63351, "CMake": 1598}
|
package soy.gabimoreno.audioclean.framework.extension
import android.app.Activity
import android.widget.Toast
import soy.gabimoreno.audioclean.BuildConfig
fun Activity.toast(message: Int, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
fun Activity.debugToast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
if (BuildConfig.DEBUG) Toast.makeText(this, message, duration).show()
}
| 0 |
Kotlin
|
0
| 9 |
624e2a5622e9da3bf46ecbf980db5a6621ce99f4
| 443 |
AudioClean
|
Apache License 2.0
|
feature-dashboard/src/main/java/com/ofalvai/habittracker/feature/dashboard/ui/habitdetail/ActionCountChart.kt
|
ofalvai
| 324,148,039 | false |
{"Kotlin": 572182, "Just": 767}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ofalvai.habittracker.feature.dashboard.ui.habitdetail
import androidx.compose.animation.*
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.airbnb.android.showkase.annotation.ShowkaseComposable
import com.ofalvai.habittracker.core.ui.theme.PreviewTheme
import com.ofalvai.habittracker.feature.dashboard.ui.model.ActionCountChart
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlin.math.max
private const val MinBarHeight = 0.02f
private val BarWidth = 32.dp
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun ActionCountChart(
values: ImmutableList<ActionCountChart.ChartItem>,
modifier: Modifier = Modifier
) {
if (values.isEmpty()) {
return
}
// Reverse items and use reverseLayout = true to initially scroll to end
val reversedItems = remember(values) { values.reversed() }
AnimatedContent(
targetState = reversedItems,
transitionSpec = { fadeIn(animationSpec = tween(300, delayMillis = 150)) with fadeOut() },
contentAlignment = Alignment.BottomCenter
) { items ->
val maxValue = items.maxByOrNull { it.value }!!.value
LazyRow(
modifier = modifier.height(200.dp).fillMaxWidth(),
reverseLayout = true
) {
itemsIndexed(items) { index, chartItem ->
Column(
modifier = Modifier.padding(horizontal = 4.dp).fillMaxHeight()
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.Bottom,
) {
val value = chartItem.value
val heightRatio = if (maxValue > 0) value / maxValue.toFloat() else 0f
val isEven = index % 2 == 0
Text(
modifier = Modifier.width(BarWidth).padding(top = 8.dp, bottom = 4.dp),
text = value.toString(),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodySmall
)
val background = if (isEven) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary
Box(
modifier = Modifier
.background(background, shape = RoundedCornerShape(4.dp))
.fillMaxHeight(fraction = max(MinBarHeight, heightRatio))
.width(BarWidth)
)
}
Text(
modifier = Modifier.width(BarWidth).padding(top = 4.dp),
text = chartItem.label,
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodySmall
)
}
}
}
}
}
@Preview
@ShowkaseComposable(name = "Action count chart", group = "Habit details", styleName = "Months")
@Composable
fun PreviewActionCountChartMonths() {
PreviewTheme {
ActionCountChart(
persistentListOf(
ActionCountChart.ChartItem("6", 2021, 15),
ActionCountChart.ChartItem("7", 2021, 0),
ActionCountChart.ChartItem("8", 2021, 7),
ActionCountChart.ChartItem("9", 2021, 5),
ActionCountChart.ChartItem("10", 2021, 19)
)
)
}
}
@Preview
@ShowkaseComposable(name = "Action count chart", group = "Habit details", styleName = "Weeks")
@Composable
fun PreviewActionCountChartMonth() {
PreviewTheme {
ActionCountChart(
persistentListOf(
ActionCountChart.ChartItem("W22", 2021, 0),
ActionCountChart.ChartItem("W33", 2021, 1),
ActionCountChart.ChartItem("W44", 2021, 2),
ActionCountChart.ChartItem("W55", 2021, 3),
ActionCountChart.ChartItem("W66", 2021, 4),
ActionCountChart.ChartItem("W77", 2021, 5),
ActionCountChart.ChartItem("W88", 2021, 6),
ActionCountChart.ChartItem("W99", 2021, 7),
ActionCountChart.ChartItem("W10", 2021, 8)
)
)
}
}
@Preview
@ShowkaseComposable(name = "Action count chart", group = "Habit details", styleName = "Empty")
@Composable
fun PreviewActionCountChartEmpty() {
PreviewTheme {
ActionCountChart(
persistentListOf(
ActionCountChart.ChartItem("2", 2021, 0),
ActionCountChart.ChartItem("3", 2021, 0),
ActionCountChart.ChartItem("4", 2021, 0),
ActionCountChart.ChartItem("5", 2021, 0),
ActionCountChart.ChartItem("6", 2021, 0),
ActionCountChart.ChartItem("7", 2021, 0),
ActionCountChart.ChartItem("8", 2021, 0),
ActionCountChart.ChartItem("9", 2021, 0),
ActionCountChart.ChartItem("10", 2021, 0)
)
)
}
}
| 21 |
Kotlin
|
3
| 98 |
6b7ac6117063d39649ac80ed23b5cd926edcd027
| 6,392 |
HabitBuilder
|
Apache License 2.0
|
app/src/main/java/com/example/to_docompose/presentation/screens/task/TaskScreen.kt
|
vluk4
| 508,537,821 | false |
{"Kotlin": 73194}
|
package com.example.to_docompose.presentation.screens.task
import android.annotation.SuppressLint
import android.content.Context
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.material.Scaffold
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import com.example.to_docompose.data.models.Priority
import com.example.to_docompose.data.models.ToDoTask
import com.example.to_docompose.presentation.viewmodel.SharedViewModel
import com.example.to_docompose.util.Action
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun TaskScreen(
selectedTask: ToDoTask?,
sharedViewModel: SharedViewModel,
navigateToListScreen: (Action) -> Unit
) {
val title: String by sharedViewModel.title
val description: String by sharedViewModel.description
val priority: Priority by sharedViewModel.priority
val context = LocalContext.current
BackHandler {
navigateToListScreen(Action.NO_ACTION)
}
Scaffold(
topBar = {
TaskAppBar(
selectedTask = selectedTask,
navigateToListScreen = { action ->
if (action == Action.NO_ACTION) {
navigateToListScreen(action)
} else {
if (sharedViewModel.validateFields()) {
navigateToListScreen(action)
} else {
displayToast(context = context)
}
}
}
)
},
content = {
TaskContent(
title = title,
onTitleChange = {
sharedViewModel.updateTitle(it)
},
description = description,
onDescriptionChange = {
sharedViewModel.description.value = it
},
priority = priority,
onPrioritySelected = {
sharedViewModel.priority.value = it
}
)
}
)
}
fun displayToast(context: Context) {
Toast.makeText(context, "Fields Empty", Toast.LENGTH_SHORT).show()
}
@Composable
fun BackHandler(
backDispatcher: OnBackPressedDispatcher? =
LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher,
onBackPressed: () -> Unit
) {
val currentOnBackPressed by rememberUpdatedState(newValue = onBackPressed)
val backCallback = remember {
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
currentOnBackPressed()
}
}
}
DisposableEffect(key1 = backDispatcher) {
backDispatcher?.addCallback(backCallback)
onDispose {
backCallback.remove()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
7b8cf2920025074b2ae034dd6ccc99f54e0ec783
| 3,004 |
ToDoComposeApp
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.