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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
analysis/src/org/jetbrains/kotlin/idea/references/KtArrayAccessReferenceDescriptorsImpl.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2021 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.idea.references
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.kotlin.psi.KtImportAlias
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_GET
import org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_SET
internal class KtArrayAccessReferenceDescriptorsImpl(
expression: KtArrayAccessExpression
) : KtArrayAccessReference(expression), KtDescriptorsBasedReference {
override fun handleElementRename(newElementName: String): PsiElement = renameImplicitConventionalCall(newElementName)
override fun isReferenceToImportAlias(alias: KtImportAlias): Boolean {
return super<KtDescriptorsBasedReference>.isReferenceToImportAlias(alias)
}
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
val getFunctionDescriptor = context[INDEXED_LVALUE_GET, expression]?.candidateDescriptor
val setFunctionDescriptor = context[INDEXED_LVALUE_SET, expression]?.candidateDescriptor
return listOfNotNull(getFunctionDescriptor, setFunctionDescriptor)
}
}
| 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 1,475 | intellij-kotlin | Apache License 2.0 |
decoder/wasm/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/wasm/decoder/section/index/BinaryLabelIndexDecoder.kt | CharlieTap | 743,980,037 | false | {"Kotlin": 1667685, "WebAssembly": 75136} | package io.github.charlietap.chasm.decoder.wasm.decoder.section.index
import com.github.michaelbull.result.Result
import io.github.charlietap.chasm.ast.module.Index
import io.github.charlietap.chasm.decoder.wasm.error.WasmDecodeError
import io.github.charlietap.chasm.decoder.wasm.reader.WasmBinaryReader
internal fun BinaryLabelIndexDecoder(
reader: WasmBinaryReader,
): Result<Index.LabelIndex, WasmDecodeError> = BinaryIndexDecoder(reader, Index::LabelIndex)
| 2 | Kotlin | 2 | 43 | 4cb170e73e120a15de6397ad24d2f23c1fae3f87 | 468 | chasm | Apache License 2.0 |
app/src/main/java/com/yelai/wearable/ui/course/CourseDetailActivity.kt | xlhlivy | 160,481,777 | false | null | package com.yelai.wearable.ui.course
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewPager
import cn.droidlover.xdroidmvp.router.Router
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.yelai.wearable.R
import com.yelai.wearable.base.BaseActivity
import com.yelai.wearable.contract.CourseContract
import com.yelai.wearable.entity.TabEntity
import com.yelai.wearable.load
import com.yelai.wearable.model.CourseTimeDetail
import com.yelai.wearable.model.Page
import com.yelai.wearable.model.Student
import com.yelai.wearable.present.PCourse
import kotlinx.android.synthetic.main.course_activity_detail.*
/**
* Created by xuhao on 2017/12/1.
* desc:搜索功能
*/
class CourseDetailActivity : BaseActivity<CourseContract.Presenter>(), CourseContract.View{
override fun getLayoutId(): Int = R.layout.course_activity_detail
// private var name: String? = null
// // 签到(0:未签到 1:已签到 2:请假)
// private var signed: Int = 0//签到
//
// // abnormal:异常(0:否 1:是)
// private var abnormal: Int = 0//异常
//
// private var memberId: Int = 0//
//
// private var heart: Int = 0//
override fun success(type: CourseContract.Success, data: Any) {
if(type == CourseContract.Success.CourseTimeDetail){
data as CourseTimeDetail
initViewWithData(data)
bulletinBoard.notice(data.notice)
studentsFragment.courseTimeDetail = data
// var list = ArrayList<Student>()
//
// var i = 0
// do {
// list.add(Student().apply {
// name = "张三娃${i}"
// signed = 0
// abnormal = 0
// memberId = i
// heart = i * 10
// })
// }while (++i < 20)
studentsFragment.list(Page<List<Student>>().apply {
pages = 1
currPage = 1
count = 1
[email protected] = data.students
})
}
}
private fun initViewWithData(data:CourseTimeDetail){
when(data.type){
"1"->{
tvCourseType.text = "教学课"
tvCourseType.setBackgroundResource(R.drawable.day_right_circle_green_background)
ivBackground.load(R.drawable.course_item_background_banner1)
}
"2"->{
tvCourseType.text = "训练课"
tvCourseType.setBackgroundResource(R.drawable.day_right_circle_orange_background)
ivBackground.load(R.drawable.course_item_background_banner2)
}
"3"->{
tvCourseType.text = "兴趣课"
tvCourseType.setBackgroundResource(R.drawable.day_right_circle_red_background)
ivBackground.load(R.drawable.course_item_background_banner3)
}
else->{
tvCourseType.text = "训练课"
tvCourseType.setBackgroundResource(R.drawable.day_right_circle_orange_background)
ivBackground.load(R.drawable.course_item_background_banner2)
}
}
ivBackground.load(data.img)
tvCourseName.text = data.title
tvCourseDetail.text = "课次: ${data.number}/${data.times}"
tvCourseTime.text = "上课时间: ${data.time_str}"
tvAssign.text = "${data.signed}"
tvExceptionCnt.text = "${data.abnormal}"
tvStep.text = "${data.step}"
}
private val mFragments = ArrayList<Fragment>()
private val mTitles = arrayOf("公告栏", "学生列表")
private val mTabEntities = ArrayList<CustomTabEntity>()
private val timesId by lazy{intent.extras.getString("timesId")}
private val bulletinBoard by lazy{
CourseBulletinBoardFragment.newInstance()
}
private val studentsFragment by lazy {
StudentsFragment.newInstance()
}
override fun initData(savedInstanceState: Bundle?) {
mToolbar.setMiddleText("课程详情", ContextCompat.getColor(this, R.color.text_black_color))
showToolbar()
for (i in mTitles.indices) {
mTabEntities.add(TabEntity(mTitles[i],0, 0))
}
mFragments.add(bulletinBoard)
mFragments.add(studentsFragment)
viewPager.adapter = MyPagerAdapter(supportFragmentManager)
initViewpager()
p.courseTimesDetail(timesId)
}
private fun initViewpager(){
tabLayout.setTabData(mTabEntities)
tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
override fun onTabSelect(position: Int) {
viewPager.currentItem = position
}
override fun onTabReselect(position: Int) {
if (position == 0) {
// tabLayout.showMsg(0, 2)
// UnreadMsgUtils.show(mTabLayout_2.getMsgView(0), mRandom.nextInt(100) + 1)
}
}
})
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
tabLayout.currentTab = position
}
override fun onPageScrollStateChanged(state: Int) {
}
})
viewPager.offscreenPageLimit = 2
viewPager.currentItem = 0
}
override fun newP(): PCourse = PCourse()
private inner class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getCount(): Int {
return mFragments.size
}
override fun getPageTitle(position: Int): CharSequence? {
return mTitles[position]
}
override fun getItem(position: Int): Fragment {
return mFragments[position]
}
}
companion object {
fun launch(activity: Context,timesId:String) {
Router.newIntent(activity as Activity)
.to(CourseDetailActivity::class.java)
.putString("timesId",timesId)
.launch()
}
}
}
| 1 | null | 1 | 1 | 2c681c92a3c062dc387bc3b927643c5c3ef34695 | 6,475 | AiSportsTeacher | MIT License |
app/src/main/java/com/app/nikhil/coroutinedownloader/utils/FileUtils.kt | nikhilbansal97 | 198,953,655 | false | null | package com.app.nikhil.coroutinedownloader.utils
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import okio.BufferedSink
import okio.buffer
import okio.sink
import timber.log.Timber
import java.io.File
import java.net.URI
class FileUtils(private val context: Context) {
companion object {
private const val MIME_TYPE_VIDEO = "video"
private const val MIME_TYPE_AUDIO = "audio"
private const val MIME_TYPE_IMAGE = "image"
}
private val contentResolver: ContentResolver by lazy { context.contentResolver }
fun getFilePath(url: String): String {
val fileName = getFileName(url)
val fileExtension = getFileExtension(url)
val externalDir = context.getExternalFilesDir(fileExtension)
return externalDir?.path + fileName
}
fun getFileUri(url: String, mimeType: String?): Uri? {
return insertIntoAppropriateMediaStore(url, mimeType)
}
@SuppressLint("InlinedApi")
private fun insertIntoAppropriateMediaStore(url: String, mimeType: String?): Uri? {
return when {
mimeType == null -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val collectionUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI
val contentValues = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, getFileName(url))
put(MediaStore.Downloads.IS_PENDING, 1)
}
contentResolver.safeInsert(collectionUri, contentValues)
} else {
val collectionUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentValues = ContentValues().apply {
put(MediaStore.Files.FileColumns.DISPLAY_NAME, getFileName(url))
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
}
contentResolver.safeInsert(collectionUri, contentValues)
}
}
mimeType.contains(MIME_TYPE_VIDEO) -> {
val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
val contentValues = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME, getFileName(url))
put(MediaStore.Video.Media.IS_PENDING, 1)
}
val cursor = contentResolver.query(
Uri.parse("$collectionUri"),
arrayOf(MediaStore.Video.VideoColumns.DISPLAY_NAME),
null,
null
)
Timber.d("Got cursor $cursor")
cursor?.let { cursor ->
val nameIndex = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DISPLAY_NAME)
Timber.d("Cursor has nameIndex $nameIndex")
while (cursor.moveToNext()) {
Timber.d("Cursor has next()")
val name = cursor.getString(nameIndex)
Timber.d("Got $name in MediaStore!")
}
Timber.d("Cursor access completed")
}
contentResolver.insert(collectionUri, contentValues)
}
mimeType.contains(MIME_TYPE_IMAGE) -> {
val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, getFileName(url))
put(MediaStore.Images.Media.IS_PENDING, 1)
}
contentResolver.safeInsert(collectionUri, contentValues)
}
mimeType.contains(MIME_TYPE_AUDIO) -> {
val collectionUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
val contentValues = ContentValues().apply {
put(MediaStore.Audio.Media.DISPLAY_NAME, getFileName(url))
put(MediaStore.Audio.Media.IS_PENDING, 1)
}
contentResolver.safeInsert(collectionUri, contentValues)
}
else -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val collectionUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI
val contentValues = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, getFileName(url))
put(MediaStore.Downloads.IS_PENDING, 1)
}
contentResolver.safeInsert(collectionUri, contentValues)
} else {
val collectionUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentValues = ContentValues().apply {
put(MediaStore.Files.FileColumns.DISPLAY_NAME, getFileName(url))
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
}
contentResolver.safeInsert(collectionUri, contentValues)
}
}
}
}
fun getFileName(url: String): String {
val uri = URI.create(url)
val path = uri.path
val index = path.indexOfLast { it == '/' }
if (index != -1) {
return path.substring(index + 1)
}
return "Noname"
}
private fun getFileExtension(url: String): String {
val fileName = getFileName(url)
val index = fileName.indexOfLast { it == '.' }
if (index != -1) {
return fileName.substring(index + 1)
}
return ""
}
fun getFileSize(fileName: String): Long {
val file = File(context.getExternalFilesDir(null), fileName)
return if (file.exists()) file.length() else 0
}
fun getNewBufferedSink(uri: Uri): BufferedSink? {
return contentResolver.openOutputStream(uri)?.sink()?.buffer()
}
fun downloadCompleted(uri: String) {
val finalUri = Uri.parse(uri) ?: return
val contentValues: ContentValues = createDownloadCompleteContentValues(finalUri)
contentResolver.update(finalUri, contentValues, null, null)
}
@SuppressLint("InlinedApi")
private fun createDownloadCompleteContentValues(uri: Uri): ContentValues {
return ContentValues().apply {
put(MediaStore.Video.Media.IS_PENDING, 0)
}
}
} | 0 | Kotlin | 1 | 9 | b6b6ea59e043b0847beb9f3803e501e17429ab01 | 6,322 | CoroutineDownloader | Apache License 2.0 |
pensjon-brevbaker/src/test/kotlin/no/nav/pensjon/brev/fixtures/OrienteringOmRettigheterUfoereDto.kt | navikt | 375,334,697 | false | null | package no.nav.pensjon.brev.fixtures
import no.nav.pensjon.brev.api.model.*
import no.nav.pensjon.brev.api.model.vedlegg.OrienteringOmRettigheterUfoereDto
fun createOrienteringOmRettigheterUfoereDto() =
OrienteringOmRettigheterUfoereDto(
bruker_borINorge = false,
harTilleggForFlereBarn = true,
institusjon_gjeldende = Institusjon.INGEN,
avdoed_sivilstand = Sivilstand.ENSLIG,
harInnvilgetBarnetillegg = true,
) | 0 | Kotlin | 2 | 0 | 49e27874bf9b0f20df4c4411405b7434f49f58bc | 461 | pensjonsbrev | MIT License |
dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/persistence/file/advanced/ConsentAwareFileMigrator.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.core.internal.persistence.file.advanced
import androidx.annotation.WorkerThread
import com.datadog.android.core.internal.persistence.file.FileMover
import com.datadog.android.core.internal.persistence.file.FileOrchestrator
import com.datadog.android.privacy.TrackingConsent
import com.datadog.android.v2.api.InternalLogger
import java.util.concurrent.ExecutorService
import java.util.concurrent.RejectedExecutionException
internal class ConsentAwareFileMigrator(
private val fileMover: FileMover,
private val executorService: ExecutorService,
private val internalLogger: InternalLogger
) : DataMigrator<TrackingConsent> {
@WorkerThread
override fun migrateData(
previousState: TrackingConsent?,
previousFileOrchestrator: FileOrchestrator,
newState: TrackingConsent,
newFileOrchestrator: FileOrchestrator
) {
val operation = when (previousState to newState) {
null to TrackingConsent.PENDING,
null to TrackingConsent.GRANTED,
null to TrackingConsent.NOT_GRANTED,
TrackingConsent.PENDING to TrackingConsent.NOT_GRANTED -> {
WipeDataMigrationOperation(
previousFileOrchestrator.getRootDir(),
fileMover,
internalLogger
)
}
TrackingConsent.GRANTED to TrackingConsent.PENDING,
TrackingConsent.NOT_GRANTED to TrackingConsent.PENDING -> {
WipeDataMigrationOperation(
newFileOrchestrator.getRootDir(),
fileMover,
internalLogger
)
}
TrackingConsent.PENDING to TrackingConsent.GRANTED -> {
MoveDataMigrationOperation(
previousFileOrchestrator.getRootDir(),
newFileOrchestrator.getRootDir(),
fileMover,
internalLogger
)
}
TrackingConsent.PENDING to TrackingConsent.PENDING,
TrackingConsent.GRANTED to TrackingConsent.GRANTED,
TrackingConsent.GRANTED to TrackingConsent.NOT_GRANTED,
TrackingConsent.NOT_GRANTED to TrackingConsent.NOT_GRANTED,
TrackingConsent.NOT_GRANTED to TrackingConsent.GRANTED -> {
NoOpDataMigrationOperation()
}
else -> {
internalLogger.log(
InternalLogger.Level.WARN,
targets = listOf(
InternalLogger.Target.MAINTAINER,
InternalLogger.Target.TELEMETRY
),
"Unexpected consent migration from $previousState to $newState"
)
NoOpDataMigrationOperation()
}
}
try {
@Suppress("UnsafeThirdPartyFunctionCall") // NPE cannot happen here
executorService.submit(operation)
} catch (e: RejectedExecutionException) {
internalLogger.log(
InternalLogger.Level.ERROR,
InternalLogger.Target.MAINTAINER,
DataMigrator.ERROR_REJECTED,
e
)
}
}
}
| 33 | Kotlin | 39 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 3,537 | dd-sdk-android | Apache License 2.0 |
aesi/src/main/kotlin/com/virtlink/editorservices/structureoutline/IStructureOutlineConfiguration.kt | Virtlink | 90,153,785 | false | {"Git Config": 1, "Diff": 1, "Markdown": 1139, "Text": 2, "Ignore List": 19, "Makefile": 3, "YAML": 3, "Gradle": 21, "INI": 6, "Kotlin": 221, "Handlebars": 1, "Shell": 1, "ANTLR": 2, "XML": 5, "Maven POM": 7, "JAR Manifest": 4, "Java": 60, "Gemfile.lock": 1, "Ruby": 1, "SCSS": 1, "JSON with Comments": 2, "JSON": 6} | package com.virtlink.editorservices.structureoutline
interface IStructureOutlineConfiguration {
// Empty
} | 1 | null | 1 | 1 | f7af2531913d9809f3429c0d8e3a82fb695d5ba4 | 111 | aesi | Apache License 2.0 |
quetrucazo/app/src/main/java/com/utnmobile/quetrucazo/model/Ronda.kt | UTN-FRBA-Mobile | 793,528,407 | false | {"Kotlin": 75448, "TypeScript": 75180, "Dockerfile": 433} | package com.utnmobile.quetrucazo.model
class Ronda {
private var numeroRonda: Int
private var arrancaJugador1: Boolean
private var esTurnoJugador1: Boolean
private var cartasJugadasJugador1: List<Carta>
private var cartasJugadasJugador2: List<Carta>
constructor(numeroRonda: Int, arrancaJugador1: Boolean, esTurnoJugador1: Boolean, cartasJugadasJugador1: List<Carta>, cartasJugadasJugador2: List<Carta>) {
this.numeroRonda = numeroRonda
this.arrancaJugador1 = arrancaJugador1
this.esTurnoJugador1 = esTurnoJugador1
this.cartasJugadasJugador1 = cartasJugadasJugador1
this.cartasJugadasJugador2 = cartasJugadasJugador2
}
fun cartaGanadora(carta1: Carta, carta2: Carta){
if (carta1.valorCarta() < carta2.valorCarta()){
println(carta1.toString())
} else if (carta1.valorCarta() > carta2.valorCarta()){
println(carta2.toString())
} else{
println("EMPATE")
}
}
} | 0 | Kotlin | 0 | 0 | 78567979f0e980ee5e720a150270b47d081b121f | 1,006 | QueTrucazo | MIT License |
app/src/main/java/com/oguzdogdu/wallieshd/presentation/latest/LatestWallpaperAdapter.kt | oguzsout | 616,912,430 | false | {"Kotlin": 456497} | package com.oguzdogdu.wallieshd.presentation.latest
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.oguzdogdu.domain.model.latest.LatestImage
import com.oguzdogdu.wallieshd.core.BasePagingDataAdapter
import com.oguzdogdu.wallieshd.databinding.ItemMainImageBinding
import com.oguzdogdu.wallieshd.util.loadImage
class LatestWallpaperAdapter :
BasePagingDataAdapter<LatestImage, LatestWallpaperAdapter.MainImageViewHolder>() {
inner class MainImageViewHolder(private val binding: ItemMainImageBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(wallpaper: LatestImage?) {
binding.apply {
imageViewItemWallpaper.loadImage(url = wallpaper?.url)
root.setOnClickListener {
onItemClickListener?.let {
it(wallpaper)
}
}
}
}
}
override fun createViewHolder(parent: ViewGroup): MainImageViewHolder {
return MainImageViewHolder(
ItemMainImageBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun bindViewHolder(holder: MainImageViewHolder, item: LatestImage) {
holder.bind(item)
}
}
| 0 | Kotlin | 0 | 8 | 88456612d6a87b23a253f5b1df495d1c7ca0449a | 1,378 | Wallies | MIT License |
terra-classic-core/src/commonMain/kotlin/terra/vesting/v1beta1/vesting.converter.kt | jdekim43 | 759,720,689 | false | {"Kotlin": 8940168, "Java": 3242559} | // Transform from terra/vesting/v1beta1/vesting.proto
@file:GeneratorVersion(version = "0.3.1")
package terra.vesting.v1beta1
import google.protobuf.Any
import java.lang.IllegalStateException
import kr.jadekim.protobuf.`annotation`.GeneratorVersion
import kr.jadekim.protobuf.converter.ProtobufConverter
import kr.jadekim.protobuf.converter.parseProtobuf
public expect object LazyGradedVestingAccountConverter : ProtobufConverter<LazyGradedVestingAccount>
public fun LazyGradedVestingAccount.toAny(): Any = Any(LazyGradedVestingAccount.TYPE_URL,
with(LazyGradedVestingAccountConverter) { toByteArray() })
public fun Any.parse(converter: ProtobufConverter<LazyGradedVestingAccount>):
LazyGradedVestingAccount {
if (typeUrl != LazyGradedVestingAccount.TYPE_URL) throw
IllegalStateException("Please check the type_url")
return value.parseProtobuf(converter)
}
public expect object ScheduleConverter : ProtobufConverter<Schedule>
public fun Schedule.toAny(): Any = Any(Schedule.TYPE_URL, with(ScheduleConverter) { toByteArray() })
public fun Any.parse(converter: ProtobufConverter<Schedule>): Schedule {
if (typeUrl != Schedule.TYPE_URL) throw IllegalStateException("Please check the type_url")
return value.parseProtobuf(converter)
}
public expect object VestingScheduleConverter : ProtobufConverter<VestingSchedule>
public fun VestingSchedule.toAny(): Any = Any(VestingSchedule.TYPE_URL,
with(VestingScheduleConverter) { toByteArray() })
public fun Any.parse(converter: ProtobufConverter<VestingSchedule>): VestingSchedule {
if (typeUrl != VestingSchedule.TYPE_URL) throw IllegalStateException("Please check the type_url")
return value.parseProtobuf(converter)
}
| 0 | Kotlin | 0 | 0 | eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc | 1,702 | chameleon.proto | Apache License 2.0 |
app/src/main/java/com/i/crypto/di/AppModule.kt | hdmor | 757,415,570 | false | {"Kotlin": 29319} | package com.i.crypto.di
import com.i.crypto.common.Constants
import com.i.crypto.data.remote.CoinPaprikaApi
import com.i.crypto.data.repository.CoinRepositoryImpl
import com.i.crypto.domain.repository.CoinRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideCoinPaprikaApi(): CoinPaprikaApi =
Retrofit.Builder().baseUrl(Constants.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build().create(CoinPaprikaApi::class.java)
@Provides
@Singleton
fun provideCoinRepository(api: CoinPaprikaApi): CoinRepository = CoinRepositoryImpl(api)
} | 0 | Kotlin | 0 | 0 | c9f3babe1a89ad8d287170bd90795e2848dd105d | 867 | iCrypto | MIT License |
app/src/main/java/com/droid47/petpot/workmanagers/SyncPetTypeWorker.kt | AndroidKiran | 247,345,176 | false | null | package com.droid47.petpot.workmanagers
import android.app.Application
import android.content.Context
import androidx.work.*
import com.droid47.petpot.base.widgets.Failure
import com.droid47.petpot.launcher.domain.interactors.SyncPetTypeUseCase
import io.reactivex.Single
import java.util.concurrent.TimeUnit
import javax.inject.Inject
private val REQUEST_TAG = SyncPetTypeWorker::class.java.simpleName
private val IMMEDIATE_REQUEST_TAG = "${REQUEST_TAG}_IMMEDIATE"
private val PERIODIC_REQUEST_TAG = "${REQUEST_TAG}_PERIODIC"
class SyncPetTypeWorker @Inject constructor(
application: Application,
workerParameters: WorkerParameters,
private val syncPetTypeUseCase: SyncPetTypeUseCase
) : RxWorker(application, workerParameters) {
override fun createWork(): Single<Result> =
syncPetTypeUseCase.buildUseCaseSingleWithSchedulers(false)
.map {
when (it) {
is Failure -> Result.failure()
else -> Result.success()
}
}.onErrorReturn {
Result.failure()
}
companion object {
private val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.METERED)
.build()
private val periodicRequest = PeriodicWorkRequest.Builder(
SyncPetTypeWorker::class.java,
15,
TimeUnit.DAYS,
PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS,
TimeUnit.MINUTES
).setConstraints(constraints)
.addTag(PERIODIC_REQUEST_TAG)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
PeriodicWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
).build()
fun enqueuePeriodicRequest(context: Context) {
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
PERIODIC_REQUEST_TAG,
ExistingPeriodicWorkPolicy.KEEP,
periodicRequest
)
}
private val request = OneTimeWorkRequest.Builder(SyncPetTypeWorker::class.java)
.setConstraints(constraints)
.addTag(IMMEDIATE_REQUEST_TAG)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
WorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
).build()
fun enqueueRequest(context: Context) {
WorkManager.getInstance(context).enqueueUniqueWork(
IMMEDIATE_REQUEST_TAG,
ExistingWorkPolicy.REPLACE,
request
)
}
fun getOneTimeRequestStatus(context: Context) =
WorkManager.getInstance(context).getWorkInfosForUniqueWorkLiveData(REQUEST_TAG)
}
} | 1 | null | 1 | 2 | 07d9c0c4f0d5bef32d9705f6bb49f938ecc456e3 | 2,789 | PetPot | Apache License 2.0 |
app/src/main/java/io/marlon/cleanarchitecture/ui/mvp/user/UserPresenter.kt | marloncarvalho | 110,142,579 | false | null | package io.marlon.cleanarchitecture.ui.mvp.user
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.OnLifecycleEvent
import io.marlon.cleanarchitecture.domain.exception.ModelNotFound
import io.marlon.cleanarchitecture.domain.model.User
import io.marlon.cleanarchitecture.domain.usecase.user.GetUserDetails
import io.marlon.cleanarchitecture.ui.mvp.BasePresenter
import io.marlon.cleanarchitecture.ui.mvp.ViewErrorHandler
import timber.log.Timber
import javax.inject.Inject
class UserPresenter @Inject constructor(
private val eh: ViewErrorHandler,
private val getUser: GetUserDetails) : BasePresenter<UserContract.View>(), UserContract.Presenter {
override fun loadUser(user: String) {
view.showLoading()
getUser.execute(
params = user,
onNext = { onGetUser(it) },
onError = { onGetUserError(it) }
)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
override fun destroy() {
getUser.clear()
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
override fun init() {
Timber.d("Initializing View. OnResume event.")
}
private fun onGetUserError(throwable: Throwable) {
Timber.d("Error loading user!")
view.hideLoading()
if (!eh.handle(view, throwable)) {
if (throwable is ModelNotFound) {
view.showError("User not found.")
}
}
}
private fun onGetUser(user: User) {
Timber.d("OnNext -> Presenter got an user! ${user.login}, ${user.name}, ${user.id}")
view.showUser(user!!)
view.hideLoading()
}
} | 0 | Kotlin | 0 | 0 | 613153498ffb28813652526a5a829ed64f71a1fa | 1,659 | android-clean-architecture | MIT License |
stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/ParticipantState.kt | GetStream | 505,572,267 | false | {"Kotlin": 2549850, "MDX": 279508, "Python": 18285, "Shell": 4455, "JavaScript": 1112, "PureBasic": 107} | /*
* Copyright (c) 2014-2023 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-video-android/blob/main/LICENSE
*
* 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.getstream.video.android.core
import androidx.compose.runtime.Stable
import io.getstream.result.Result
import io.getstream.video.android.core.internal.InternalStreamVideoApi
import io.getstream.video.android.core.model.AudioTrack
import io.getstream.video.android.core.model.MediaTrack
import io.getstream.video.android.core.model.NetworkQuality
import io.getstream.video.android.core.model.Reaction
import io.getstream.video.android.core.model.VideoTrack
import io.getstream.video.android.core.model.VisibilityOnScreenState
import io.getstream.video.android.core.utils.combineStates
import io.getstream.video.android.core.utils.mapState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.openapitools.client.models.MuteUsersResponse
import org.threeten.bp.Instant
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.ZoneOffset
import stream.video.sfu.models.Participant
import stream.video.sfu.models.TrackType
/**
* Represents the state of a participant in a call.
*
* * A list of participants is shared when you join a call the SFU send you the participant joined event.
*
*/
@Stable
public data class ParticipantState(
/** The SFU returns a session id for each participant. This session id is unique */
var sessionId: String = "",
/** The call object */
val call: Call,
/** The current version of the user, this is the start for participant.user stateflow */
private val initialUserId: String,
/** A prefix to identify tracks, internal */
@InternalStreamVideoApi
var trackLookupPrefix: String = "",
) {
val isLocal by lazy {
sessionId == call.session?.sessionId
}
/** video track */
internal val _videoTrack = MutableStateFlow<VideoTrack?>(null)
val videoTrack: StateFlow<VideoTrack?> = _videoTrack
internal val _visibleOnScreen = MutableStateFlow(VisibilityOnScreenState.UNKNOWN)
val visibleOnScreen: StateFlow<VisibilityOnScreenState> = _visibleOnScreen
/**
* State that indicates whether the camera is capturing and sending video or not.
*/
// todo: videoAvailable might be more descriptive
internal val _videoEnabled: MutableStateFlow<Boolean> = MutableStateFlow(false)
val videoEnabled: StateFlow<Boolean> = _videoEnabled
/**
* State that indicates whether the mic is capturing and sending the audio or not.
*/
internal val _audioEnabled: MutableStateFlow<Boolean> = MutableStateFlow(false)
val audioEnabled: StateFlow<Boolean> = _audioEnabled
internal val _audioTrack = MutableStateFlow<AudioTrack?>(null)
val audioTrack: StateFlow<AudioTrack?> = _audioTrack
internal val _screenSharingEnabled: MutableStateFlow<Boolean> = MutableStateFlow(false)
val screenSharingEnabled: StateFlow<Boolean> = _screenSharingEnabled
internal val _screenSharingTrack = MutableStateFlow<VideoTrack?>(null)
val screenSharingTrack: StateFlow<VideoTrack?> = _screenSharingTrack
internal val _name = MutableStateFlow("")
val name: StateFlow<String> = _name
internal val _image = MutableStateFlow("")
val image: StateFlow<String> = _image
internal val _userId = MutableStateFlow(initialUserId)
val userId: StateFlow<String> = _userId
// Could also be a property on the user
val userNameOrId: StateFlow<String> = _name.mapState { it.ifEmpty { _userId.value } }
/**
* When you joined the call
*/
internal val _joinedAt: MutableStateFlow<OffsetDateTime?> = MutableStateFlow(null)
val joinedAt: StateFlow<OffsetDateTime?> = _joinedAt
/**
* The audio level of the participant, single float value
*/
internal val _audioLevel: MutableStateFlow<Float> = MutableStateFlow(0f)
val audioLevel: StateFlow<Float> = _audioLevel
/**
* The last 5 values for the audio level. This list easier to work with for some audio visualizations
*/
internal val _audioLevels: MutableStateFlow<List<Float>> =
MutableStateFlow(listOf(0f, 0f, 0f, 0f, 0f))
val audioLevels: StateFlow<List<Float>> = _audioLevels
/**
* The video quality of the participant
*/
internal val _networkQuality: MutableStateFlow<NetworkQuality> =
MutableStateFlow(NetworkQuality.UnSpecified())
val networkQuality: StateFlow<NetworkQuality> = _networkQuality
internal val _dominantSpeaker: MutableStateFlow<Boolean> = MutableStateFlow(false)
val dominantSpeaker: StateFlow<Boolean> = _dominantSpeaker
internal val _speaking: MutableStateFlow<Boolean> = MutableStateFlow(false)
val speaking: StateFlow<Boolean> = _speaking
internal val _lastSpeakingAt: MutableStateFlow<OffsetDateTime?> = MutableStateFlow(null)
val lastSpeakingAt: StateFlow<OffsetDateTime?> = _lastSpeakingAt
internal val _reactions = MutableStateFlow<List<Reaction>>(emptyList())
val reactions: StateFlow<List<Reaction>> = _reactions
val video: StateFlow<Video?> = combineStates(_videoTrack, _videoEnabled) { track, enabled ->
Video(
sessionId = sessionId,
track = track,
enabled = enabled,
)
}
val audio: StateFlow<Audio?> = combineStates(_audioTrack, _audioEnabled) { track, enabled ->
Audio(
sessionId = sessionId,
track = track,
enabled = enabled,
)
}
val screenSharing: StateFlow<ScreenSharing?> =
combineStates(_screenSharingTrack, _screenSharingEnabled) { track, enabled ->
ScreenSharing(
sessionId = sessionId,
track = track,
enabled = enabled,
)
}
suspend fun muteAudio(): Result<MuteUsersResponse> {
// how do i mute another user?
return call.muteUser(_userId.value, audio = true, video = false, screenShare = false)
}
suspend fun muteVideo(): Result<MuteUsersResponse> {
return call.muteUser(_userId.value, audio = false, video = true, screenShare = false)
}
suspend fun muteScreenshare(): Result<MuteUsersResponse> {
return call.muteUser(_userId.value, audio = false, video = false, screenShare = true)
}
suspend fun pin() {
return call.state.pin(this.userId.value, this.sessionId)
}
suspend fun unpin() {
return call.state.unpin(this.sessionId)
}
fun updateAudioLevel(audioLevel: Float) {
val currentAudio = _audioLevels.value.toMutableList()
currentAudio.removeAt(0)
currentAudio.add(audioLevel)
if (currentAudio[0] == 0f && currentAudio[2] == 0f) {
currentAudio[0] = audioLevel
currentAudio[2] = audioLevel
}
_audioLevels.value = currentAudio.toList()
_audioLevel.value = audioLevel
}
internal val _roles = MutableStateFlow<List<String>>(emptyList())
val roles: StateFlow<List<String>> = _roles
fun updateFromParticipantInfo(participant: Participant) {
sessionId = participant.session_id
val joinedAtMilli =
participant.joined_at?.toEpochMilli() ?: OffsetDateTime.now().toEpochSecond()
val instant = Instant.ofEpochSecond(joinedAtMilli)
_joinedAt.value = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC)
trackLookupPrefix = participant.track_lookup_prefix
_networkQuality.value = NetworkQuality.fromConnectionQuality(participant.connection_quality)
_speaking.value = participant.is_speaking
// _dominantSpeaker.value = participant.is_dominant_speaker. we ignore this and only handle the event
updateAudioLevel(participant.audio_level)
_audioEnabled.value = participant.published_tracks.contains(TrackType.TRACK_TYPE_AUDIO)
_videoEnabled.value = participant.published_tracks.contains(TrackType.TRACK_TYPE_VIDEO)
_screenSharingEnabled.value =
participant.published_tracks.contains(TrackType.TRACK_TYPE_SCREEN_SHARE)
_roles.value = participant.roles
_name.value = participant.name
_image.value = participant.image
}
public fun consumeReaction(reaction: Reaction) {
val newReactions = _reactions.value.toMutableList()
newReactions.remove(reaction)
_reactions.value = newReactions
}
@Stable
public sealed class Media(
public open val sessionId: String,
public open val track: MediaTrack?,
public open val enabled: Boolean,
public val type: TrackType = TrackType.TRACK_TYPE_UNSPECIFIED,
)
@Stable
public data class Video(
public override val sessionId: String,
public override val track: VideoTrack?,
public override val enabled: Boolean,
) : Media(
sessionId = sessionId,
track = track,
enabled = enabled,
type = TrackType.TRACK_TYPE_VIDEO,
)
@Stable
public data class Audio(
public override val sessionId: String,
public override val track: AudioTrack?,
public override val enabled: Boolean,
) : Media(
sessionId = sessionId,
track = track,
enabled = enabled,
type = TrackType.TRACK_TYPE_AUDIO,
)
@Stable
public data class ScreenSharing(
public override val sessionId: String,
public override val track: VideoTrack?,
public override val enabled: Boolean,
) : Media(
sessionId = sessionId,
track = track,
enabled = enabled,
type = TrackType.TRACK_TYPE_SCREEN_SHARE,
)
}
| 3 | Kotlin | 30 | 308 | 1c67906e4c01e480ab180f30b39f341675bc147e | 10,169 | stream-video-android | FSF All Permissive License |
kandy-api/src/main/kotlin/org/jetbrains/kotlinx/kandy/dsl/internal/DataFramePlotContext.kt | Kotlin | 502,039,936 | false | {"Kotlin": 1556423} | /*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.kandy.dsl.internal
import org.jetbrains.kotlinx.dataframe.*
import org.jetbrains.kotlinx.dataframe.api.getColumns
import org.jetbrains.kotlinx.dataframe.api.groupBy
import org.jetbrains.kotlinx.dataframe.columns.ColumnReference
import org.jetbrains.kotlinx.kandy.ir.data.NamedData
import org.jetbrains.kotlinx.kandy.ir.feature.FeatureName
import org.jetbrains.kotlinx.kandy.ir.feature.PlotFeature
/**
* Represents a standard plotting context initialized with a [DataFrame] as its primary dataset.
* The class allows the seamless integration of the dataframe's columns into the plotting process.
* It also provides convenient methods for grouping data and creating grouped contexts.
*
* The implemented [ColumnsContainer] interface is delegated to the [dataFrame],
* enabling the user to leverage the columns of the dataframe directly in the plotting process.
*
* @param dataFrame the initial dataframe that this plotting context operates upon.
*
* @property _plotContext the underlying plot context, typically set to 'this' instance.
* @property datasetHandlers a mutable list of handlers for managing datasets.
* @property plotFeatures a mutable map representing various plot features.
*/
public class DataFramePlotContext<T>(
@PublishedApi
internal val dataFrame: DataFrame<T>
) : LayerPlotContext(), ColumnsContainer<T> by dataFrame {
override val _plotContext: PlotContext = this
override val datasetHandlers: MutableList<DatasetHandler> = mutableListOf(
DatasetHandler(NamedData(dataFrame))
)
override val plotFeatures: MutableMap<FeatureName, PlotFeature> = mutableMapOf()
/**
* Fetches the specified columns from the dataframe.
*
* @param selector a selector to determine the columns to be fetched.
* @return a list of selected data columns.
*/
public fun <C> columns(selector: ColumnsSelector<T, C>): List<DataColumn<C>> = dataFrame.get(selector)
/**
* Fetches the specified columns from the dataframe by their names.
*
* @param columns names of the desired columns.
* @return a list of selected data columns.
*/
public fun <C> columns(vararg columns: String): List<AnyCol> = dataFrame.getColumns(*columns)
/**
* Creates and initializes a new context with the dataframe grouped by the specified column names.
*
* @param columns the column names to group the dataframe by.
* @param block a lambda with receiver block that configures the new grouped context.
*/
public inline fun groupBy(
columns: Iterable<String>,
block: GroupedContext<T, T>.() -> Unit
) {
val groupBy = dataFrame.groupBy(*columns.toList().toTypedArray())
GroupedContext(
groupBy,
datasetHandler.buffer,
this
).apply(block)
}
/**
* Creates and initializes a new context with the dataframe grouped by the specified column names.
*
* @param columns the column names to group the dataframe by.
* @param block a lambda with receiver block that configures the new grouped context.
*/
public inline fun groupBy(
vararg columns: String,
block: GroupedContext<T, T>.() -> Unit
): Unit = groupBy(columns.toList(), block)
/**
* Creates and initializes a new context with the dataframe grouped by the given column references.
*
* @param columnReferences references to the columns to group by.
* @param block a lambda with receiver block that configures the new grouped context.
*/
public inline fun groupBy(
vararg columnReferences: ColumnReference<*>,
block: GroupedContext<T, T>.() -> Unit
): Unit = groupBy(columnReferences.map { it.name() }, block)
/**
* Creates and initializes a new context with the dataframe grouped by the given column references.
*
* @param columnReferences a list of references to the columns to group by.
* @param block a lambda with receiver block that configures the new grouped context.
*/
public inline fun groupBy(
columnReferences: List<ColumnReference<*>>,
block: GroupedContext<T, T>.() -> Unit
): Unit = groupBy(columnReferences.map { it.name() }, block)
} | 123 | Kotlin | 11 | 522 | 2764bce7e9eec4888fdce71b306631cd4e0a208c | 4,391 | kandy | Apache License 2.0 |
components/membership/registration-impl/src/main/kotlin/net/corda/membership/impl/registration/dynamic/mgm/MGMRegistrationContextValidator.kt | corda | 346,070,752 | false | null | package net.corda.membership.impl.registration.dynamic.mgm
import net.corda.configuration.read.ConfigurationGetService
import net.corda.membership.impl.registration.dynamic.verifiers.OrderVerifier
import net.corda.membership.impl.registration.dynamic.verifiers.P2pEndpointVerifier
import net.corda.membership.lib.grouppolicy.GroupPolicyConstants.PolicyValues.P2PParameters.TlsType
import net.corda.membership.lib.grouppolicy.GroupPolicyConstants.PolicyValues.P2PParameters.SessionPkiMode.NO_PKI
import net.corda.membership.lib.schema.validation.MembershipSchemaValidationException
import net.corda.membership.lib.schema.validation.MembershipSchemaValidatorFactory
import net.corda.schema.membership.MembershipSchema
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.v5.base.versioning.Version
internal class MGMRegistrationContextValidator(
private val membershipSchemaValidatorFactory: MembershipSchemaValidatorFactory,
private val orderVerifier: OrderVerifier = OrderVerifier(),
private val p2pEndpointVerifier: P2pEndpointVerifier = P2pEndpointVerifier(orderVerifier),
private val configurationGetService: ConfigurationGetService,
) {
private companion object {
const val errorMessageTemplate = "No %s was provided."
val errorMessageMap = errorMessageTemplate.run {
mapOf(
SESSION_KEY_ID to format("session key"),
ECDH_KEY_ID to format("ECDH key"),
REGISTRATION_PROTOCOL to format("registration protocol"),
SYNCHRONISATION_PROTOCOL to format("synchronisation protocol"),
P2P_MODE to format("P2P mode"),
SESSION_KEY_POLICY to format("session key policy"),
PKI_SESSION to format("session PKI property"),
PKI_TLS to format("TLS PKI property"),
)
}
}
@Suppress("ThrowsCount")
@Throws(MGMRegistrationContextValidationException::class)
fun validate(context: Map<String, String>) {
try {
validateContextSchema(context)
validateContext(context)
} catch (ex: MembershipSchemaValidationException) {
throw MGMRegistrationContextValidationException(
"Onboarding MGM failed. ${ex.message}",
ex
)
} catch (ex: IllegalArgumentException) {
throw MGMRegistrationContextValidationException(
"Onboarding MGM failed. ${ex.message ?: "Reason unknown."}",
ex
)
} catch (ex: Exception) {
throw MGMRegistrationContextValidationException(
"Onboarding MGM failed. Unexpected error occurred during context validation. ${ex.message}",
ex
)
}
}
@Throws(MembershipSchemaValidationException::class)
private fun validateContextSchema(context: Map<String, String>) {
membershipSchemaValidatorFactory
.createValidator()
.validateRegistrationContext(
MembershipSchema.RegistrationContextSchema.Mgm,
Version(1, 0),
context
)
}
@Throws(IllegalArgumentException::class)
@Suppress("ThrowsCount")
private fun validateContext(context: Map<String, String>) {
for (key in errorMessageMap.keys) {
context[key] ?: throw IllegalArgumentException(errorMessageMap[key])
}
p2pEndpointVerifier.verifyContext(context)
if (context[PKI_SESSION] != NO_PKI.toString()) {
context.keys.filter { TRUSTSTORE_SESSION.format("[0-9]+").toRegex().matches(it) }.apply {
require(isNotEmpty()) { "No session trust store was provided." }
require(orderVerifier.isOrdered(this, 4)) { "Provided session trust stores are incorrectly numbered." }
}
}
context.keys.filter { TRUSTSTORE_TLS.format("[0-9]+").toRegex().matches(it) }.apply {
require(isNotEmpty()) { "No TLS trust store was provided." }
require(orderVerifier.isOrdered(this, 4)) { "Provided TLS trust stores are incorrectly numbered." }
}
val contextRegistrationTlsType = context[TLS_TYPE]?.let { tlsType ->
TlsType.fromString(tlsType) ?: throw IllegalArgumentException("Invalid TLS type: $tlsType")
} ?: TlsType.ONE_WAY
val clusterTlsType = TlsType.getClusterType(configurationGetService::getSmartConfig)
if (contextRegistrationTlsType != clusterTlsType) {
throw IllegalArgumentException(
"A cluster with TLS type is $clusterTlsType can not register " +
"MGM with TLS type $contextRegistrationTlsType"
)
}
}
}
internal class MGMRegistrationContextValidationException(
val reason: String,
e: Throwable?
) : CordaRuntimeException(reason, e) | 82 | null | 9 | 28 | fa43ea7a49afb8ed2d1686a6e847c8a02d376f85 | 4,896 | corda-runtime-os | Apache License 2.0 |
appcues/src/test/java/com/appcues/AnalyticsPublisherTest.kt | appcues | 413,524,565 | false | null | package com.appcues
import com.appcues.AnalyticType.EVENT
import com.appcues.AnalyticType.GROUP
import com.appcues.AnalyticType.IDENTIFY
import com.appcues.AnalyticType.SCREEN
import com.appcues.analytics.ActivityRequestBuilder
import com.appcues.analytics.AnalyticsEvent.ScreenView
import com.appcues.analytics.TrackingData
import com.appcues.data.remote.appcues.request.ActivityRequest
import com.appcues.data.remote.appcues.request.EventRequest
import com.appcues.rules.KoinScopeRule
import com.appcues.rules.MainDispatcherRule
import com.google.common.truth.Truth.assertThat
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.koin.core.component.get
import java.util.Date
@OptIn(ExperimentalCoroutinesApi::class)
internal class AnalyticsPublisherTest : AppcuesScopeTest {
@get:Rule
override val koinTestRule = KoinScopeRule()
@get:Rule
val dispatcherRule = MainDispatcherRule()
private lateinit var analyticsPublisher: AnalyticsPublisher
private data class TrackedEventTest(
val type: AnalyticType,
val value: String?,
val properties: Map<String, Any>?,
val isInternal: Boolean,
)
private val eventList: ArrayList<TrackedEventTest> = arrayListOf()
private val testListener: AnalyticsListener = object : AnalyticsListener {
override fun trackedAnalytic(type: AnalyticType, value: String?, properties: Map<String, Any>?, isInternal: Boolean) {
eventList.add(TrackedEventTest(type, value, properties, isInternal))
}
}
@Before
fun setUp() {
analyticsPublisher = AnalyticsPublisher(get())
}
@Test
fun `analyticsPublisher SHOULD sanitize Date objects to Double in properties map`() {
// GIVEN
val dateLong = 1666102372942
val attributes = hashMapOf(
"date" to Date(dateLong),
"map" to hashMapOf<String, Any>(
"date" to Date(dateLong)
),
"list" to listOf<Any>(Date(dateLong))
)
val activity = ActivityRequest(
accountId = "123",
userId = "userId",
events = listOf(EventRequest("event1", attributes = attributes))
)
val data = TrackingData(EVENT, false, activity)
// WHEN
analyticsPublisher.publish(testListener, data)
// THEN
assertThat(eventList).hasSize(1)
with(eventList[0]) {
assertThat(properties).hasSize(3)
assertThat(properties).containsEntry("date", dateLong.toDouble())
assertThat(properties!!["map"] as Map<*, *>).containsEntry("date", dateLong.toDouble())
assertThat(properties["list"] as List<*>).containsExactly(dateLong.toDouble())
}
}
@Test
fun `analyticsListener SHOULD track event WHEN event TrackingData is published`() {
// GIVEN
val attributes = hashMapOf<String, Any>("prop" to 42)
val activity = ActivityRequest(
accountId = "123",
userId = "userId",
events = listOf(EventRequest("event1", attributes = attributes))
)
val data = TrackingData(EVENT, false, activity)
val listener = mockk<AnalyticsListener>(relaxed = true)
// WHEN
analyticsPublisher.publish(listener, data)
// THEN
verify { listener.trackedAnalytic(EVENT, "event1", attributes, false) }
}
@Test
fun `analyticsListener SHOULD track screen WHEN screen TrackingData is published`() {
// GIVEN
val attributes = hashMapOf<String, Any>(ActivityRequestBuilder.SCREEN_TITLE_ATTRIBUTE to "screen1")
val activity = ActivityRequest(
accountId = "123",
userId = "userId",
events = listOf(EventRequest(ScreenView.eventName, attributes = attributes))
)
val data = TrackingData(SCREEN, false, activity)
val listener = mockk<AnalyticsListener>(relaxed = true)
// WHEN
analyticsPublisher.publish(listener, data)
// THEN
verify { listener.trackedAnalytic(SCREEN, "screen1", attributes, false) }
}
@Test
fun `analyticsListener SHOULD track identify WHEN identify TrackingData is published`() {
// GIVEN
val storage: Storage = get()
storage.userId = "userId"
val attributes = hashMapOf<String, Any>("prop" to 42)
val activity = ActivityRequest(
accountId = "123",
userId = storage.userId,
profileUpdate = attributes
)
val data = TrackingData(IDENTIFY, false, activity)
val listener = mockk<AnalyticsListener>(relaxed = true)
// WHEN
analyticsPublisher.publish(listener, data)
// THEN
verify { listener.trackedAnalytic(IDENTIFY, "userId", attributes, false) }
}
@Test
fun `analyticsListener SHOULD track group WHEN group TrackingData is published`() {
// GIVEN
val storage: Storage = get()
storage.groupId = "groupId"
val attributes = hashMapOf<String, Any>("prop" to 42)
val activity = ActivityRequest(
accountId = "123",
userId = "userId",
groupId = storage.groupId,
groupUpdate = attributes
)
val data = TrackingData(GROUP, false, activity)
val listener = mockk<AnalyticsListener>(relaxed = true)
// WHEN
analyticsPublisher.publish(listener, data)
// THEN
verify { listener.trackedAnalytic(GROUP, "groupId", attributes, false) }
}
@Test
fun `analyticsListener SHOULD track internal event WHEN event TrackingData is published AND isInternal equals true`() {
// GIVEN
val attributes = hashMapOf<String, Any>("prop" to 42)
val activity = ActivityRequest(
accountId = "123",
userId = "userId",
events = listOf(EventRequest("event1", attributes = attributes))
)
val data = TrackingData(EVENT, true, activity)
val listener = mockk<AnalyticsListener>(relaxed = true)
// WHEN
analyticsPublisher.publish(listener, data)
// THEN
verify { listener.trackedAnalytic(EVENT, "event1", attributes, true) }
}
}
| 5 | null | 2 | 9 | 944511391b720bf387f86b795630b532b5e1e516 | 6,383 | appcues-android-sdk | MIT License |
app/src/main/java/io/github/nwtgck/piping_phone/MainActivity.kt | nwtgck | 171,876,685 | false | null | package io.github.nwtgck.piping_phone
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.media.*
import android.media.AudioTrack.MODE_STREAM
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import permissions.dispatcher.*
import java.io.BufferedInputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.SecureRandom
import kotlin.math.max
// Create a RecordAudio
// (Play command: play -t raw -r 44100 -e signed -b 16 -c 1 hoge2.rawfile) (command from: https://stackoverflow.com/a/25362384/2885946)
// (from: https://qiita.com/ino-shin/items/214dba25f49fa098402f)
fun createAudioRecord(): AudioRecord {
// Sampling rate (Hz)
val samplingRate = 44100
// Frame rate (fps)
val frameRate = 10
// Audio data size in 1 frame
val oneFrameDataCount = samplingRate / frameRate
// Audio data byte size in 1 frame
// (NOTE: Byte = 8 bit, Short = 16 bit)
val oneFrameSizeInByte = oneFrameDataCount * 2
// Audio data buffer size
// (NOTE: This should be > oneFrameSizeInByte)
// (NOTE: It is necessary to make it larger than the minimum value required by the device)
val audioBufferSizeInByte =
max(oneFrameSizeInByte,
android.media.AudioRecord.getMinBufferSize(
samplingRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
)
)
// Create audio record
val audioRecord = AudioRecord(
MediaRecorder.AudioSource.MIC,
samplingRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
audioBufferSizeInByte
)
return audioRecord
}
fun getPath(fromId: String, toId: String): String {
// TODO: Use SHA256
return "phone/${fromId}-to-${toId}"
}
fun randomConnectId(stringLen: Int): String {
// (from: https://www.baeldung.com/kotlin-random-alphanumeric-string)
val random = SecureRandom()
val charPool : List<Char> = listOf('a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
val randomString = (1..stringLen)
.map { i -> random.nextInt(charPool.size) }
.map(charPool::get)
.joinToString("");
return randomString
}
@RuntimePermissions
class MainActivity : AppCompatActivity() {
companion object {
val CONNECT_ID_PREF_KEY = "CONNECT_ID_PREF_KEY"
val PEER_CONNECT_ID_PREF_KEY = "PEER_CONNECT_ID_PREF_KEY"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get shared preferences
val pref = getSharedPreferences("pref", Context.MODE_PRIVATE)
// Connect ID edit
var connectIdEdit: EditText = findViewById(R.id.connect_id)
// Peer's connect ID edit
var peerConnectIdEdit: EditText = findViewById(R.id.connection_id)
// Connect button
var connectButton: Button = findViewById(R.id.connect_button)
// Save connect-IDs button
val saveConnectIdsButton: Button = findViewById(R.id.save_connect_ids_button)
// Set random connect ID
connectIdEdit.setText(
pref.getString(
CONNECT_ID_PREF_KEY,
randomConnectId(3)
)
)
// Set peer's connect ID
peerConnectIdEdit.setText(
pref.getString(PEER_CONNECT_ID_PREF_KEY, "")
)
// On connect button clicked
connectButton.setOnClickListener {
recordSendReceivePlayAudioWithPermissionCheck()
}
saveConnectIdsButton.setOnClickListener {
// Save connect IDs
pref.edit()
.putString(CONNECT_ID_PREF_KEY, connectIdEdit.text.toString())
.putString(PEER_CONNECT_ID_PREF_KEY, peerConnectIdEdit.text.toString())
.apply()
Toast.makeText(applicationContext, "Connect IDs saved", Toast.LENGTH_LONG).show()
}
}
@NeedsPermission(Manifest.permission.RECORD_AUDIO)
fun recordSendReceivePlayAudio() {
// Server URL edit
var serverUrlEdit: EditText = findViewById(R.id.server_url)
// Connect ID edit
var connectIdEdit: EditText = findViewById(R.id.connect_id)
// Peer's connect ID edit
var peerConnectIdEdit: EditText = findViewById(R.id.connection_id)
// Get server base URL
val serverUrl: String = serverUrlEdit.text.toString()
// Get connect ID
val connectId: String = connectIdEdit.text.toString()
// Get peer's connect ID
val peerConnectId: String = peerConnectIdEdit.text.toString()
// Record and send sound
recordAndSendSound(serverUrl, connectId, peerConnectId)
// Receive and play sound
receiveAndPlaySound(serverUrl, connectId, peerConnectId)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// NOTE: delegate the permission handling to generated function
onRequestPermissionsResult(requestCode, grantResults)
}
@OnShowRationale(Manifest.permission.RECORD_AUDIO)
fun showRationaleForRecordAudio(request: PermissionRequest) {
showRationaleDialog("A phone needs to send your voice to your receiver.", request)
}
@OnPermissionDenied(Manifest.permission.RECORD_AUDIO)
fun onRecordAudioDenied() {
Toast.makeText(this, "record audio denied", Toast.LENGTH_SHORT).show()
}
@OnNeverAskAgain(Manifest.permission.RECORD_AUDIO)
fun onRecordAudioNeverAskAgain() {
Toast.makeText(this, "never_askagain", Toast.LENGTH_SHORT).show()
}
private fun recordAndSendSound(serverUrl: String, connectId: String, peerConnectId: String) {
// (from: https://qiita.com/furu8ma/items/0194a69a50aa62b8aa6c)
val task = @SuppressLint("StaticFieldLeak")
object : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void): Void? {
var con: HttpURLConnection? = null
try {
// Create URL string
// TODO: Construct URL not to use "/" manually
val urlStr = "${serverUrl}/${getPath(connectId, peerConnectId)}"
Log.i("POST urlStr", urlStr)
val url = URL(urlStr)
val con = url.openConnection() as HttpURLConnection
con.requestMethod = "POST"
con.instanceFollowRedirects = false
con.doInput = true
con.doOutput = true
con.allowUserInteraction = true
val audioRecord = createAudioRecord()
Log.i("audioRecord.bufferSizeInFrames", audioRecord.bufferSizeInFrames.toString())
con.setChunkedStreamingMode(audioRecord.bufferSizeInFrames / 2)
con.connect()
// Start recording
audioRecord.startRecording()
val os = con.outputStream
val bytes = ByteArray(audioRecord.bufferSizeInFrames)
var read = 0
while ({read = audioRecord.read(bytes, 0, bytes.size); read}() > 0) {
Log.i("Before Record", "before record")
os.write(bytes, 0, read)
Log.i("Record WRITE", "write ${read} bytes")
Thread.yield()
}
Log.i("Record finish", "POST finished")
} catch (e: Throwable) {
Log.i("error", e.message)
} finally {
con?.disconnect()
}
return null
}
}
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
}
fun receiveAndPlaySound(serverUrl: String, connectId: String, peerConnectId: String) {
// Buffer size for audio track
val bufSize = AudioTrack.getMinBufferSize(
44100,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT
)
// (from: http://ytch.hatenablog.com/entry/2013/07/21/213130)
val audioTrack = AudioTrack(
AudioManager.STREAM_VOICE_CALL,
44100, // TODO: hard code
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufSize,
MODE_STREAM
)
Toast.makeText(applicationContext, "bufSize: "+bufSize.toString(), Toast.LENGTH_LONG).show()
audioTrack.play()
// (from: https://qiita.com/furu8ma/items/0194a69a50aa62b8aa6c)
val getTask = @SuppressLint("StaticFieldLeak")
object : AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void): Void? {
var con: HttpURLConnection? = null
try {
// Create URL string
// TODO: Construct URL not to use "/" manually
val urlStr = "${serverUrl}/${getPath(peerConnectId, connectId)}"
Log.i("urlStr", urlStr)
val url = URL(urlStr)
con = url.openConnection() as HttpURLConnection
con.requestMethod = "GET"
con.instanceFollowRedirects = false
con.doInput = true
con.doOutput = false
con.setChunkedStreamingMode(256)
con.connect()
val iStream = BufferedInputStream(con.inputStream, bufSize)
val bytes = ByteArray(bufSize)
while(true) {
// Fill bytes until getting bytes.size except the last otherwise have noses
var read = 0
var totalRead = 0
do {
read = iStream.read(bytes, totalRead, bytes.size - totalRead)
if(read < 0) break
totalRead += read
} while (totalRead != bytes.size)
audioTrack.write(bytes, 0, totalRead)
Log.i("READ PLAY", "read ${totalRead} bytes")
if(read < 0) break
Thread.yield()
}
Log.i("READ PLAY finish", "GET finished")
} catch (e: Throwable) {
Log.e("error message", "${e?.message}")
} finally {
con?.disconnect()
}
return null
}
}
getTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
}
// (base: https://github.com/permissions-dispatcher/PermissionsDispatcher/blob/95c7286ae4cb42cc6880d4d4031619ac1bacf03b/sample/src/main/java/permissions/dispatcher/sample/MainActivity.java#L107)
private fun showRationaleDialog(messageResId: String, request: PermissionRequest) {
AlertDialog.Builder(this)
.setPositiveButton("Allow", { dialog, which -> request.proceed() })
.setNegativeButton("Deny", { dialog, which -> request.cancel() })
.setCancelable(false)
.setMessage(messageResId)
.show()
}
}
| 6 | Kotlin | 0 | 1 | 692b9337f057f768903d3b70678fc748e47757f2 | 11,808 | piping-phone-android | MIT License |
core/src/commonMain/kotlin/maryk/core/processors/datastore/matchers/IsQualifierMatcher.kt | marykdb | 290,454,412 | false | {"Kotlin": 3292488, "JavaScript": 1004} | package maryk.core.processors.datastore.matchers
import maryk.core.processors.datastore.matchers.FuzzyMatchResult.MATCH
import maryk.core.processors.datastore.matchers.FuzzyMatchResult.NO_MATCH
import maryk.core.processors.datastore.matchers.FuzzyMatchResult.OUT_OF_RANGE
import maryk.core.properties.references.IsPropertyReference
import maryk.lib.extensions.compare.compareToWithOffsetLength
/** Defines a matcher for a qualifier. */
sealed class IsQualifierMatcher
/**
* Defines an exact [qualifier] matcher.
* Optionally set [referencedQualifierMatcher] to match values behind a reference
*/
class QualifierExactMatcher(
val reference: IsPropertyReference<*, *, *>?,
val qualifier: ByteArray,
val referencedQualifierMatcher: ReferencedQualifierMatcher? = null
) : IsQualifierMatcher() {
fun compareTo(qualifier: ByteArray, offset: Int): Int {
return this.qualifier.compareToWithOffsetLength(qualifier, offset)
}
}
enum class FuzzyMatchResult {
NO_MATCH, MATCH, OUT_OF_RANGE
}
/**
* Defines a fuzzy qualifier matcher with [qualifierParts] and in between [fuzzyMatchers]
* Optionally set [referencedQualifierMatcher] to match values behind a reference
*/
class QualifierFuzzyMatcher(
val reference: IsPropertyReference<*, *, *>?,
val qualifierParts: List<ByteArray>,
val fuzzyMatchers: List<IsFuzzyMatcher>,
val referencedQualifierMatcher: ReferencedQualifierMatcher? = null
) : IsQualifierMatcher() {
/** Find first possible match */
fun firstPossible() = qualifierParts.first()
/** Compare current [qualifier] at [offset] */
fun isMatch(qualifier: ByteArray, offset: Int, length: Int = qualifier.size) : FuzzyMatchResult {
var index = offset
val lastIndexPlusOne = offset + length
for ((qIndex, qPart) in qualifierParts.withIndex()) {
for (byte in qPart) {
if (lastIndexPlusOne <= index) { return NO_MATCH }
if (byte != qualifier[index++]) {
// If first part does not match it is out of range. Otherwise, possible matches so no match
return if (qIndex == 0) OUT_OF_RANGE else NO_MATCH
}
}
if (fuzzyMatchers.lastIndex >= qIndex) {
try {
fuzzyMatchers[qIndex].skip {
if (index >= lastIndexPlusOne) {
// So JS skips out.
throw Throwable("0 char encountered")
}
qualifier[index++]
}
} catch (e: Throwable) {
return NO_MATCH
}
}
}
return MATCH
}
}
| 1 | Kotlin | 1 | 8 | 530e0b7f41cc16920b69b7c8adf7b5718733ce2f | 2,743 | maryk | Apache License 2.0 |
src/Day10.kt | ajmfulcher | 573,611,837 | false | {"Kotlin": 24722} | import kotlin.properties.Delegates
fun main() {
fun part1(input: List<String>): Int {
val strength = mutableListOf<Int>()
var xval = 1
var cycle by Delegates.observable(0) { prop, old, new ->
if (new % 40 == 20) strength += new * xval
}
input.forEach { entry ->
when {
entry == "noop" -> cycle += 1
else -> {
cycle += 1
cycle += 1
xval += entry.split(" ")[1].toInt()
}
}
}
return strength.fold(0) { acc, i -> acc + i }
}
fun part2(input: List<String>): Int {
val crt = Array(7) { Array<String>(40) { "" } }
var xval = 1
var cycle by Delegates.observable(-1) { _, _, new ->
val x = new % 40
val y = new / 40
crt[y][x] = if (Math.abs(xval - x) <= 1) "#" else "."
}
input.forEach { entry ->
when {
entry == "noop" -> cycle += 1
else -> {
cycle += 1
cycle += 1
xval += entry.split(" ")[1].toInt()
}
}
}
crt.forEach { line -> println(line.joinToString("")) }
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
println(part1(testInput))
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 1)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 981f6014b09e347241e64ba85e0c2c96de78ef8a | 1,659 | advent-of-code-2022-kotlin | Apache License 2.0 |
androidApp/src/main/java/com/aglushkov/wordteacher/androidApp/general/extensions/StringDesc.kt | soniccat | 302,971,014 | false | null | package com.aglushkov.wordteacher.androidApp.general.extensions
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import dev.icerock.moko.resources.desc.StringDesc
@Composable
fun StringDesc.resolveString() = toString(LocalContext.current) | 0 | Kotlin | 1 | 1 | 1defa8e2973da24f0f313e70c1f5a19595c53e5a | 283 | WordTeacher | MIT License |
net/craftventure/audioserver/packet/PacketID.kt | Craftventure | 770,049,457 | false | {"Kotlin": 3656616, "Java": 684034} | package net.craftventure.audioserver.packet
enum class PacketID(
val id: Int,
val direction: Direction = Direction.OUT
) {
LOGIN(1, Direction.IN),
KICK(2),
CLIENT_ACCEPTED(3),
PING(8, Direction.BOTH),
RELOAD(14),
AREA_DEFINITION(4),
AREA_STATE(5),
SYNC(6),
KEY_VALUE(7),
VOLUME(13, Direction.BOTH),
LOCATION_UPDATE(15),
DISPLAY_AREA_ENTER(18, Direction.IN),
OPERATOR_DEFINITION(19),
OPERATOR_CONTROL_UPDATE(20),
OPERATOR_SLOT_UPDATE(21),
OPERATOR_CONTROL_CLICK(22, Direction.IN),
OPERATOR_RIDE_UPDATE(34),
PARK_PHOTO(23),
PLAYER_LOCATIONS(27),
ADD_MAP_LAYERS(28),
REMOVE_MAP_LAYERS(35),
MARKER_ADD(36),
MARKER_REMOVE(37),
POLYGON_OVERLAY_ADD(38),
POLYGON_OVERLAY_REMOVE(39),
SPATIAL_AUDIO_DEFINITION(29),
SPATIAL_AUDIO_UPDATE(30),
SPATIAL_AUDIO_REMOVE(31),
AREA_REMOVE(32),
BATCH_PACKET(33);
enum class Direction(
val allowsSend: Boolean,
val allowsReceive: Boolean
) {
IN(false, true),
OUT(true, false),
BOTH(true, true)
}
companion object {
fun fromId(id: Int) = values().firstOrNull { it.id == id }
}
}
| 0 | Kotlin | 1 | 21 | 015687ff6687160835deacda57121480f542531b | 1,216 | open-plugin-parts | MIT License |
kotlin-mui/src/main/generated/mui/material/StepConnector.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/material/StepConnector")
@file:JsNonModule
package mui.material
external interface StepConnectorProps :
mui.system.StandardProps,
react.dom.html.HTMLAttributes<org.w3c.dom.HTMLDivElement> {
/**
* Override or extend the styles applied to the component.
*/
var classes: StepConnectorClasses?
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
var sx: mui.system.SxProps<mui.system.Theme>?
}
/**
*
* Demos:
*
* - [Steppers](https://mui.com/components/steppers/)
*
* API:
*
* - [StepConnector API](https://mui.com/api/step-connector/)
*/
@JsName("default")
external val StepConnector: react.FC<StepConnectorProps>
| 12 | Kotlin | 145 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 779 | kotlin-wrappers | Apache License 2.0 |
HTTPShortcuts/app/src/main/java/ch/rmy/android/http_shortcuts/adapters/SelectVariableOptionsAdapter.kt | staticStone | 136,870,061 | true | {"Kotlin": 435889, "Java": 57185} | package ch.rmy.android.http_shortcuts.adapters
import android.view.ViewGroup
import android.widget.TextView
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.realm.models.Option
import ch.rmy.android.http_shortcuts.utils.UUIDUtils
import kotterknife.bindView
class SelectVariableOptionsAdapter : SimpleListAdapter<Option, SelectVariableOptionsAdapter.SelectOptionViewHolder>() {
var options: List<Option>
get() = items
set(value) {
items = value
}
var clickListener: ((Option) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = SelectOptionViewHolder(parent)
override fun getItemId(item: Option) = UUIDUtils.toLong(item.id)
inner class SelectOptionViewHolder(parent: ViewGroup) : SimpleViewHolder<Option>(parent, R.layout.select_option) {
private val label: TextView by bindView(R.id.select_option_label)
override fun updateViews(item: Option) {
label.text = item.label
itemView.setOnClickListener { clickListener?.invoke(item) }
}
}
} | 0 | Kotlin | 0 | 0 | 2570dc75da654c232ea8f778c65116132a447978 | 1,112 | HTTP-Shortcuts | MIT License |
stretchez/src/main/java/me/shangdelu/stretchez/database/StretchExercise.kt | ShangDeLu | 554,451,333 | false | null | package me.shangdelu.stretchez.database
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.*
@Entity
data class StretchExercise (@PrimaryKey(autoGenerate = true) var exerciseID: Int = 0,
//Don't set planID as ForeignKey since template Exercise have no planID,
// and planID cannot be null as ForeignKey
var planID: UUID? = null,
var exerciseName: String = "",
var exerciseDescription: String = "",
var exerciseDuration: Int = 30,
var exerciseLink: String = "",
var orderNumber: Int = -1,
//boolean check parameter for whether an exercise is a template,
//0 means it's not a template, 1 means it is a template
var isTemplate: Int = 0) | 0 | Kotlin | 0 | 0 | e037754e7b34768f745658c5cf51bba721e9f7ec | 969 | StretchEz | Apache License 2.0 |
src/Day01.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | fun main() {
fun part1(input: List<String>): Int {
val list = mutableListOf<Int>()
list.add(0)
for (s in input) {
if (s.isEmpty()) {
list.add(0)
} else {
list[list.lastIndex]+= s.toInt()
}
}
return list.max()
}
fun part2(input: List<String>): Int {
val list = mutableListOf<Int>()
list.add(0)
for (s in input) {
if (s.isEmpty()) {
list.add(0)
} else {
list[list.lastIndex]+= s.toInt()
}
}
list.sortDescending()
return list.take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 962 | AoC-2022 | Apache License 2.0 |
app/src/androidTest/java/com/drondon/myweather/data/CityWeatherDaoTest.kt | m1r0n41k | 155,295,959 | false | null | /*
* Copyright 2017-2018 the original author or authors.
*
* 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.
*
* Created by - <NAME> on 11/1/18 3:31 AM
*
* Last modified 11/1/18 3:31 AM
*/
package com.drondon.myweather.data
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.drondon.myweather.comon.TestUtils
import com.drondon.myweather.comon.lambdaMock
import com.drondon.myweather.comon.lifecycle
import com.drondon.myweather.comon.owner
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import org.koin.test.KoinTest
import org.mockito.Mockito.verify
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
@RunWith(AndroidJUnit4::class)
class CityWeatherDaoTest : KoinTest {
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
private var appDataBase: AppDataBase? = null
private var dao: CityWeatherDao? = null
@Before
fun setUp() {
appDataBase = AppDataBase.buildDatabase(ApplicationProvider.getApplicationContext(), true)
dao = appDataBase!!.cityWeatherDao()
}
@After
fun tearDown() {
appDataBase?.close()
}
@Test
fun insertAll() {
assertNotNull(appDataBase)
val dao = this.dao
assertNotNull(dao)
val list = listOf(TestUtils.createCityWeather(1))
dao.insertAll(list)
val allLiveData = dao.getAll()
val observer = lambdaMock<(List<CityWeather>) -> Unit>()
allLiveData.observe(lifecycle().owner(), Observer { observer(it) })
//Check invocation
verify(observer).invoke(list)
val value = allLiveData.value
assertNotNull(value)
assertEquals(1, value.size)
}
@Test
fun delete() {
assertNotNull(appDataBase)
val dao = this.dao
assertNotNull(dao)
val list = listOf(TestUtils.createCityWeather(1))
dao.insertAll(list)
val allLiveData = dao.getAll()
val observer = lambdaMock<(List<CityWeather>) -> Unit>()
allLiveData.observe(lifecycle().owner(), Observer { observer(it) })
//Check invocation
verify(observer).invoke(list)
val value = allLiveData.value
assertNotNull(value)
assertEquals(1, value.size)
//Delete all from table
dao.delete(list)
val valueAfterDelete = allLiveData.value
assertNotNull(valueAfterDelete)
assertEquals(0, valueAfterDelete.size)
}
} | 0 | Kotlin | 0 | 0 | d360273a1308c2612dae91dd95419f72561635a4 | 3,213 | MyWeather | Apache License 2.0 |
app/src/main/java/com/yadaniil/bitcurve/logic/AccountsManager.kt | yadaniyil | 122,737,451 | false | null | package com.yadaniil.bitcurve.logic
import com.yadaniil.bitcurve.Application
import com.yadaniil.bitcurve.data.Repository
import com.yadaniil.bitcurve.data.db.models.AccountEntity
import com.google.common.collect.ImmutableList
import org.bitcoinj.core.Address
import org.bitcoinj.core.NetworkParameters
import org.bitcoinj.crypto.ChildNumber
import org.bitcoinj.wallet.DeterministicKeyChain
import org.bitcoinj.wallet.KeyChain
import org.bitcoinj.wallet.Wallet
/**
* Created by danielyakovlev on 1/29/18.
*/
class AccountsManager(private val repo: Repository) {
private var accounts: MutableList<Account>? = null
private var params: NetworkParameters
private val INITIAL_LOOKAHEAD = 20
init {
accounts = ArrayList()
params = WalletHelper.params
}
fun sync(btcWallet: Wallet?) {
repo.getAllAccounts().forEach { addAccount(it, btcWallet) }
}
// region Accounts
fun getAllAccounts() = accounts?.toList() ?: emptyList()
fun addAccount(accountEntity: AccountEntity, wallet: Wallet?) {
val coinType = if (Application.isTestnet) {
ChildNumber(1, true)
} else {
when (accountEntity.coinType) {
Bitcoin().name -> ChildNumber.ZERO_HARDENED
BitcoinCash().name -> ChildNumber(BitcoinCash().coinPath, true)
Litecoin().name -> ChildNumber(Litecoin().coinPath, true)
else -> ChildNumber.ZERO_HARDENED
}
}
val accountPath = ImmutableList.of(
ChildNumber(44, true),
coinType,
ChildNumber(accountEntity.accountId.toInt(), true))
val keyChain = DeterministicKeyChain(wallet?.keyChainSeed, accountPath)
wallet?.addAndActivateHDChain(keyChain)
addAccount(accountEntity, keyChain)
}
private fun addAccount(accountEntity: AccountEntity, keyChain: DeterministicKeyChain) {
if (keyChain.lookaheadSize < accountEntity.lastIssuedReceiveAddressIndex) {
keyChain.lookaheadSize = accountEntity.lastIssuedReceiveAddressIndex
keyChain.maybeLookAhead()
}
val account = Account(accountEntity, keyChain)
initAddressesForAccount(account)
accounts?.add(account)
}
fun getIdForNewAccount(coinType: String): Long {
val accounts = getAllAccounts().filter { it.accountEntity.coinType == coinType }
if (accounts.isEmpty()) return 0
return accounts.last().accountEntity.accountId.plus(1)
}
fun getAccountById(accountId: Long) =
accounts?.find { it.accountEntity.accountId == accountId }
fun getAccountByEntityId(accountEntityId: Long) =
accounts?.find { it.accountEntity.id == accountEntityId }
fun deleteAllAccounts() {
accounts?.clear()
repo.deleteAllAccounts()
}
// endregion Accounts
// region Addresses
private fun initAddressesForAccount(account: Account) {
val receiveAddresses: MutableList<Address> = ArrayList()
val receiveDeterministicKeys = account.keyChain
.getKeys(KeyChain.KeyPurpose.RECEIVE_FUNDS, INITIAL_LOOKAHEAD)
receiveDeterministicKeys.forEach {
receiveAddresses += it.toAddress(params)
}
val changeAddresses: MutableList<Address> = ArrayList()
val changeDeterministicKeys = account.keyChain
.getKeys(KeyChain.KeyPurpose.CHANGE, INITIAL_LOOKAHEAD)
changeDeterministicKeys.forEach {
changeAddresses += it.toAddress(params)
}
account.receiveAddresses = receiveAddresses.toList()
account.changeAddresses = changeAddresses.toList()
}
fun getCurrentReceiveAddressOfAccount(accountEntityId: Long): Address? {
val account = getAccountByEntityId(accountEntityId)
return account?.let { it.receiveAddresses[it.accountEntity.lastIssuedReceiveAddressIndex] }
}
@Throws(FullGapLimitException::class)
fun getFreshReceiveAddressOfAccount(accountEntityId: Long): Address? {
val account = getAccountByEntityId(accountEntityId)
val newLastIssuedReceiveAddressIndex = account?.accountEntity
?.lastIssuedReceiveAddressIndex?.plus(1) ?: 0
// Check if gap limit will be exceeded
try {
account?.let { it.receiveAddresses[newLastIssuedReceiveAddressIndex] }
} catch (e: IndexOutOfBoundsException) {
throw FullGapLimitException()
}
account?.let {
val updatedAccountEntity = it.accountEntity
.copy(lastIssuedReceiveAddressIndex = newLastIssuedReceiveAddressIndex)
repo.updateAccount(updatedAccountEntity)
it.accountEntity = updatedAccountEntity
}
return getCurrentReceiveAddressOfAccount(accountEntityId)
}
// endregion Addresses
}
| 0 | Kotlin | 0 | 0 | 7f592b5501c1fd5dc67ec3857de8d1341c9f81dd | 4,906 | BitCurve | MIT License |
app/src/main/java/cat/xojan/random1/feature/mediaplayback/MediaPlaybackFullScreenActivity.kt | joan-domingo | 62,473,559 | false | null | package cat.xojan.random1.feature.mediaplayback
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.text.format.DateUtils
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.SeekBar
import cat.xojan.random1.R
import cat.xojan.random1.domain.model.EventLogger
import cat.xojan.random1.feature.MediaBrowserProvider
import cat.xojan.random1.feature.MediaPlayerBaseActivity
import cat.xojan.random1.feature.mediaplayback.PlaybackManager.Companion.SET_SLEEP_TIMER
import cat.xojan.random1.feature.mediaplayback.PlaybackManager.Companion.SLEEP_TIMER_LABEL
import cat.xojan.random1.feature.mediaplayback.PlaybackManager.Companion.SLEEP_TIMER_MILLISECONDS
import cat.xojan.random1.feature.mediaplayback.QueueManager.Companion.METADATA_HAS_NEXT_OR_PREVIOUS
import cat.xojan.random1.injection.component.DaggerMediaPlaybackFullScreenComponent
import cat.xojan.random1.injection.component.MediaPlaybackFullScreenComponent
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.synthetic.main.activity_media_playback.*
import javax.inject.Inject
class MediaPlaybackFullScreenActivity : MediaPlayerBaseActivity(),
MediaBrowserProvider, SleepTimeSelectorDialogFragment.Listener {
companion object {
fun newIntent(context: Context): Intent {
return Intent(context, MediaPlaybackFullScreenActivity::class.java)
}
}
private val TAG = MediaPlaybackFullScreenActivity::class.java.simpleName
val component: MediaPlaybackFullScreenComponent by lazy {
DaggerMediaPlaybackFullScreenComponent.builder()
.appComponent(applicationComponent)
.baseActivityModule(activityModule)
.build()
}
@Inject
internal lateinit var eventLogger: EventLogger
private val handler = Handler()
private val updateTimerTask = object : Runnable {
override fun run() {
val controller = MediaControllerCompat
.getMediaController(this@MediaPlaybackFullScreenActivity)
controller?.playbackState?.let {
updateProgress(controller.playbackState)
}
handler.postDelayed(this, 250)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component.inject(this)
setContentView(R.layout.activity_media_playback)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
button_play_pause.setOnClickListener {
val controller = MediaControllerCompat.getMediaController(this)
val playbackState = controller.playbackState
playbackState?.let {
when (playbackState.state) {
PlaybackStateCompat.STATE_PLAYING -> {
controller.transportControls.pause()
}
PlaybackStateCompat.STATE_PAUSED -> {
controller.transportControls.play()
}
}
}
}
button_fast_rewind.setOnClickListener {
val controller = MediaControllerCompat.getMediaController(this)
controller.transportControls.rewind()
}
button_previous.setOnClickListener {
val controller = MediaControllerCompat.getMediaController(this)
controller.transportControls.skipToPrevious()
}
button_next.setOnClickListener {
val controller = MediaControllerCompat.getMediaController(this)
controller.transportControls.skipToNext()
}
button_fast_forward.setOnClickListener {
val controller = MediaControllerCompat.getMediaController(this)
controller.transportControls.fastForward()
}
seek_bar.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
media_timer.text = DateUtils.formatElapsedTime((progress/1000).toLong())
}
override fun onStartTrackingTouch(p0: SeekBar?) {
handler.removeCallbacks(updateTimerTask)
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
handler.removeCallbacks(updateTimerTask)
MediaControllerCompat
.getMediaController(this@MediaPlaybackFullScreenActivity)
.transportControls.seekTo(seekBar.progress.toLong())
handler.postDelayed(updateTimerTask, 100)
}
})
sleep_timer_icon.setOnClickListener {
val dialogFragment = SleepTimeSelectorDialogFragment()
dialogFragment.show(supportFragmentManager, SleepTimeSelectorDialogFragment.TAG)
}
}
override fun onTimeSelected(milliseconds: Long, label: String?) {
val controller = MediaControllerCompat.getMediaController(this)
val bundle = Bundle()
bundle.putLong(SLEEP_TIMER_MILLISECONDS, milliseconds)
bundle.putString(SLEEP_TIMER_LABEL, label)
controller.transportControls.sendCustomAction(SET_SLEEP_TIMER, bundle)
eventLogger.logSleepTimerAction(milliseconds)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
mMediaBrowser.let {
if (mMediaBrowser.isConnected) {
Log.d(TAG, "onStart: connected")
onMediaControllerConnected()
}
}
}
override fun onResume() {
super.onResume()
handler.postDelayed(updateTimerTask, 0)
}
override fun onMediaControllerConnected() {
val controller = MediaControllerCompat.getMediaController(this)
controller?.registerCallback(mCallback)
updateView()
updateDuration(controller.metadata)
}
private fun updateView() {
val controller = MediaControllerCompat.getMediaController(this)
val metadata = controller.metadata
metadata?.let {
title = metadata.description.title
Glide.with(this)
.load(metadata.description?.iconUri)
.apply(RequestOptions().placeholder(R.drawable.placeholder))
.into(podcast_art)
if (metadata.getLong(METADATA_HAS_NEXT_OR_PREVIOUS) == 1L) {
button_next.visibility = View.VISIBLE
button_previous.visibility = View.VISIBLE
} else {
button_next.visibility = View.GONE
button_previous.visibility = View.GONE
}
}
val playbackState = controller.playbackState
playbackState?.let {
when (playbackState.state) {
PlaybackStateCompat.STATE_PLAYING -> {
buffer_progress_bar.visibility = View.GONE
button_play_pause.visibility = View.VISIBLE
button_play_pause.setImageResource(R.drawable.ic_pause)
}
PlaybackStateCompat.STATE_PAUSED -> {
buffer_progress_bar.visibility = View.GONE
button_play_pause.visibility = View.VISIBLE
button_play_pause.setImageResource(R.drawable.ic_play_arrow)
}
PlaybackStateCompat.STATE_BUFFERING -> {
buffer_progress_bar.visibility = View.VISIBLE
button_play_pause.visibility = View.GONE
}
}
val timeInMilliseconds: Long = playbackState.extras
?.getLong(SLEEP_TIMER_MILLISECONDS) ?: 0L
val timerLabel = playbackState.extras?.getString(SLEEP_TIMER_LABEL)
when (timeInMilliseconds) {
0L -> {
sleep_timer_icon.setImageResource(R.drawable.ic_timer_off_white_24px)
sleep_timer.visibility = View.GONE
}
else -> {
sleep_timer.visibility = View.VISIBLE
sleep_timer.text = timerLabel
sleep_timer_icon.setImageResource(R.drawable.ic_timer_white_24px)
}
}
}
}
private fun updateDuration(metadata: MediaMetadataCompat?) {
metadata?.let {
val duration = metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION).toInt()
seek_bar.max = duration
val textDuration = DateUtils.formatElapsedTime(((duration / 1000).toLong()))
media_duration.text = textDuration
}
}
override fun onStop() {
super.onStop()
val controller = MediaControllerCompat.getMediaController(this)
controller?.unregisterCallback(mCallback)
handler.removeCallbacks(updateTimerTask)
}
private fun updateProgress(playbackState: PlaybackStateCompat) {
var currentPosition = playbackState.position
if (playbackState.state == PlaybackStateCompat.STATE_PLAYING) {
// Calculate the elapsed time between the last position update and now and unless
// paused, we can assume (delta * speed) + current position is approximately the
// latest position. This ensure that we do not repeatedly call the getPlaybackState()
// on MediaControllerCompat.
val timeDelta = SystemClock.elapsedRealtime() - playbackState.lastPositionUpdateTime
currentPosition += timeDelta.toInt() * playbackState.playbackSpeed.toLong()
}
seek_bar.progress = currentPosition.toInt()
media_timer.text = DateUtils.formatElapsedTime(currentPosition/1000)
}
private val mCallback = object : MediaControllerCompat.Callback() {
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
super.onMetadataChanged(metadata)
if (metadata == null) {
return
}
updateView()
updateDuration(metadata)
}
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
super.onPlaybackStateChanged(state)
updateView()
}
}
} | 0 | null | 6 | 8 | d8e8a813de7131b0fd0b08e9b10c379a86e76476 | 10,786 | Podcasts-RAC1-Android | MIT License |
compose/integrations/composable-test-cases/testcases/constructors/main/src/commonMain/kotlin/Implementations.kt | JetBrains | 293,498,508 | false | {"Kotlin": 1921608, "Shell": 12615, "Dockerfile": 6720, "JavaScript": 5187, "Swift": 2823, "Ruby": 2627, "Java": 1964, "HTML": 1834, "PowerShell": 1708, "Groovy": 1415} | import androidx.compose.runtime.Composable
class ImplementsHasComposable(
override val composable: @Composable () -> Unit
): HasComposable
class ImplementsHasComposableTyped<T>(
override val composable: @Composable (T) -> Unit
): HasComposableTyped<T>
| 64 | Kotlin | 1174 | 16,150 | 7e9832f6494edf3e7967082c11417e78cfd1d9d0 | 262 | compose-multiplatform | Apache License 2.0 |
app/src/main/java/eu/kanade/presentation/more/settings/SettingsMainScreen.kt | ddmgy | 355,654,262 | true | {"Kotlin": 2406425} | package eu.kanade.presentation.more.settings
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Search
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.stringResource
import eu.kanade.presentation.components.AppBar
import eu.kanade.presentation.components.AppBarActions
import eu.kanade.presentation.components.PreferenceRow
import eu.kanade.presentation.components.Scaffold
import eu.kanade.presentation.components.ScrollbarLazyColumn
import eu.kanade.tachiyomi.R
@Composable
fun SettingsMainScreen(
navigateUp: () -> Unit,
sections: List<SettingsSection>,
onClickSearch: () -> Unit,
) {
Scaffold(
topBar = { scrollBehavior ->
AppBar(
title = stringResource(R.string.label_settings),
navigateUp = navigateUp,
actions = {
AppBarActions(
listOf(
AppBar.Action(
title = stringResource(R.string.action_search),
icon = Icons.Outlined.Search,
onClick = onClickSearch,
),
),
)
},
scrollBehavior = scrollBehavior,
)
},
) { contentPadding ->
ScrollbarLazyColumn(
contentPadding = contentPadding,
) {
sections.map {
item {
PreferenceRow(
title = stringResource(it.titleRes),
painter = it.painter,
onClick = it.onClick,
)
}
}
}
}
}
data class SettingsSection(
@StringRes val titleRes: Int,
val painter: Painter,
val onClick: () -> Unit,
)
| 0 | Kotlin | 2 | 0 | ddd180e56aef69380b1da3137dca8aed590b68e1 | 1,988 | tachiyomi | Apache License 2.0 |
Android/app/src/main/java/ru/alexskvortsov/policlinic/data/system/schedulers/AppSchedulersProvider.kt | AlexSkvor | 244,438,301 | false | null | package ru.alexskvortsov.policlinic.data.system.schedulers
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class AppSchedulersProvider : Scheduler {
override fun ui(): io.reactivex.Scheduler = AndroidSchedulers.mainThread()
override fun computation(): io.reactivex.Scheduler = Schedulers.computation()
override fun trampoline(): io.reactivex.Scheduler = Schedulers.trampoline()
override fun newThread(): io.reactivex.Scheduler = Schedulers.newThread()
override fun io(): io.reactivex.Scheduler = Schedulers.io()
} | 0 | Kotlin | 0 | 0 | 5cc6a10a1399ee08643e69308afd4626938882b0 | 588 | polyclinic | Apache License 2.0 |
graphs/adapter-api/src/main/kotlin/com/anaplan/engineering/azuki/graphs/adapter/api/GraphFunctionalElements.kt | anaplan-engineering | 458,253,960 | false | {"Kotlin": 390046, "Groovy": 6043, "Shell": 1385, "CSS": 957} | package com.anaplan.engineering.azuki.graphs.adapter.api
import com.anaplan.engineering.azuki.core.system.FunctionalElement
import com.anaplan.engineering.azuki.graphs.adapter.api.GraphFunctionalElements.GraphFunction
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class IsA(
val functionalElement: FunctionalElement
)
object GraphFunctionalElements {
const val UndirectedGraph = 1
const val DirectedGraph = 2
const val GraphFunction = 3
}
object GraphFunctions {
@IsA(GraphFunction)
const val HasCycles = 4
@IsA(GraphFunction)
const val GetSimpleCycleCount = 5
}
| 0 | Kotlin | 3 | 2 | e58e832738f9cac8e78ffc482ceefc01c421464a | 641 | azuki | MIT License |
app/src/main/java/com/hyouteki/oasis/fragments/AddFragment.kt | Hyouteki | 673,227,811 | false | null | package com.hyouteki.oasis.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.hyouteki.oasis.activities.MainActivity
import com.hyouteki.oasis.communicators.MainCommunicator
import com.hyouteki.oasis.databinding.FragmentAddBinding
class AddFragment : ModalFragment() {
private lateinit var binding: FragmentAddBinding
private lateinit var communicator: MainCommunicator
companion object {
const val TAG = "ADD_FRAGMENT"
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
binding = FragmentAddBinding.inflate(inflater, container, false)
communicator = activity as MainCommunicator
handleTouches()
return binding.root
}
private fun handleTouches() {
binding.marketplace.setOnClickListener {
communicator.handleMarketplacePostAddAction()
}
}
} | 0 | null | 1 | 2 | 921bc345035e332da43690cb50451fa7a1e8e0c7 | 1,048 | Oasis | MIT License |
telegramClient/src/commonMain/kotlin/pw/binom/telegram/dto/PollAnswer.kt | caffeine-mgn | 309,111,702 | false | null | package pw.binom.telegram.dto
import kotlinx.serialization.Serializable
@Serializable
class PollAnswer{
} | 0 | Kotlin | 0 | 1 | 96d6b59f131371f1fea3a07159c3cf641820568c | 108 | telegramClient | Apache License 2.0 |
app-backend/src/main/kotlin/jooq/main/enums/KugMemberStatusEnum.kt | Heapy | 40,936,978 | false | {"Kotlin": 3311624, "TypeScript": 19032, "Less": 5146, "HTML": 4493, "JavaScript": 2299, "CSS": 2174, "Dockerfile": 243} | /*
* This file is generated by jOOQ.
*/
package link.kotlin.server.jooq.main.enums
import link.kotlin.server.jooq.main.Public
import org.jooq.Catalog
import org.jooq.EnumType
import org.jooq.Schema
/**
* This class is generated by jOOQ.
*/
@Suppress("UNCHECKED_CAST")
enum class KugMemberStatusEnum(@get:JvmName("literal") public val literal: String) : EnumType {
UNAPPROVED("UNAPPROVED"),
APPROVED("APPROVED"),
BANNED("BANNED");
override fun getCatalog(): Catalog? = schema.catalog
override fun getSchema(): Schema = Public.PUBLIC
override fun getName(): String = "kug_member_status_enum"
override fun getLiteral(): String = literal
}
| 21 | Kotlin | 1220 | 11,018 | 2f4cfa75180e759d91fe238cc3f638beec9286e2 | 673 | awesome-kotlin | Apache License 2.0 |
app/src/main/java/uoc/cbonache/tfg/ui/shippingList/ShippingListPresenter.kt | cbonacheuoc | 109,753,411 | true | {"Kotlin": 144808, "Java": 6706} | package uoc.cbonache.tfg.ui.shippingList
import uoc.cbonache.tfg.model.Shipping
import uoc.cbonache.tfg.shippings.GetShippingsListInteractor
import uoc.cbonache.tfg.ui.exception.AndroidExceptionHandler
import uoc.cbonache.tfg.ui.model.mapper.mapToShippingViewEntity
import javax.inject.Inject
/**
* @author cbonache
*/
class ShippingListPresenter @Inject constructor(val view: ShippingListView,
private val getShippingsListInteractor: GetShippingsListInteractor,
private val exceptionHandler: AndroidExceptionHandler) {
fun onStart() {
view.showLoading()
getShippingsListInteractor.execute(Unit){result ->
view.hideLoading()
result.success { shippings ->
if (shippings.isEmpty()) {
view.showNoShippingsWaring()
} else {
view.dismissNoShippingsWarning()
view.showShippingList(shippings.map(Shipping::mapToShippingViewEntity))
}
}
result.failure { exception ->
exceptionHandler.notifyException(view,exception)
}
}
}
fun onShippingPressed(code: String) {
view.navigateToShippingDetail(code)
}
fun onClickQR() {
view.scanQR()
}
} | 0 | Kotlin | 0 | 1 | c6c3cdc87eb96aaf179a6442111371aebe0a80dc | 1,377 | Transpdroid-Android-App | Apache License 2.0 |
andfixdemo/src/main/java/com/liwei/andfixdemo/AndFixPatchManager.kt | liwei49699 | 267,739,678 | false | {"Java": 500011, "Kotlin": 78584, "Smali": 7115, "Shell": 479} | package com.liwei.andfixdemo
class AndfixPatchManager {
} | 1 | null | 1 | 1 | 5ce9094bbfeb86468d560fb29012e0dc29856334 | 58 | OfficeProcess | Apache License 2.0 |
src/main/kotlin/com/github/mkartashev/hserr/miner/artifact/Version.kt | JetBrains | 817,294,168 | false | {"Kotlin": 214924, "Java": 173358, "Lex": 6208} | // Copyright 2024 JetBrains s.r.o. and contributors.
// Use of this source code is governed by the Apache 2.0 license.
package com.github.mkartashev.hserr.miner.artifact
import com.github.mkartashev.hserr.miner.HsErrLog
import com.github.mkartashev.hserr.miner.text.TextRange
import java.time.LocalDate
import java.time.format.DateTimeParseException
class VersionArtifact(
log: HsErrLog,
jreVersionTextRange: TextRange,
jvmVersionTextRange: TextRange,
val buildDate: LocalDate,
val jreVersionFull: String,
val jreVersionBuild: String,
val jvmVersionFull: String,
val jvmVersionBuild: String,
val builtWith: String
) : Artifact(log) {
override val title: String = "JVM/JRE versions"
override val locations by lazy {
setOf(jreVersionTextRange, jvmVersionTextRange).toSortedSet(compareBy { it.start })
}
val jreVersionMajor: Int by lazy {
jreVersionBuild.takeWhile { it.isDigit() }.toInt()
}
private val versionsDiffer: Boolean
get() = jreVersionBuild != jvmVersionBuild
override val comment by lazy {
jvmVersionFull +
if (versionsDiffer) "; JVM and JRE ($jreVersionFull) versions differ, which normally doesn't happen" else ""
}
}
internal object VersionExtractor : ArtifactExtractor<VersionArtifact> {
override fun extract(log: HsErrLog): VersionArtifact {
val header = log.getArtifact(HeaderArtifact::class) ?: fail("No Summary section found")
var jreVersionSelection = header.location.start.moveToLineStartsWithString("# JRE version:").selectUpToEOL()
val jvmVersionSelection = header.location.start.moveToLineStartsWithString("# Java VM:").selectUpToEOL()
// vm_info: OpenJDK 64-Bit Server VM (17.0.6+10-b888.3) for linux-amd64 JRE (17.0.6+10-b888.3), built on 2024-03-17 by "builduser" with gcc 8.3.1 20190311 (Red Hat 8.3.1-3)
val vmInfoSel = log.start.moveToLineStartsWithString("vm_info:").selectUpToEOL()
if (jreVersionSelection.isEmpty() && vmInfoSel.isEmpty()) fail("Couldn't locate JRE version")
if (jvmVersionSelection.isEmpty() && vmInfoSel.isEmpty()) fail("Couldn't locate Java VM version")
var jreVersionBuild = ""
var jreVersionFull = ""
var jvmVersionBuild = ""
var jvmVersionFull = ""
// # JRE version: OpenJDK Runtime Environment JBR-17.0.3+7-469.12-jcef (17.0.3+7) (build 17.0.3+7-b469.12)
val jreVersionTokens = jreVersionSelection.toString().split(' ')
if (jreVersionTokens.size >= 8) {
if (!jreVersionTokens[jreVersionTokens.lastIndex - 1].contains("build")) fail("Couldn't find JRE build number")
jreVersionBuild = jreVersionTokens.lastOrNull()?.trim('(', ')') ?: ""
jreVersionFull =
jreVersionTokens.dropWhile { !it.contains('.') }.firstOrNull()?.trim('(', ')') ?: ""
}
// # Java VM: OpenJDK 64-Bit Server VM JBR-17.0.3+7-469.12-jcef (17.0.3+7-b469.12, mixed mode, tiered, compressed oops, compressed class ptrs, g1 gc, bsd-aarch64)
val jvmVersionTokens = jvmVersionSelection.toString().split(' ')
if (jvmVersionTokens.size >= 9) {
jvmVersionFull = jvmVersionTokens.dropWhile { !it.contains('.') }.firstOrNull()?.trim(',') ?: ""
jvmVersionBuild =
jvmVersionTokens.dropWhile { !it.startsWith('(') }.dropWhile { !it.contains('.') }.firstOrNull()
?.trim('(', ')', ',') ?: ""
}
val vmInfo = vmInfoSel.toString()
if (jreVersionBuild.isEmpty() || jreVersionFull.isEmpty()) {
// try getting from "vm_info:" line
jreVersionBuild = vmInfo.substringAfter("JRE (").substringBefore(')')
jreVersionFull = jreVersionBuild
jreVersionSelection = vmInfoSel
}
jvmVersionFull = jvmVersionFull.trim { it == '(' || it == ')' || it == ',' }
if (jvmVersionBuild.isEmpty() || jvmVersionFull.isEmpty()) {
// try getting from "vm_info:" line
jvmVersionBuild = vmInfo.substringAfter('(').substringBefore(')')
jvmVersionFull = jvmVersionBuild
jreVersionSelection = vmInfoSel
}
val vmInfoBuild = vmInfo.substringAfter("built on ", "")
val buildDateCandidate = vmInfoBuild.substringBefore(' ')
val buildDateString =
if (buildDateCandidate.length >= 10) buildDateCandidate.substring(0, 10) else buildDateCandidate
val buildDate = try {
LocalDate.parse(buildDateString)
} catch (ignored: DateTimeParseException) {
Artifact.DEFAULT_DATE
}
val buildWith = if (vmInfoBuild.contains(" with ")) {
vmInfoBuild.substringAfter(" with ").trim()
} else {
Artifact.DEFAULT_STRING
}
return VersionArtifact(
log,
jreVersionSelection, jvmVersionSelection,
buildDate,
jreVersionFull.trim(), jreVersionBuild.trim(),
jvmVersionFull.trim(), jvmVersionBuild.trim(),
buildWith
)
}
}
| 2 | Kotlin | 2 | 11 | ac0e3b1ee6235b22f4497bf17d4341a281bb85ba | 5,129 | HotSpotCrashExaminerPlugin | Apache License 2.0 |
app/src/main/java/bruhcollective/itaysonlab/abroulette/AbApp.kt | iTaysonLab | 488,246,577 | false | null | package bruhcollective.itaysonlab.abroulette
import android.app.Application
import android.util.Log
import com.topjohnwu.superuser.Shell
class AbApp: Application() {
override fun onCreate() {
super.onCreate()
Log.w("ABRoulette", "ABRoulette ${BuildConfig.VERSION_NAME} by iTaysonLab")
Shell.enableVerboseLogging = BuildConfig.DEBUG
Shell.setDefaultBuilder(Shell.Builder.create().setFlags(Shell.FLAG_REDIRECT_STDERR).setTimeout(10))
}
} | 0 | Kotlin | 0 | 1 | 812d272ffe9cc0b5fbc830fda5c54fd17d155017 | 457 | ABRoulette | Apache License 2.0 |
app/src/main/java/com/project/acehotel/core/domain/auth/usecase/AuthUseCase.kt | AceHotelProject | 732,506,429 | false | {"Kotlin": 762486} | package com.project.acehotel.core.domain.auth.repository
import com.project.acehotel.core.data.source.Resource
import com.project.acehotel.core.domain.auth.model.Auth
import com.project.acehotel.core.domain.auth.model.User
import kotlinx.coroutines.flow.Flow
import okhttp3.MultipartBody
interface IAuthRepository {
fun loginUser(email: String, password: String): Flow<Resource<Auth>>
fun forgetPassword(email: String): Flow<Resource<Int>>
suspend fun insertCacheUser(user: Auth)
fun getUser(): Flow<Auth>
suspend fun updateUser(user: Auth)
suspend fun deleteUser(user: Auth)
fun saveAccessToken(token: String): Flow<Boolean>
fun saveRefreshToken(token: String): Flow<Boolean>
fun getAccessToken(): Flow<String>
fun getRefreshToken(): Flow<String>
suspend fun deleteToken()
fun uploadImage(image: List<MultipartBody.Part>): Flow<Resource<List<String>>>
fun getUserByHotel(hotelId: String): Flow<Resource<List<User>>>
fun getUserById(id: String, hotelId: String): Flow<Resource<User>>
fun updateUser(
id: String,
hotelId: String,
email: String,
): Flow<Resource<User>>
fun deleteUserAccount(id: String, hotelId: String): Flow<Resource<Int>>
} | 0 | Kotlin | 0 | 0 | 785f99aa5c1d5be4e2d3505ee877fee5a33ba823 | 1,251 | AceHotel-App | MIT License |
presentation/src/main/java/com/developer/mvi_project_cleanarchitecture/utils/Decoration.kt | mhmd-android | 509,102,234 | false | null | package com.developer.mvi_project_cleanarchitecture.utils
interface Decoration<out classBuilder> {
fun setMarginTop(value: Int): classBuilder
fun setMarginBottom(value: Int): classBuilder
fun setMarginLeft(value: Int): classBuilder
fun setMarginRight(value: Int): classBuilder
} | 0 | Kotlin | 0 | 0 | a64c7c98a318f3d6777b745c6b9e09f2f5e5a632 | 295 | Mvi-CleanArchitecture | Apache License 2.0 |
app/src/main/java/com/donnelly/steve/nytsearch/services/models/SearchDocument.kt | sdonn3 | 150,913,321 | false | {"Gradle": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 19, "XML": 19, "Java": 1} | package com.donnelly.steve.nytsearch.services.models
import com.google.gson.annotations.SerializedName
data class SearchDocument(
@SerializedName("web_url")
val webUrl: String?,
val snippet: String?,
@SerializedName("print_page")
val printPage: String?,
val source: String?,
val multimedia: ArrayList<SearchMultimedia>?,
val headline: SearchHeadline?,
val keywords: ArrayList<SearchKeywords>?,
@SerializedName("pub_date")
val publicationDate: String?,
@SerializedName("document_type")
val documentType: String?,
@SerializedName("news_desk")
val newsDesk: String?,
val byline: SearchByline?,
@SerializedName("type_of_material")
val typeOfMaterial: String?,
@SerializedName("_id")
val id: String?,
@SerializedName("word_count")
val wordCount: String?,
val score: Double?
) | 1 | null | 1 | 1 | 2fd18d49beb672888269583eae567d64484cb094 | 956 | NYTSearch | Apache License 2.0 |
cxrv/src/main/java/com/xiaocydx/cxrv/itemclick/_ListAdapter.kt | xiaocydx | 460,257,515 | false | null | package com.xiaocydx.cxrv.itemclick
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.xiaocydx.cxrv.list.*
/**
* 若触发了[target]的点击,则调用[action]
*
* 1. [action]的逻辑会覆盖[target]已经设置的[OnClickListener]。
* 2. 在合适的时机会清除[target]的状态,避免共享[RecycledViewPool]场景出现内存泄漏问题。
*
* @param intervalMs 执行[action]的间隔时间
* @param target 需要触发点击的目标视图,若返回`null`则表示不触发点击
*/
inline fun <ITEM : Any, VH : ViewHolder> ListAdapter<out ITEM, out VH>.doOnItemClick(
intervalMs: Long = NO_INTERVAL,
crossinline target: VH.() -> View? = { itemView },
crossinline action: (holder: VH, item: ITEM) -> Unit
): Disposable = DisposableWrapper().also { wrapper ->
doOnAttach { rv ->
rv.doOnItemClick(adapter = this, intervalMs, target) { holder, position ->
getItemOrNull(position)?.let { action(holder, it) }
}.also(wrapper::attach)
}.also(wrapper::attachIfEmpty)
}
/**
* [ListAdapter.doOnItemClick]的简易版本
*
* 1. [action]的逻辑会覆盖`itemView`已经设置的[OnClickListener]。
* 2. 在合适的时机会清除`itemView`的状态,避免共享[RecycledViewPool]场景出现内存泄漏问题。
* 3. 调用场景只关注item,可以将[doOnSimpleItemClick]和函数引用结合使用。
*/
inline fun <ITEM : Any, VH : ViewHolder> ListAdapter<out ITEM, out VH>.doOnSimpleItemClick(
crossinline action: (item: ITEM) -> Unit
): Disposable = doOnSimpleItemClick(NO_INTERVAL, action)
/**
* [ListAdapter.doOnItemClick]的简易版本
*
* 1. [action]的逻辑会覆盖`itemView`已经设置的[OnClickListener]。
* 2. 在合适的时机会清除`itemView`的状态,避免共享[RecycledViewPool]场景出现内存泄漏问题。
* 3. 调用场景只关注item,可以将[doOnSimpleItemClick]和函数引用结合使用。
*
* @param intervalMs 执行[action]的间隔时间
*/
inline fun <ITEM : Any, VH : ViewHolder> ListAdapter<out ITEM, out VH>.doOnSimpleItemClick(
intervalMs: Long,
crossinline action: (item: ITEM) -> Unit
): Disposable = doOnItemClick(intervalMs) { _, item -> action(item) }
/**
* 若触发了[target]的长按,则调用[action]
*
* 1. [action]返回`true`表示消费长按,松手时不会触发点击。
* 2. [action]的逻辑会覆盖[target]已经设置的[OnLongClickListener]。
* 3. 在合适的时机会清除[target]的状态,避免共享[RecycledViewPool]场景出现内存泄漏问题。
*
* @param target 需要触发点击的目标视图,若返回`null`则表示不触发长按
*/
inline fun <ITEM : Any, VH : ViewHolder> ListAdapter<out ITEM, out VH>.doOnLongItemClick(
crossinline target: VH.() -> View? = { itemView },
crossinline action: (holder: VH, item: ITEM) -> Boolean
): Disposable = DisposableWrapper().also { wrapper ->
doOnAttach { rv ->
rv.doOnLongItemClick(adapter = this, target) { holder, position ->
getItemOrNull(position)?.let { action(holder, it) } ?: false
}.also(wrapper::attach)
}.also(wrapper::attachIfEmpty)
}
/**
* [ListAdapter.doOnLongItemClick]的简易版本
*
* 1. [action]返回`true`表示消费长按,松手时不会触发点击。
* 2. [action]的逻辑会覆盖`itemView`已经设置的[OnLongClickListener]。
* 3. 在合适的时机会清除`itemView`的状态,避免共享[RecycledViewPool]场景出现内存泄漏问题。
* 4. 调用场景只关注item,可以将[doOnSimpleLongItemClick]和函数引用结合使用。
*/
inline fun <ITEM : Any, VH : ViewHolder> ListAdapter<out ITEM, out VH>.doOnSimpleLongItemClick(
crossinline action: (item: ITEM) -> Boolean
): Disposable = doOnLongItemClick { _, item -> action(item) } | 0 | Kotlin | 0 | 7 | 7283f04892a84661ff82f33eed377da2cc015874 | 3,203 | CXRV | Apache License 2.0 |
app/src/main/java/com/kusamaru/standroid/nicovideo/fragment/NicoVideoMyListListFragment.kt | kusamaru | 442,642,043 | false | {"Kotlin": 1954774} | package com.kusamaru.standroid.nicovideo.fragment
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.kusamaru.standroid.nicoapi.nicovideo.dataclass.NicoVideoData
import com.kusamaru.standroid.nicovideo.adapter.AllShowDropDownMenuAdapter
import com.kusamaru.standroid.nicovideo.adapter.NicoVideoListAdapter
import com.kusamaru.standroid.nicovideo.viewmodel.factory.NicoVideoMyListListViewModelFactory
import com.kusamaru.standroid.nicovideo.viewmodel.NicoVideoMyListListViewModel
import com.kusamaru.standroid.tool.getThemeColor
import com.kusamaru.standroid.databinding.FragmentNicovideoMylistListBinding
/**
* マイリストの動画一覧表示Fragment。
* ViewPagerで表示するFragmentです。
* 入れてほしいもの↓
* mylist_id |String |マイリストのID。空の場合はとりあえずマイリストをリクエストします
* mylist_is_me|Boolean|マイリストが自分のものかどうか。自分のマイリストの場合はtrue
* */
class NicoVideoMyListListFragment : Fragment() {
/** ViewModel */
private lateinit var myListListViewModel: NicoVideoMyListListViewModel
/** RecyclerViewへ渡す配列 */
private val recyclerViewList = arrayListOf<NicoVideoData>()
/** RecyclerViewへ入れるAdapter */
val nicoVideoListAdapter = NicoVideoListAdapter(recyclerViewList)
/** findViewById駆逐 */
private val viewBinding by lazy { FragmentNicovideoMylistListBinding.inflate(layoutInflater) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val myListId = arguments?.getString("mylist_id")!!
val isMe = arguments?.getBoolean("mylist_is_me")!!
myListListViewModel = ViewModelProvider(this, NicoVideoMyListListViewModelFactory(requireActivity().application, myListId, isMe)).get(NicoVideoMyListListViewModel::class.java)
// ダークモード
viewBinding.fragmentNicovideoMylistListAppBar.background = ColorDrawable(getThemeColor(requireContext()))
// RecyclerView初期化
initRecyclerView()
// 並び替えメニュー初期化
initSortMenu()
// データ取得を待つ
myListListViewModel.nicoVideoDataListLiveData.observe(viewLifecycleOwner) { videoList ->
recyclerViewList.clear()
recyclerViewList.addAll(videoList)
nicoVideoListAdapter.notifyDataSetChanged()
}
// くるくる
myListListViewModel.loadingLiveData.observe(viewLifecycleOwner) { isLoading ->
viewBinding.fragmentNicovideoMylistListSwipe.isRefreshing = isLoading
}
// ひっぱって更新
viewBinding.fragmentNicovideoMylistListSwipe.setOnRefreshListener {
myListListViewModel.getMyListVideoList()
}
}
/** 並び替えメニュー初期化 */
private fun initSortMenu() {
val sortList = arrayListOf(
"登録が新しい順",
"登録が古い順",
"再生の多い順",
"再生の少ない順",
"投稿日時が新しい順",
"投稿日時が古い順",
"再生時間の長い順",
"再生時間の短い順",
"コメントの多い順",
"コメントの少ない順",
"マイリスト数の多い順",
"マイリスト数の少ない順"
)
val adapter = AllShowDropDownMenuAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, sortList)
viewBinding.fragmentNicovideoMylistListSort.apply {
setAdapter(adapter)
setOnItemClickListener { parent, view, position, id ->
myListListViewModel.sort(position)
}
setText(sortList[0], false)
}
}
/** RecyclerView初期化 */
private fun initRecyclerView() {
viewBinding.fragmentNicovideoMylistListRecyclerview.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
// Adapterセット
adapter = nicoVideoListAdapter
}
}
} | 0 | Kotlin | 0 | 3 | 5c58707eecc7a994fbd4bc900b22106697bf3806 | 4,090 | StanDroid | Apache License 2.0 |
src/main/kotlin/no/nav/amt/distribusjon/varsel/hendelse/VarselHendelseDto.kt | navikt | 775,942,443 | false | {"Kotlin": 215914, "PLpgSQL": 635, "Dockerfile": 173} | package no.nav.amt.distribusjon.varsel.hendelse
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import no.nav.tms.varsel.action.Varseltype
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, visible = true, property = "@event_name")
@JsonSubTypes(
JsonSubTypes.Type(value = OpprettetVarselHendelse::class, name = "opprettet"),
JsonSubTypes.Type(value = InaktivertVarselHendelse::class, name = "inaktivert"),
JsonSubTypes.Type(value = SlettetVarselHendelse::class, name = "slettet"),
JsonSubTypes.Type(value = EksternStatusHendelse::class, name = "eksternStatusOppdatert"),
)
sealed interface VarselHendelseDto {
val varselId: String
val varseltype: Varseltype
val namespace: String
val appnavn: String
}
data class EksternStatusHendelse(
override val varselId: String,
override val varseltype: Varseltype,
override val namespace: String,
override val appnavn: String,
val status: String,
val kanal: String?,
val renotifikasjon: Boolean?,
val feilmelding: String?,
) : VarselHendelseDto {
companion object Status {
const val SENDT = "sendt"
const val FEILET = "feilet"
const val BESTILT = "bestilt"
}
}
data class InaktivertVarselHendelse(
override val varselId: String,
override val varseltype: Varseltype,
override val namespace: String,
override val appnavn: String,
) : VarselHendelseDto
data class OpprettetVarselHendelse(
override val varselId: String,
override val varseltype: Varseltype,
override val namespace: String,
override val appnavn: String,
) : VarselHendelseDto
data class SlettetVarselHendelse(
override val varselId: String,
override val varseltype: Varseltype,
override val namespace: String,
override val appnavn: String,
) : VarselHendelseDto
| 1 | Kotlin | 0 | 0 | 91f497f53dcbf0008fc9d927d23bf6089d0fb037 | 1,863 | amt-distribusjon | MIT License |
platform/ml-api/src/com/intellij/internal/ml/MLFeatureValueBase.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ml
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
interface MLFeatureValueBase {
val value: Any
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 269 | intellij-community | Apache License 2.0 |
gitnote-jetbrains/src/main/kotlin/io/cjlee/gitnote/GitNoteGutterIconRenderer.kt | cjlee38 | 780,015,519 | false | {"Kotlin": 33950, "Rust": 21360, "JavaScript": 10992, "HTML": 896} | package io.cjlee.gitnote
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.editor.markup.GutterDraggableObject
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.util.IconLoader
import com.intellij.util.IconUtil
import io.cjlee.gitnote.core.CoreHandler
import io.cjlee.gitnote.core.Message
import javax.swing.Icon
open class GitNoteGutterIconRenderer(
private val filePath: String,
private val handler: CoreHandler,
private val messages: List<Message>,
private val onDispose: () -> Unit
) : GutterIconRenderer() {
override fun getIcon(): Icon = ICON
override fun getTooltipText(): String = messages.last().message
override fun equals(other: Any?): Boolean = other is GutterIconRenderer && other.icon == this.icon
override fun hashCode(): Int = icon.hashCode()
override fun isNavigateAction(): Boolean {
return true
}
override fun getAlignment(): Alignment {
return Alignment.RIGHT
}
override fun getClickAction(): AnAction {
return object : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val gitNoteDialog = GitNoteDialog(e.project, filePath, handler, line, onDispose)
gitNoteDialog.show()
}
}
}
open val line: Int
get() = messages.last().line
override fun getDraggableObject(): GutterDraggableObject? {
// TODO : drag & drop
return super.getDraggableObject()
}
companion object {
val ICON = IconLoader.getIcon("/icons/icon.png", GitNoteGutterIconRenderer::class.java)
.let { IconUtil.scale(it, null, (13.0 / it.iconWidth).toFloat()) }
}
}
| 2 | Kotlin | 0 | 1 | b70f40950120deeac4bc25371956198b1db64cbc | 1,796 | gitnote | Apache License 2.0 |
app/src/main/java/com/example/k_health/food/adapter/FoodListAdapter.kt | SeokJiWon1207 | 420,371,551 | false | {"Kotlin": 149316} | package com.example.k_health.food.adapter
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.k_health.databinding.ItemFoodBinding
import com.example.k_health.food.data.models.Item
class FoodListAdapter(private val itemClickListener: (Item) -> Unit) :
ListAdapter<Item, FoodListAdapter.ViewHolder>(diffUtil) {
var checkedList = mutableListOf<Item>()
inner class ViewHolder(private val binding: ItemFoodBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: Item) = with(binding) {
foodNameTextView.text = item.foodName
gramTextView.text = item.gram.plus("g")
kcalTextView.text = item.kcal.plus("kcal")
root.setOnClickListener {
itemClickListener(item)
}
checkBox.apply {
setOnCheckedChangeListener(null) // 체크박스 리스너 초기화
isChecked = item.isSelected // 체크박스의 체크 여부를 데이터 클래스의 flag값으로 판단
setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener { // 체크박스의 상태값을 알기 위해 리스너 등록
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
Log.d(TAG, "position : ${adapterPosition} / isCheckd : ${isChecked}")
item.setSelected(isChecked) // 데이터 클래스의 객체와 동일
checkedList.add(item)
Log.d(TAG,"${checkedList}")
}
})
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ItemFoodBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(currentList.shuffled()[position])
}
companion object {
// DiffUtil은 RecyclerView의 성능을 한층 더 개선할 수 있게 해주는 유틸리티 클래스다.
// 기존의 데이터 리스트와 교체할 데이터 리스트를 비교해서 실질적으로 업데이트가 필요한 아이템들을 추려낸다.
val diffUtil = object : DiffUtil.ItemCallback<Item>() {
// 두 아이템이 동일한 아이템인지 체크한다. 같으면 areContentsTheSame 으로, 다르면 갱신
// Ex) item이 자신만의 고유한 foodName 같은걸 가지고 있다면 그걸 기준으로 삼으면 된다.
override fun areItemsTheSame(oldItem: Item, newItem: Item) =
oldItem.foodName == newItem.foodName
// 두 아이템이 동일한 내용물을 가지고 있는지 체크한다.
override fun areContentsTheSame(oldItem: Item, newItem: Item) =
oldItem.hashCode() == newItem.hashCode()
}
const val TAG = "FoodListAdapter"
}
} | 0 | Kotlin | 0 | 0 | 067d1dbabb741232a61cac71e12b646840dcc38f | 2,888 | K-Health | Apache License 2.0 |
app/src/main/java/com/realtimemap/repo/remote/SocketClientImpl.kt | rahmatya685 | 312,604,137 | false | null | package com.realtimemap.repo.remote
import com.realtimemap.util.Constants
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket
import javax.inject.Inject
import kotlin.properties.Delegates
class SocketClientImpl @Inject constructor(
socketParams: SocketParams
) : SocketClient {
private lateinit var socket: Socket
private lateinit var out: PrintWriter
private lateinit var `in`: BufferedReader
private lateinit var userLocations: (List<String>) -> Unit
private lateinit var userLocationsUpdate: (String) -> Unit
private var data by Delegates.observable("", { _, _, raw ->
if (isUpdate(raw) && ::userLocationsUpdate.isInitialized){
val cleanText =raw.replace(Constants.KEY_UPDATE,"").trim()
userLocationsUpdate.invoke(cleanText )
}
if (isUserList(raw) && ::userLocations.isInitialized) {
val purified = purifyText(raw)
userLocations.invoke(purified)
}
})
init {
GlobalScope.launch {
socket = Socket(socketParams.ip, socketParams.port)
out = PrintWriter(socket.getOutputStream(), true)
`in` = BufferedReader(InputStreamReader(socket.getInputStream()))
out.println(socketParams.authentication)
}
}
override fun listenToUpdates(userLocationsUpdate: (String) -> Unit) {
this.userLocationsUpdate = userLocationsUpdate
initListener()
}
override fun listenToUserLocation(userLocations: (List<String>) -> Unit) {
this.userLocations = userLocations
initListener()
}
private fun initListener() {
while (isSocketValid()) {
`in`.readLine()?.let { raw ->
data = raw
}
}
}
fun isSocketValid(): Boolean = ::socket.isInitialized && !socket.isClosed
fun isUserList(text: String): Boolean = text.startsWith(Constants.KEY_USER_LIST)
fun isUpdate(text: String): Boolean = text.startsWith(Constants.KEY_UPDATE)
fun purifyText(text: String): List<String> {
val refinedText = text.replace(Constants.KEY_USER_LIST, "")
.replace(Constants.KEY_UPDATE, "")
return refinedText.split(";").filter { !it.isNullOrBlank() }
}
override fun disconnect() {
socket.close()
out.close()
`in`.close()
}
}
| 0 | Kotlin | 0 | 3 | 199b6c16d989d640ad88e98803745ab160e6ae91 | 2,487 | RealtimeLocation | Apache License 2.0 |
codec/src/commonTest/kotlin/com/inkapplications/ack/codec/position/CompressedPositionChunkerTest.kt | InkApplications | 277,934,100 | false | {"Kotlin": 233829, "Perl": 93} | package com.inkapplications.ack.codec.position
import com.inkapplications.ack.codec.valueFor
import inkapplications.spondee.measure.us.toKnots
import inkapplications.spondee.spatial.degrees
import inkapplications.spondee.structure.toDouble
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class CompressedPositionChunkerTest {
@Test
fun validPosition() {
val given = "/5L!!<*e7>7P[Test"
val result = CompressedPositionChunker.popChunk(given)
assertEquals("Test", result.remainingData)
assertEquals(49.5, result.result.coordinates.latitude.asDecimal, 0.01)
assertEquals(-72.75, result.result.coordinates.longitude.asDecimal, 0.01)
assertEquals(36.2, result.result.extension?.valueFor(CompressedPositionExtensions.TrajectoryExtra::class)?.speed?.toKnots()?.toDouble()!!, 1e-1)
assertEquals(88.degrees, result.result.extension.valueFor(CompressedPositionExtensions.TrajectoryExtra::class)?.direction)
}
@Test
fun invalidPosition() {
val given = "Hello World"
assertFails { CompressedPositionChunker.popChunk(given) }
}
}
| 4 | Kotlin | 1 | 0 | e1eea2aba2d97cdf9713299cd61c8771a6e7fa7c | 1,158 | ACK | MIT License |
coworker-core/src/main/kotlin/org/camunda/community/extension/coworker/impl/CozeebeImpl.kt | camunda-community-hub | 574,492,193 | false | {"Kotlin": 120722} | package org.camunda.community.extension.coworker.impl
import io.camunda.zeebe.client.CredentialsProvider
import io.camunda.zeebe.client.ZeebeClientConfiguration
import io.camunda.zeebe.client.api.JsonMapper
import io.camunda.zeebe.client.api.command.ClientException
import io.camunda.zeebe.client.api.worker.JobClient
import io.camunda.zeebe.client.impl.NoopCredentialsProvider
import io.camunda.zeebe.client.impl.ZeebeClientImpl.buildChannel
import io.camunda.zeebe.client.impl.ZeebeClientImpl.buildGatewayStub
import io.camunda.zeebe.client.impl.worker.JobClientImpl
import io.camunda.zeebe.gateway.protocol.GatewayGrpc.GatewayStub
import io.camunda.zeebe.gateway.protocol.GatewayGrpcKt
import io.grpc.CallCredentials
import io.grpc.CallOptions
import io.grpc.ClientInterceptors
import io.grpc.ManagedChannel
import org.camunda.community.extension.coworker.Cozeebe
import org.camunda.community.extension.coworker.credentials.ZeebeCoworkerClientCredentials
import org.camunda.community.extension.coworker.zeebe.worker.builder.JobCoworkerBuilder
import org.camunda.community.extension.coworker.zeebe.worker.handler.JobHandler
import java.io.Closeable
import java.io.IOException
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
fun ZeebeClientConfiguration.buildCallCredentials(): CallCredentials? {
val customCredentialsProvider = this.credentialsProvider ?: return null
return ZeebeCoworkerClientCredentials(customCredentialsProvider)
}
fun ZeebeClientConfiguration.buildGatewayCoroutineStub(
channel: ManagedChannel
): GatewayGrpcKt.GatewayCoroutineStub {
val callOptions = this.buildCallCredentials()?.let {
CallOptions.DEFAULT.withCallCredentials(it)
} ?: CallOptions.DEFAULT
return GatewayGrpcKt
.GatewayCoroutineStub(
ClientInterceptors.intercept(channel, interceptors),
callOptions
)
}
fun ZeebeClientConfiguration.buildExecutorService(): ScheduledExecutorService =
Executors.newScheduledThreadPool(this.numJobWorkerExecutionThreads)
class CozeebeImpl(
private val zeebeClientConfiguration: ZeebeClientConfiguration,
private val managedChannel: ManagedChannel = buildChannel(zeebeClientConfiguration),
private val gatewayStub: GatewayStub = buildGatewayStub(managedChannel, zeebeClientConfiguration),
private val gatewayCoroutineStub: GatewayGrpcKt.GatewayCoroutineStub = zeebeClientConfiguration
.buildGatewayCoroutineStub(managedChannel),
private val jsonMapper: JsonMapper = zeebeClientConfiguration.jsonMapper,
private val scheduledExecutorService: ScheduledExecutorService = zeebeClientConfiguration.buildExecutorService(),
private val credentialsProvider: CredentialsProvider = zeebeClientConfiguration.credentialsProvider
?: NoopCredentialsProvider(),
private val retryPredicate: (Throwable) -> Boolean = credentialsProvider::shouldRetryRequest,
private val jobClient: JobClient = JobClientImpl(gatewayStub, zeebeClientConfiguration, jsonMapper, retryPredicate)
) : Cozeebe {
private val closeables: MutableList<Closeable> = mutableListOf()
override fun newCoWorker(jobType: String, jobHandler: JobHandler): JobCoworkerBuilder = JobCoworkerBuilder(
configuration = zeebeClientConfiguration,
jobClient = jobClient,
gatewayStub = gatewayCoroutineStub,
jsonMapper = jsonMapper,
jobType = jobType,
jobHandler = jobHandler,
retryPredicate = retryPredicate,
executorService = scheduledExecutorService,
closeables = closeables
)
override fun configuration() = zeebeClientConfiguration
override fun close() {
closeables
.forEach {
runCatching { it.close() }.onFailure {
if (it !is IOException) {
throw it
}
}
}
scheduledExecutorService.shutdownNow()
try {
if (!scheduledExecutorService.awaitTermination(15, TimeUnit.SECONDS)) {
throw ClientException(
"Timed out awaiting termination of job worker executor after 15 seconds"
)
}
} catch (e: InterruptedException) {
throw ClientException(
"Unexpected interrupted awaiting termination of job worker executor", e
)
}
managedChannel.shutdownNow()
try {
if (!managedChannel.awaitTermination(15, TimeUnit.SECONDS)) {
throw ClientException(
"Timed out awaiting termination of in-flight request channel after 15 seconds"
)
}
} catch (e: InterruptedException) {
throw ClientException(
"Unexpectedly interrupted awaiting termination of in-flight request channel", e
)
}
}
}
| 14 | Kotlin | 3 | 6 | a64f6e966fed5949f39a5f93c8e99235d28be7c3 | 4,959 | kotlin-coworker | Apache License 2.0 |
projects/court-case-and-delius/src/test/kotlin/uk/gov/justice/digital/hmpps/service/OffenderManagerServiceTest.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 4403685, "HTML": 72513, "D2": 44286, "Ruby": 26979, "Shell": 23475, "SCSS": 6630, "HCL": 2712, "Dockerfile": 2552, "JavaScript": 1428, "Python": 268} | package uk.gov.justice.digital.hmpps.service
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.whenever
import org.springframework.ldap.core.LdapTemplate
import uk.gov.justice.digital.hmpps.data.generator.PersonGenerator.PRISON_MANAGER
import uk.gov.justice.digital.hmpps.data.generator.PersonGenerator.generatePersonManager
import uk.gov.justice.digital.hmpps.data.generator.StaffGenerator
import uk.gov.justice.digital.hmpps.integrations.delius.person.entity.Person
import uk.gov.justice.digital.hmpps.integrations.delius.person.entity.PersonRepository
import uk.gov.justice.digital.hmpps.integrations.delius.provider.entity.LdapUser
import uk.gov.justice.digital.hmpps.integrations.delius.service.OffenderManagerService
import javax.naming.ldap.LdapName
@ExtendWith(MockitoExtension::class)
class OffenderManagerServiceTest {
@Mock
lateinit var personRepository: PersonRepository
@Mock
lateinit var ldapTemplate: LdapTemplate
@Mock
lateinit var person: Person
private lateinit var offenderManagerService: OffenderManagerService
@BeforeEach
fun setUp() {
offenderManagerService = OffenderManagerService(personRepository, ldapTemplate)
val staff = StaffGenerator.generate("N01ABBC", user = StaffGenerator.STAFF_USER)
whenever(person.offenderManagers).thenReturn(listOf(generatePersonManager(person, staff)))
whenever(person.prisonOffenderManagers).thenReturn(listOf(PRISON_MANAGER))
whenever(personRepository.findByCrn(any())).thenReturn(person)
}
@Test
fun `email is null when empty string `() {
val ldapUser = LdapUser(
dn = LdapName("cn=test"),
email = "",
forename = "",
surname = "",
telephoneNumber = "",
username = "TestUser"
)
whenever(ldapTemplate.find(any(), eq(LdapUser::class.java))).thenReturn(listOf(ldapUser))
val ret = offenderManagerService.getAllOffenderManagersForCrn("CRN", false)
assertEquals(null, ret[0].staff?.email)
}
@Test
fun `email is null when null `() {
val ldapUser = LdapUser(
dn = LdapName("cn=test"),
email = null,
forename = "",
surname = "",
telephoneNumber = "",
username = "TestUser"
)
whenever(ldapTemplate.find(any(), eq(LdapUser::class.java))).thenReturn(listOf(ldapUser))
val ret = offenderManagerService.getAllOffenderManagersForCrn("CRN", false)
assertEquals(null, ret[0].staff?.email)
}
@Test
fun `email is populated `() {
val ldapUser = LdapUser(
dn = LdapName("cn=test"),
email = "test",
forename = "",
surname = "",
telephoneNumber = "",
username = "TestUser"
)
whenever(ldapTemplate.find(any(), eq(LdapUser::class.java))).thenReturn(listOf(ldapUser))
val ret = offenderManagerService.getAllOffenderManagersForCrn("CRN", false)
assertEquals("test", ret[0].staff?.email)
}
}
| 4 | Kotlin | 0 | 2 | 35dce3c0cb146117ab52162a8a14d97394d05101 | 3,372 | hmpps-probation-integration-services | MIT License |
native/native.tests/testData/caches/ic/externalDependency/userLib/file1.kt | JetBrains | 3,432,266 | false | null | fun bar() = external.foo() | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 26 | kotlin | Apache License 2.0 |
compiler/fir/resolve/testData/resolve/diagnostics/infixFunctions.kt | danysantiago | 247,057,405 | true | {"Markdown": 61, "Gradle": 617, "Gradle Kotlin DSL": 331, "Java Properties": 12, "Shell": 10, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 11, "Java": 6433, "Kotlin": 49287, "Proguard": 8, "XML": 1563, "Text": 10494, "JavaScript": 270, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "INI": 137, "AsciiDoc": 1, "SVG": 31, "HTML": 464, "Groovy": 31, "JSON": 45, "JFlex": 3, "Maven POM": 96, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 37, "C": 1, "YAML": 2, "Ruby": 2, "OpenStep Property List": 2, "Swift": 2, "Objective-C": 2, "Scala": 1} | infix fun Int.good(x: Int) {}
<!INAPPLICABLE_INFIX_MODIFIER!>infix fun Int.foo(x: Int, y: Int) {}<!>
<!INAPPLICABLE_INFIX_MODIFIER!>infix fun Int.bar() {}<!>
<!INAPPLICABLE_INFIX_MODIFIER!>infix fun baz(x: Int, y: Int) {}<!>
infix class A
infix typealias B = A
infix val x = 1 | 0 | null | 0 | 1 | 9dd201aaf243cf9198cf129b22d3aa38fcff182c | 282 | kotlin | Apache License 2.0 |
plugins/core/src/main/kotlin/de/fayard/refreshVersions/core/internal/VersionCandidatesResultMode.kt | Splitties | 150,827,271 | false | null | package de.fayard.refreshVersions.core.internal
internal data class VersionCandidatesResultMode(
val filterMode: FilterMode,
val sortingMode: SortingMode
) {
enum class FilterMode { AllIntermediateVersions, LatestByStabilityLevel, Latest; }
sealed class SortingMode {
sealed class ByRepo : SortingMode() {
companion object : ByRepo()
object LastUpdated : ByRepo()
object LastVersionComparison : ByRepo()
}
object ByVersion : SortingMode()
}
}
| 113 | null | 109 | 1,606 | df624c0fb781cb6e0de054a2b9d44808687e4fc8 | 526 | refreshVersions | MIT License |
memkched-client/src/test/kotlin/common/com/raycoarana/memkched/test/StringToBytesTranscoder.kt | raycoarana | 597,846,682 | false | null | package com.raycoarana.memkched.test
import com.raycoarana.memkched.api.Flags
import com.raycoarana.memkched.api.Transcoder
object StringToBytesTranscoder : Transcoder<String> {
override suspend fun encode(value: String): ByteArray =
value.toByteArray(Charsets.UTF_8)
override suspend fun decode(flags: Flags, source: ByteArray): String =
String(source, charset = Charsets.UTF_8)
}
| 7 | Kotlin | 0 | 0 | 97df1f6aacd8fb12983aefbfb4405b05ceaa1733 | 409 | memkched | MIT License |
library/src/main/java/app/moviebase/androidx/widget/recyclerview/viewholder/Recyclable.kt | MoviebaseApp | 255,031,168 | false | null | package app.moviebase.androidx.widget.recyclerview.viewholder
interface Recyclable {
fun recycle()
}
| 0 | Kotlin | 0 | 1 | 27e06659f68ea642dff11a95a604c927babc8689 | 106 | android-elements | Apache License 2.0 |
Healthcare-app/android/MDBRealmPatient/app/src/main/java/com/wekanmdb/storeinventory/ui/signup/SignupActivity.kt | realm | 422,284,529 | false | {"Kotlin": 966534, "Swift": 867269, "Objective-C": 232478, "TypeScript": 75527, "JavaScript": 32651, "HTML": 2365, "Ruby": 2276, "Less": 31} | package com.wekanmdb.storeinventory.ui.signup
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.text.method.PasswordTransformationMethod
import android.text.method.SingleLineTransformationMethod
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.DatePicker
import android.widget.EditText
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.wekanmdb.storeinventory.R
import com.wekanmdb.storeinventory.app.apprealm
import com.wekanmdb.storeinventory.app.key
import com.wekanmdb.storeinventory.app.taskApp
import com.wekanmdb.storeinventory.app.user
import com.wekanmdb.storeinventory.base.BaseActivity
import com.wekanmdb.storeinventory.databinding.ActivityLoginBinding
import com.wekanmdb.storeinventory.databinding.ActivitySignupBinding
import com.wekanmdb.storeinventory.ui.patientBasicInfo.PatientInfoActivity
import com.wekanmdb.storeinventory.utils.Constants.Companion.DOCTOR
import com.wekanmdb.storeinventory.utils.DatePickerFragment
import com.wekanmdb.storeinventory.utils.EncrytionUtils
import com.wekanmdb.storeinventory.utils.RealmUtils
import com.wekanmdb.storeinventory.utils.UiUtils.isValidEmail
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_signup.*
import java.text.SimpleDateFormat
import java.util.*
class SignupActivity : BaseActivity<ActivityLoginBinding>(), SignupNavigator,
DatePickerDialog.OnDateSetListener {
companion object {
fun getCallingIntent(context: Context): Intent {
return Intent(context, SignupActivity::class.java)
}
}
private lateinit var activitySignupBinding: ActivitySignupBinding
private lateinit var signupViewModel: SignupViewModel
override fun getLayoutId(): Int = R.layout.activity_signup
private var showCreatePwd = true
var showConfirmPwd = true
var calendar: Calendar = Calendar.getInstance()
var date: Date? = null
override fun initView(mViewDataBinding: ViewDataBinding?) {
activitySignupBinding = mViewDataBinding as ActivitySignupBinding
signupViewModel = ViewModelProvider(this).get(SignupViewModel::class.java)
activitySignupBinding.signupViewModel = signupViewModel
signupViewModel.navigator = this
activitySignupBinding.imageView6.setOnClickListener {
finish()
}
spinnerInit()
}
// This function is used to generate static dropdown values ans view for gender and Role
private fun spinnerInit() {
val gender =
listOf("Select Gender", "Male", "Female", "Others")
val genderAdapter = ArrayAdapter(
this,
R.layout.spinner_row, gender
)
val role =
listOf("Patient")
val adapter = ArrayAdapter(
this,
R.layout.spinner_row, role
)
activitySignupBinding.spinner2.adapter = genderAdapter
activitySignupBinding.spinner.adapter = adapter
}
@RequiresApi(Build.VERSION_CODES.O)
/*
* click function of First Time Signing up and check the fields are not empty
* getting response from register user and start the next activity
* */
override fun signupClick() {
if (signupViewModel.firstName.get().isNullOrEmpty()) {
showToast("Enter first name")
return
}
if (signupViewModel.lastName.get().isNullOrEmpty()) {
showToast("Enter last name")
return
}
if (signupViewModel.email.get().isNullOrEmpty()) {
showToast("Enter email")
return
}
if (!isValidEmail(signupViewModel.email.get().toString().trim())) {
showToast("Enter valid email")
return
}
if (signupViewModel.createPassword.get().isNullOrEmpty()) {
showToast("Enter password")
return
}
if (signupViewModel.confirmPassword.get().isNullOrEmpty()) {
showToast("Enter confirm password")
return
}
if (activitySignupBinding.spinner.selectedItem.toString().isNullOrEmpty()) {
showToast("Select the Role")
return
}
if (activitySignupBinding.spinner2.selectedItem.toString().isNullOrEmpty()) {
showToast("Select the Gender")
return
}
if (activitySignupBinding.textView58.text.toString().isNullOrEmpty()) {
showToast("Select the DOB")
return
}
if (activitySignupBinding.createPassword.text.toString() != activitySignupBinding.confirmPassword.text.toString()) {
showToast("Password mismatch")
return
}
val userRole = activitySignupBinding.spinner.selectedItem.toString()
val gender = activitySignupBinding.spinner2.selectedItem.toString()
showLoading()
signupViewModel.getRegisterUser(
userRole, gender, date
).observe(this) { authenticateUser ->
// Query results are AuthenticateUser
if (authenticateUser?.isSuccess == true) {
user = taskApp.currentUser()
key = EncrytionUtils.getExistingKey(appPreference)
if (key == null) {
key = EncrytionUtils.getNewKey(appPreference)
}
//Creating realm instance
Realm.getInstanceAsync(
RealmUtils.getRealmconfig(),
object : Realm.Callback() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onSuccess(realm: Realm) {
hideLoading()
apprealm = realm
if (userRole == DOCTOR) {
//TODO : Need to show the hospitals list to select
} else {
startActivity(PatientInfoActivity.getCallingIntent(this@SignupActivity))
}
}
})
} else {
showToast("" + authenticateUser?.error)
hideLoading()
}
}
}
/*
* click function of showing the entered password
*/
override fun showCreatePasswordClick() {
if (signupViewModel.createPassword.get().isNullOrEmpty()) {
showToast("please enter the password")
return
}
createPassword.requestFocus()
if (showCreatePwd) {
showCreatePwd = false
showPassword(createPassword, imageView7)
} else {
showCreatePwd = true
hidePassword(createPassword, imageView7)
}
}
/*
* click function of showing the entered confirm password
*/
override fun showConfirmPasswordClick() {
if (signupViewModel.confirmPassword.get().isNullOrEmpty()) {
showToast("please enter the confirm password")
return
}
confirmPassword.requestFocus()
if (showConfirmPwd) {
showConfirmPwd = false
showPassword(confirmPassword, imageView8)
} else {
showConfirmPwd = true
hidePassword(confirmPassword, imageView8)
}
}
override fun patientUserClick() {
activitySignupBinding.textCreate.text = resources.getString(R.string.create)
}
//Calender for selecting date of birth
override fun dobClick() {
val datePicker: DialogFragment = DatePickerFragment()
datePicker.show(supportFragmentManager, "date picker")
}
private fun showPassword(password: EditText, imageView: ImageView) {
password.transformationMethod = SingleLineTransformationMethod()
imageView.setImageDrawable(
ContextCompat.getDrawable(
applicationContext,
R.mipmap.pwd_show
)
)
password.setSelection(password.text!!.length)
}
private fun hidePassword(password: EditText, imageView: ImageView) {
password.transformationMethod = PasswordTransformationMethod()
imageView.setImageDrawable(
ContextCompat.getDrawable(
applicationContext,
R.mipmap.pwd_hide
)
)
password.setSelection(password.text!!.length)
}
// Setting the date selected on Calender
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
calendar[Calendar.YEAR] = year
calendar[Calendar.MONTH] = month
calendar[Calendar.DATE] = dayOfMonth
val months = month + 1
val dat = "$year-$months-$dayOfMonth"
val dateFormat = SimpleDateFormat("yyyy-mm-dd")
date = calendar.time
try {
val d = dateFormat.parse(dat)
val jobDay = dateFormat.format(d)
activitySignupBinding.textView58.text = jobDay
} catch (e: Exception) { //java.text.ParseException: Unparseable date: Geting error
Log.d("error", e.message.toString())
}
}
}
| 0 | Kotlin | 1 | 8 | e57077e2c26a75db4e80dd40909f12dca4a431e0 | 9,404 | realm-sync-demos | Apache License 2.0 |
src/nl/hannahsten/texifyidea/modules/LatexProjectGeneratorPeer.kt | Hannah-Sten | 62,398,769 | false | null | package nl.hannahsten.texifyidea.modules
import com.intellij.ide.util.projectWizard.SettingsStep
import com.intellij.platform.ProjectGeneratorPeer
import com.intellij.ui.components.JBCheckBox
import nl.hannahsten.texifyidea.settings.TexifySettings
import java.awt.FlowLayout
import javax.swing.JComponent
import javax.swing.JPanel
/**
* Customize the project creation dialog, adding settings.
*
* Inspirec by the Rust plugin, source:
* https://github.com/intellij-rust/intellij-rust/blob/master/src/main/kotlin/org/rust/ide/newProject/RsProjectGeneratorPeer.kt
*/
class LatexProjectGeneratorPeer : ProjectGeneratorPeer<TexifySettings> {
lateinit var bibtexEnabled: JBCheckBox
private val settings = TexifySettings()
private val listeners = ArrayList<ProjectGeneratorPeer.SettingsListener>()
override fun validate(): Nothing? = null
override fun getSettings() = settings
/** Deprecated but we have to override it. */
@Deprecated("", ReplaceWith("addSettingsListener"), level = DeprecationLevel.ERROR)
override fun addSettingsStateListener(@Suppress("DEPRECATION") listener: com.intellij.platform.WebProjectGenerator.SettingsStateListener) = Unit
override fun buildUI(settingsStep: SettingsStep) = settingsStep.addExpertPanel(component)
override fun isBackgroundJobRunning() = false
override fun addSettingsListener(listener: ProjectGeneratorPeer.SettingsListener) {
listeners += listener
}
override fun getComponent(): JComponent {
return JPanel(FlowLayout(FlowLayout.LEFT)).apply {
bibtexEnabled = JBCheckBox("Configure with BibTeX support")
add(bibtexEnabled)
}
}
}
| 99 | null | 87 | 891 | 986550410e2fea91d1e93abfc683db1c8527c9d9 | 1,687 | TeXiFy-IDEA | MIT License |
app/src/main/java/me/destro/android/gitfav/features/listing/paging/StarredRepositoryDataSource.kt | dexpota | 142,775,611 | false | null | package me.destro.android.gitfav.features.listing.paging
import androidx.paging.PageKeyedDataSource
import me.destro.android.gitfav.data.Paged
import me.destro.android.gitfav.data.repository.RemoteRepository
import me.destro.android.gitfav.domain.model.Repository
import java.lang.Exception
import java.util.regex.Pattern
import com.github.kittinunf.result.Result as Result
class StarredRepositoryDataSource(private val username: String, private val githubService: RemoteRepository) : PageKeyedDataSource<String, Repository>() {
override fun loadInitial(params: PageKeyedDataSource.LoadInitialParams<String>, callback: PageKeyedDataSource.LoadInitialCallback<String, Repository>) {
val starredCall = githubService.listStarredRepository(this.username, 0)
// TODO handling this disposable
starredCall.subscribe({ response: Result<Paged<List<Repository>>, Exception> ->
response.fold({
val pagedResponse = it
val next = pagedResponse.next
val prev = pagedResponse.previous
val starredRepositories = pagedResponse.response
callback.onResult(starredRepositories, prev, next)
}, {
})
}, {
})
}
override fun loadBefore(params: PageKeyedDataSource.LoadParams<String>, callback: PageKeyedDataSource.LoadCallback<String, Repository>) {
}
override fun loadAfter(params: PageKeyedDataSource.LoadParams<String>, callback: PageKeyedDataSource.LoadCallback<String, Repository>) {
val p = Pattern.compile("page=(\\d+).*$")
val m = p.matcher(params.key)
var next: Int? = 0
if (m.find()) {
next = Integer.valueOf(m.group(1))
}
val starredCall = githubService.listStarredRepository(this.username, next!!)
// TODO handling this disposable
starredCall.subscribe({ response: Result<Paged<List<Repository>>, Exception> ->
response.fold({
val pagedResponse = it
val nextLink = pagedResponse.next
val starredRepositories = pagedResponse.response
callback.onResult(starredRepositories, nextLink)
}, {
})
}, {
})
}
}
| 1 | null | 1 | 1 | 615c0523ee7e2ebec03b999a73084a61e700717f | 2,275 | gitfav | MIT License |
example/android/app/src/main/kotlin/com/kasem/receive_sharing_intent_example/MainActivity.kt | Klabauterman | 250,911,835 | true | {"Swift": 21339, "Kotlin": 16501, "Dart": 9929, "Ruby": 3011, "Shell": 768, "Objective-C": 435} | package com.kasem.receive_sharing_intent_example
import io.flutter.embedding.android.FlutterActivity;
class MainActivity: FlutterActivity() {
}
| 0 | Swift | 0 | 0 | 0ede807498e53b4fd232417cf2d3f8259336958c | 147 | receive_sharing_intent | Apache License 2.0 |
app/src/main/java/com/codingpit/pvpcplanner/data/Repository.kt | Coding-Pit-Dev | 825,419,559 | false | {"Kotlin": 25792} | package com.codingpit.pvpcplanner.data
import com.codingpit.pvpcplanner.domains.models.PVPCModel
interface Repository{
suspend fun getPrices(): List<PVPCModel>
} | 5 | Kotlin | 0 | 1 | f78a7db1d0e6d6f40ec49f86d2f497fb8956686a | 167 | PVPC-Android | MIT License |
src/main/kotlin/others/Candy.kt | e-freiman | 471,473,372 | false | null | package others
fun candy(ratings: IntArray): Int {
val output = IntArray(ratings.size){1}
for (i in 1..ratings.lastIndex) {
if (ratings[i - 1] < ratings[i]) {
output[i] = output[i - 1] + 1
}
}
for (i in output.lastIndex - 1 downTo 0) {
if (ratings[i] > ratings[i + 1] && output[i] <= output[i + 1]) {
output[i] = output[i + 1] + 1
}
}
return output.sum()
}
fun main() {
println(candy(intArrayOf(1,0,2)))
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 495 | LeetcodeGoogleInterview | Apache License 2.0 |
app/src/main/java/com/pakohan/laundrytracker/LaundryTrackerApplication.kt | pakohan | 839,696,898 | false | {"Kotlin": 78842} | package com.pakohan.laundrytracker
import android.app.Application
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import com.pakohan.laundrytracker.data.AppContainer
import com.pakohan.laundrytracker.data.AppDataContainer
private const val USER_PREFERENCES_NAME = "user_preferences"
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
name = USER_PREFERENCES_NAME,
)
class LaundryTrackerApplication : Application() {
lateinit var container: AppContainer
override fun onCreate() {
super.onCreate()
container = AppDataContainer(
this,
dataStore,
)
}
}
| 1 | Kotlin | 0 | 0 | cdd5a645bc236e05bd55b20ea5622cd36edce041 | 783 | laundry-tracker | MIT License |
code/features/banners/src/main/java/com/benhurqs/banners/widgets/presenter/BannerPresenter.kt | Benhurqs | 281,213,359 | true | {"Kotlin": 58096} | package com.benhurqs.banners.widgets.presenter
import com.benhurqs.banners.widgets.contracts.BannerContract
import com.benhurqs.network.domain.repository.NetworkRepository
import com.benhurqs.network.entities.Banner
class BannerPresenter(private var view: BannerContract.View) : BannerContract.Presenter{
override fun callAPI() {
NetworkRepository.getBanners(
onStart = { onStart() },
onSuccess = { onSuccess(it) },
onFailure = { onFailure(it) },
onFinish = { onFinish() }
)
}
private fun onStart() {
view.showLoading()
}
private fun onSuccess(list: List<Banner>?) {
if(list.isNullOrEmpty()){
view.hideContent()
}else{
view.loadBanner(list)
}
}
private fun onFailure(error: String?){
view.hideContent()
}
private fun onFinish(){
view.hideLoading()
}
} | 0 | Kotlin | 0 | 0 | 7b1e1023ff748c20cfbfeba14d407f970cad7072 | 935 | mobile-android-challenge | MIT License |
buildSrc/src/main/kotlin/mihon/buildlogic/ProjectExtensions.kt | mihonapp | 743,704,912 | false | {"Kotlin": 2919203} | package mihon.buildlogic
import com.android.build.api.dsl.CommonExtension
import org.gradle.accessors.dm.LibrariesForAndroidx
import org.gradle.accessors.dm.LibrariesForCompose
import org.gradle.accessors.dm.LibrariesForKotlinx
import org.gradle.accessors.dm.LibrariesForLibs
import org.gradle.api.Project
import org.gradle.api.tasks.testing.Test
import org.gradle.api.tasks.testing.logging.TestLogEvent
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.provideDelegate
import org.gradle.kotlin.dsl.the
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.compose.compiler.gradle.ComposeCompilerGradlePluginExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.io.File
val Project.androidx get() = the<LibrariesForAndroidx>()
val Project.compose get() = the<LibrariesForCompose>()
val Project.kotlinx get() = the<LibrariesForKotlinx>()
val Project.libs get() = the<LibrariesForLibs>()
internal fun Project.configureAndroid(commonExtension: CommonExtension<*, *, *, *, *, *>) {
commonExtension.apply {
compileSdk = AndroidConfig.COMPILE_SDK
defaultConfig {
minSdk = AndroidConfig.MIN_SDK
ndk {
version = AndroidConfig.NDK
}
}
compileOptions {
sourceCompatibility = AndroidConfig.JavaVersion
targetCompatibility = AndroidConfig.JavaVersion
isCoreLibraryDesugaringEnabled = true
}
}
tasks.withType<KotlinCompile>().configureEach {
compilerOptions {
jvmTarget.set(AndroidConfig.JvmTarget)
freeCompilerArgs.addAll(
"-opt-in=kotlin.RequiresOptIn",
"-Xcontext-receivers",
)
// Treat all Kotlin warnings as errors (disabled by default)
// Override by setting warningsAsErrors=true in your ~/.gradle/gradle.properties
val warningsAsErrors: String? by project
allWarningsAsErrors.set(warningsAsErrors.toBoolean())
}
}
dependencies {
"coreLibraryDesugaring"(libs.desugar)
}
}
internal fun Project.configureCompose(commonExtension: CommonExtension<*, *, *, *, *, *>) {
pluginManager.apply(kotlinx.plugins.compose.compiler.get().pluginId)
commonExtension.apply {
buildFeatures {
compose = true
}
dependencies {
"implementation"(platform(compose.bom))
}
}
extensions.configure<ComposeCompilerGradlePluginExtension> {
// Enable strong skipping mode
enableStrongSkippingMode.set(true)
// Enable experimental compiler opts
// https://developer.android.com/jetpack/androidx/releases/compose-compiler#1.5.9
enableNonSkippingGroupOptimization.set(true)
val enableMetrics = project.providers.gradleProperty("enableComposeCompilerMetrics").orNull.toBoolean()
val enableReports = project.providers.gradleProperty("enableComposeCompilerReports").orNull.toBoolean()
val rootProjectDir = rootProject.layout.buildDirectory.asFile.get()
val relativePath = projectDir.relativeTo(rootDir)
if (enableMetrics) {
val buildDirPath = rootProjectDir.resolve("compose-metrics").resolve(relativePath)
metricsDestination.set(buildDirPath)
}
if (enableReports) {
val buildDirPath = rootProjectDir.resolve("compose-reports").resolve(relativePath)
reportsDestination.set(buildDirPath)
}
}
}
internal fun Project.configureTest() {
tasks.withType<Test> {
useJUnitPlatform()
testLogging {
events(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED)
}
}
}
val Project.generatedBuildDir: File get() = project.layout.buildDirectory.asFile.get().resolve("generated/mihon")
| 262 | Kotlin | 388 | 8,875 | fba9bacdc19dee7cdf9e3d1cb4ee4a496fa7b514 | 3,914 | mihon | Apache License 2.0 |
Android/App_Petridish/App/src/main/java/com/zktony/android/ui/utils/WindowStateUtils.kt | OriginalLight | 556,213,614 | false | {"Kotlin": 6123849, "C#": 376657, "Vue": 164353, "Rust": 101266, "C++": 63250, "TypeScript": 62359, "Python": 28781, "CMake": 18271, "C": 16214, "Less": 2885, "Dockerfile": 1898, "HTML": 648, "JavaScript": 450} | package com.zktony.android.ui.utils
/**
* Different type of navigation supported by app depending on device size and state.
*/
enum class NavigationType {
NONE, NAVIGATION_RAIL, PERMANENT_NAVIGATION_DRAWER
}
enum class NavigationContentPosition {
TOP, CENTER
}
/**
* Different type of page supported by app depending on each screen.
*/
enum class PageType {
LIST, START, RUNTIME,
CALIBRATION_LIST, CALIBRATION_DETAIL,
PROGRAM_LIST, PROGRAM_DETAIL,
SETTINGS, AUTH, CONFIG, MOTOR_LIST, MOTOR_DETAIL
} | 0 | Kotlin | 0 | 1 | bcf0671b9e4ad199e579764f29683c1c575369d2 | 530 | ZkTony | Apache License 2.0 |
sample/src/main/java/co/en/archx/sample/app/modules/ActivityModule.kt | en-archx | 140,067,640 | false | {"Java": 10861} | package co.en.archx.sample.app.modules
import co.en.archx.sample.ui.activity.main.MainActivity
import co.en.archx.sample.ui.activity.main.MainScope
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module()
abstract class ActivityModule {
@ContributesAndroidInjector
@MainScope
abstract fun contributeMainActivity(): MainActivity
} | 1 | Java | 1 | 1 | f1d28d17e1c35a4ca6f61b328d6cf4af71654444 | 368 | archx | Apache License 2.0 |
src/main/kotlin/talsumi/marderlib/pak/generators/lang/PAKLangGenerator.kt | Talsumi | 532,197,088 | false | null | /*
* MIT License
*
* Copyright (c) 2022 Talsumi
*
* 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 talsumi.marderlib.pak.generators.lang
import com.google.gson.JsonObject
import net.minecraft.block.Block
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
import net.minecraft.util.registry.Registry
import talsumi.marderlib.easyparametermapping.EzPMBlock
import talsumi.marderlib.pak.PAKGenerator
import talsumi.marderlib.util.FileUtil
import java.io.File
import java.nio.file.Files
//TODO: PAK Language file generator removes ':' and trailing characters from values.
class PAKLangGenerator(val namespace: String): PAKGenerator {
val actualNamespace = namespace.substringBefore('|')
val langFileName = namespace.substringAfter('|')
val mappings = HashMap<String, String>()
val mappingsList = ArrayList<Pair<String, String>>()
val newMappings = ArrayList<Pair<String, String>>()
var lineAt = 0
override fun generateFiles(file: EzPMBlock, outputFolder: File, overwrite: Boolean): Int
{
val langFile = FileUtil.createPathToFile(outputFolder, "lang", file = "$langFileName.json")
val stream = Files.lines(langFile.toPath())
val iterator = stream.iterator()
while (true) {
val line = formatLine(nextLine(iterator) ?: break)
if (line.first == "PAKGenerated")
break;
mappings[line.first] = line.second
mappingsList.add(line)
}
stream.close()
for (entry in file.getParameterMap())
if (entry.key != "autogenerate")
parseEntry(entry.key, entry.value)
if (file.getParameterAsBoolean("autogenerate") == true) {
Registry.ITEM.forEach { parseItem(it) }
Registry.BLOCK.forEach { parseBlock(it) }
}
val json = JsonObject()
for (mapping in mappingsList)
json.addProperty(mapping.first, mapping.second)
json.addProperty("PAKGenerated", "PAKGenerated")
for (mapping in newMappings)
json.addProperty(mapping.first, mapping.second)
if (!langFile.exists() || overwrite)
writeJsonToFile(langFile.toPath(), json)
return 0
}
private fun parseBlock(block: Block)
{
val id = block.registryEntry.registryKey().value
if (id.namespace == actualNamespace) {
val entry = "block.${id.namespace}.${id.path}"
val translation = formatId(id.path)
if (!mappings.containsKey(entry)) {
newMappings.add(Pair(entry, translation))
mappings[entry] = translation
}
}
}
private fun parseItem(item: Item)
{
val id = item.registryEntry.registryKey().value
if (item !is BlockItem && id.namespace == actualNamespace) {
val entry = "item.${id.namespace}.${id.path}"
val translation = formatId(id.path)
if (!mappings.containsKey(entry)) {
newMappings.add(Pair(entry, translation))
mappings[entry] = translation
}
}
}
private fun parseEntry(key: String, value: String)
{
if (!mappings.containsKey(key)) {
newMappings.add(Pair(key, value))
mappings[key] = value
}
}
private fun nextLine(iterator: Iterator<String>): String?
{
while (iterator.hasNext()) {
var str = iterator.next().trim()
lineAt++
if (str.isNotEmpty() && !str.startsWith('{') && !str.endsWith('}'))
return str.trim()
}
return null
}
private fun formatId(id: String): String
{
var name = ""
val words = id.split('_')
for (word in words.withIndex())
name+=word.value.replaceFirstChar { it.uppercase() } + if (word.index >= words.size-1) "" else " "
return name
}
private fun formatLine(line: String): Pair<String, String>
{
val args = line.replace("\"", "").replace(",", "").split(':')
return Pair(args[0].trim(), args[1].trim())
}
} | 0 | Kotlin | 0 | 0 | 64507c6cd7b7af2e735a6327f88e3ecb189ebce0 | 4,614 | MarderLib | MIT License |
app/src/main/java/com/tanasi/streamflix/fragments/movie/MovieViewModel.kt | stantanasi | 511,319,545 | false | null | package com.tanasi.streamflix.fragments.movie
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tanasi.streamflix.models.Movie
import com.tanasi.streamflix.utils.UserPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MovieViewModel(id: String) : ViewModel() {
private val _state = MutableLiveData<State>(State.Loading)
val state: LiveData<State> = _state
sealed class State {
object Loading : State()
data class SuccessLoading(val movie: Movie) : State()
data class FailedLoading(val error: Exception) : State()
}
init {
getMovie(id)
}
private fun getMovie(id: String) = viewModelScope.launch(Dispatchers.IO) {
_state.postValue(State.Loading)
try {
val movie = UserPreferences.currentProvider!!.getMovie(id)
_state.postValue(State.SuccessLoading(movie))
} catch (e: Exception) {
_state.postValue(State.FailedLoading(e))
}
}
} | 47 | null | 41 | 93 | c9255fe9ee2ef3ed8bfbeef567950f1a63a51752 | 1,119 | streamflix | Apache License 2.0 |
rain/src/main/java/com/rapidsos/rain/connection/ConnectionVerifier.kt | johndpope | 192,260,729 | false | {"Kotlin": 351294, "Shell": 212} | package com.rapidsos.rain.connection
import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
/**
* @author Josias Sena
*/
class ConnectionVerifier : AnkoLogger {
companion object {
fun isConnectedToInternet(consumer: Consumer<Boolean>): Disposable? =
ReactiveNetwork.checkInternetConnectivity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(consumer)
}
} | 0 | Kotlin | 0 | 1 | 465a1dfbe3d3a9d99418e9b23fb0c6e8790c36c6 | 735 | era-android | Apache License 2.0 |
android/coroutine-http-demo/bin/main/com/caldremch/android/coroutine/http/demo/impl/HttpObsHandlerImpl.kt | android-module | 522,390,095 | false | {"Kotlin": 149203, "Java": 23434, "Shell": 433} | package com.caldremch.android.coroutine.http.demo.impl
import com.caldremch.android.log.debugLog
import com.caldremch.http.core.abs.ICommonRequestEventCallback
import com.caldremch.http.exception.ApiHttpException
/**
* Created by Leon on 2022/7/5
*/
class HttpObsHandlerImpl : ICommonRequestEventCallback {
override fun onError(e: Throwable, showToast: Boolean) {
debugLog { "走到这里吗? ${e.message}" }
}
} | 0 | Kotlin | 0 | 1 | 52b640f9e1e65b15417a4cc61b64845aca837d74 | 423 | android-http | Apache License 2.0 |
idea/testData/navigation/implementations/multiModule/expectClass/common/common.kt | zhangdinet | 128,026,457 | true | {"Markdown": 41, "Gradle": 263, "XML": 1410, "Gradle Kotlin DSL": 118, "Ant Build System": 52, "Java Properties": 14, "Shell": 10, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 1, "Proguard": 7, "Kotlin": 35728, "Java": 5078, "Protocol Buffer": 8, "Text": 7400, "JavaScript": 234, "JAR Manifest": 2, "Roff": 201, "Roff Manpage": 26, "JSON": 16, "INI": 72, "AsciiDoc": 1, "HTML": 373, "Groovy": 25, "Maven POM": 85, "CSS": 1, "JFlex": 2, "ANTLR": 1} | package test
open class SimpleParent
expect open class <caret>ExpectedChild : SimpleParent
class ExpectedChildChild : ExpectedChild()
class SimpleChild : SimpleParent()
// REF: [common] (test).ExpectedChildChild
// REF: [jvm] (test).ExpectedChildChildJvm | 1 | Java | 1 | 1 | cf2e9c70028199ff2446d7b568983e387fb58ef4 | 259 | kotlin | Apache License 2.0 |
sample/src/test/java/app/cash/paparazzi/sample/LottieTest.kt | cashapp | 176,338,719 | false | {"Kotlin": 808142, "JavaScript": 5934, "CSS": 1797, "HTML": 1716} | package app.cash.paparazzi.sample
import app.cash.paparazzi.Paparazzi
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieCompositionFactory
import org.junit.Rule
import org.junit.Test
class LottieTest {
@get:Rule
var paparazzi = Paparazzi()
@Test
fun lottie() {
val composition = LottieCompositionFactory.fromRawResSync(paparazzi.context, R.raw.lottie_logo)
.value!!
val view = LottieAnimationView(paparazzi.context)
view.setComposition(composition)
// view.progress = 1.0f
// paparazzi.snapshot(view, "lottie logo")
view.playAnimation()
paparazzi.gif(view, "lottie logo", start = 0L, end = 5000L, fps = 60)
}
@Test
fun lottie2() {
val composition = LottieCompositionFactory.fromRawResSync(paparazzi.context, R.raw.masks).value!!
val view = LottieAnimationView(paparazzi.context)
view.setComposition(composition)
view.playAnimation()
// view.progress = 0.0f
// paparazzi.snapshot(view, "masks0")
//
// view.progress = 0.5f
// paparazzi.snapshot(view, "masks1")
//
// view.progress = 1.0f
// paparazzi.snapshot(view, "masks2")
paparazzi.gif(view, "masks", start = 0L, end = 5000L, fps = 60)
}
}
| 113 | Kotlin | 214 | 2,290 | a47d3a28700ad0994c45975a5cd0e86e834a9a81 | 1,209 | paparazzi | Apache License 2.0 |
domain/src/test/java/com/tayfuncesur/data/bookmark/BookmarkProjectTest.kt | TayfunCesur | 184,639,163 | false | null | package com.tayfuncesur.data.bookmark
import com.tayfuncesur.domain.bookmark.BookmarkProject
import com.tayfuncesur.domain.executor.PostExecutionThread
import com.tayfuncesur.domain.repository.ProjectsRepository
import io.reactivex.Completable
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnitRunner
import java.lang.IllegalArgumentException
import java.util.*
@RunWith(MockitoJUnitRunner::class)
class BookmarkProjectTest {
lateinit var bookmarkProject: BookmarkProject
@Mock
lateinit var projectsRepository: ProjectsRepository
@Mock
lateinit var postExecutionThread: PostExecutionThread
@Before
fun setup() {
bookmarkProject = BookmarkProject(projectsRepository, postExecutionThread)
}
@Test
fun shouldBookmarkProjectCompletes() {
Mockito.`when`(projectsRepository.bookmarkProject(anyString())).thenReturn(Completable.complete())
bookmarkProject.doWork(BookmarkProject.Params.projectId(UUID.randomUUID().toString())).test().assertComplete()
}
@Test(expected = IllegalArgumentException::class)
fun shouldThrowException() {
bookmarkProject.doWork().test()
}
} | 0 | Kotlin | 10 | 65 | 8aa6705cf42651422ec677c5e48c9cab12e54b9f | 1,318 | GithubProjectBrowser | Apache License 2.0 |
avd/src/com/android/tools/idea/avd/StorageCapacity.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.adddevicedialog.localavd
internal data class StorageCapacity
internal constructor(internal val value: Long, internal val unit: Unit) {
/**
* Returns an equivalent StorageCapacity with the largest unit with no loss of precision. Returns
* 2M for 2048K, for example.
*/
internal fun withMaxUnit(): StorageCapacity {
val maxUnit = maxUnit()
return StorageCapacity(valueIn(maxUnit), maxUnit)
}
private fun maxUnit(): Unit {
val array = Unit.values()
val subList = array.toList().subList(unit.ordinal + 1, array.size)
val byteCount = value * unit.byteCount
return subList.filter { byteCount % it.byteCount == 0L }.maxOrNull() ?: unit
}
internal fun valueIn(unit: Unit) = value * this.unit.byteCount / unit.byteCount
internal enum class Unit(internal val byteCount: Long) {
B(1),
KB(1_024),
MB(1_024 * 1_024),
GB(1_024 * 1_024 * 1_024),
TB(1_024L * 1_024 * 1_024 * 1_024),
}
override fun toString() = value.toString() + unit.toString().first()
}
| 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,668 | android | Apache License 2.0 |
xesar-connect/src/main/kotlin/com/open200/xesar/connect/messages/command/AssignAuthorizationProfileToMediumMapi.kt | open200 | 684,928,079 | false | {"Kotlin": 438614} | package com.open200.xesar.connect.messages.command
import com.open200.xesar.connect.utils.UUIDSerializer
import java.util.*
import kotlinx.serialization.Serializable
/**
* Represents a command POJO to assign an authorization profile to a medium.
*
* @param authorizationProfileId The id of the authorization profile.
* @param id The id of the medium.
* @param commandId The id of the command.
* @param token The token of the command.
*/
@Serializable
data class AssignAuthorizationProfileToMediumMapi(
@Serializable(with = UUIDSerializer::class) val authorizationProfileId: UUID,
@Serializable(with = UUIDSerializer::class) val id: UUID,
@Serializable(with = UUIDSerializer::class) val commandId: UUID,
val token: String
) : Command
| 18 | Kotlin | 1 | 9 | 2ded0fbbe8a5df74065c141f5afe1b20c72022c6 | 758 | xesar-connect | Apache License 2.0 |
client/src/commonMain/kotlin/com/algolia/search/client/internal/ClientRecommendationImpl.kt | OmarAliSaid | 353,348,929 | true | {"Kotlin": 1362438, "Ruby": 8863} | package com.algolia.search.client.internal
import com.algolia.search.client.ClientRecommendation
import com.algolia.search.configuration.Configuration
import com.algolia.search.configuration.Credentials
import com.algolia.search.endpoint.EndpointRecommendation
import com.algolia.search.endpoint.internal.EndpointRecommendation
import com.algolia.search.transport.internal.Transport
internal class ClientRecommendationImpl internal constructor(
internal val transport: Transport,
) : ClientRecommendation,
EndpointRecommendation by EndpointRecommendation(transport),
Configuration by transport,
Credentials by transport.credentials
| 0 | null | 0 | 0 | 19b8db887a0f4c2e1307b67cd383dcecfc7cd939 | 650 | algoliasearch-client-kotlin | MIT License |
client/src/commonMain/kotlin/com/algolia/search/client/internal/ClientRecommendationImpl.kt | OmarAliSaid | 353,348,929 | true | {"Kotlin": 1362438, "Ruby": 8863} | package com.algolia.search.client.internal
import com.algolia.search.client.ClientRecommendation
import com.algolia.search.configuration.Configuration
import com.algolia.search.configuration.Credentials
import com.algolia.search.endpoint.EndpointRecommendation
import com.algolia.search.endpoint.internal.EndpointRecommendation
import com.algolia.search.transport.internal.Transport
internal class ClientRecommendationImpl internal constructor(
internal val transport: Transport,
) : ClientRecommendation,
EndpointRecommendation by EndpointRecommendation(transport),
Configuration by transport,
Credentials by transport.credentials
| 0 | null | 0 | 0 | 19b8db887a0f4c2e1307b67cd383dcecfc7cd939 | 650 | algoliasearch-client-kotlin | MIT License |
src/main/kotlin/com/imma/service/login/LoginService.kt | Indexical-Metrics-Measure-Advisory | 344,732,013 | false | null | package com.imma.service.login
import com.imma.auth.AdminReserved
import com.imma.model.admin.User
import com.imma.service.Service
import com.imma.service.Services
import com.imma.utils.getCurrentDateTime
import org.mindrot.jbcrypt.BCrypt
class LoginService(services: Services) : Service(services) {
fun login(username: String?, plainPassword: String?): User? {
if (username == null || username.isBlank()) {
return null
}
if (AdminReserved.enabled
&& username == AdminReserved.username
&& plainPassword == AdminReserved.password
) {
// successfully login when admin enabled and username/password matched
return User().apply {
val now = getCurrentDateTime()
userId = username
name = username
nickName = username
active = true
createTime = now
lastModifyTime = now
}
}
val user = services.user { findUserByName(username) }
val credential = services.userCredential { findCredentialByName(username) } ?: return null
val hashedPassword: String = credential.credential!!
return if (BCrypt.checkpw(plainPassword, hashedPassword)) {
user
} else {
null
}
}
} | 0 | Kotlin | 0 | 1 | c42a959826e72ac8cea7a8390ccc7825f047a591 | 1,130 | watchmen-ktor | MIT License |
zircon.core/src/test/kotlin/org/codetome/zircon/internal/color/DefaultTextColorTest.kt | opencollective | 119,803,967 | false | null | package org.codetome.zircon.internal.color
import org.assertj.core.api.Assertions.assertThat
import org.codetome.zircon.api.color.TextColor
import org.junit.Test
class DefaultTextColorTest {
@Test
fun shouldGenerateProperCacheKey() {
val result = DefaultTextColor(RED, GREEN, BLUE, 123).generateCacheKey()
assertThat(result).isEqualTo("51015123")
}
@Test
fun shouldCreateDefaultTextColorWithProperDefaultAlpha() {
val result = DefaultTextColor(RED, GREEN, BLUE)
assertThat(result.getRed()).isEqualTo(RED)
assertThat(result.getGreen()).isEqualTo(GREEN)
assertThat(result.getBlue()).isEqualTo(BLUE)
assertThat(result.getAlpha()).isEqualTo(TextColor.defaultAlpha())
}
companion object {
val RED = 5
val GREEN = 10
val BLUE = 15
}
}
| 0 | null | 1 | 1 | 3c1cd8aa4b6ddcbc39b9873c54ac64e3ec6cda4d | 849 | zircon | MIT License |
plugin-annotation/src/main/java/com/mapbox/maps/plugin/annotation/generated/OnCircleAnnotationLongClickListener.kt | mapbox | 330,365,289 | false | {"Kotlin": 3982759, "Java": 98572, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2413, "CMake": 1201, "EJS": 1194} | // This file is generated.
package com.mapbox.maps.plugin.annotation.generated
import com.mapbox.maps.plugin.annotation.OnAnnotationLongClickListener
/**
* Interface definition for a callback to be invoked when a circleAnnotation has been long clicked.
*/
fun interface OnCircleAnnotationLongClickListener : OnAnnotationLongClickListener<CircleAnnotation> | 216 | Kotlin | 131 | 472 | 2700dcaf18e70d23a19fc35b479bff6a2d490475 | 360 | mapbox-maps-android | Apache License 2.0 |
app/src/main/kotlin/io/shtanko/picasagallery/core/executor/JobThreadFactory.kt | ashtanko | 99,620,302 | false | null | /*
* Copyright 2017 <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 io.shtanko.picasagallery.core.executor
import io.shtanko.picasagallery.Config.JOB_THREAD_NAME
import java.util.concurrent.ThreadFactory
object JobThreadFactory : ThreadFactory {
private var counter = 0
override fun newThread(runnable: Runnable?): Thread = Thread(
runnable,
JOB_THREAD_NAME + counter++
)
} | 1 | null | 1 | 4 | ad6961aa1d60668786797a443b64e6710f464f8c | 925 | Picasa-Gallery-Android | Apache License 2.0 |
BraintreeCore/src/test/java/com/braintreepayments/api/BraintreeHttpResponseParserUnitTest.kt | braintree | 21,631,528 | false | null | package com.braintreepayments.api
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.net.HttpURLConnection
class BraintreeHttpResponseParserUnitTest {
private lateinit var urlConnection: HttpURLConnection
private lateinit var baseParser: BaseHttpResponseParser
@Before
fun beforeEach() {
baseParser = mockk()
urlConnection = mockk()
}
@Test
@Throws(Exception::class)
fun parse_forwardsResultByDefault() {
every { baseParser.parse(123, urlConnection) } returns "parse result"
val sut = BraintreeHttpResponseParser(baseParser)
val result = sut.parse(123, urlConnection)
assertEquals("parse result", result)
}
@Test
@Throws(Exception::class)
fun parse_propagatesExceptionsByDefault() {
val exception = Exception("error")
every { baseParser.parse(123, urlConnection) } throws exception
val sut = BraintreeHttpResponseParser(baseParser)
try {
sut.parse(123, urlConnection)
fail("should not get here")
} catch (actualException: Exception) {
assertSame(exception, actualException)
}
}
@Test
@Throws(Exception::class)
fun parse_whenBaseParserThrowsAuthorizationException_throwsNewAuthorizationExceptionWithMessage() {
val authorizationException = AuthorizationException(Fixtures.ERROR_RESPONSE)
every { baseParser.parse(123, urlConnection) } throws authorizationException
val sut = BraintreeHttpResponseParser(baseParser)
try {
sut.parse(123, urlConnection)
fail("should not get here")
} catch (actualException: AuthorizationException) {
assertEquals("There was an error", actualException.message)
}
}
@Test
@Throws(Exception::class)
fun parse_whenBaseParserThrowsUnprocessibleEntityException_throwsErrorWithResponseException() {
val unprocessableEntityException = UnprocessableEntityException(Fixtures.ERROR_RESPONSE)
every {
baseParser.parse(123, urlConnection)
} throws unprocessableEntityException
val sut = BraintreeHttpResponseParser(baseParser)
try {
sut.parse(123, urlConnection)
fail("should not get here")
} catch (actualException: ErrorWithResponse) {
assertEquals("There was an error", actualException.message)
}
}
} | 24 | null | 237 | 403 | 3e071c3b297c07cc108df696d96e664e1752a598 | 2,513 | braintree_android | MIT License |
BraintreeCore/src/test/java/com/braintreepayments/api/BraintreeHttpResponseParserUnitTest.kt | braintree | 21,631,528 | false | null | package com.braintreepayments.api
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.net.HttpURLConnection
class BraintreeHttpResponseParserUnitTest {
private lateinit var urlConnection: HttpURLConnection
private lateinit var baseParser: BaseHttpResponseParser
@Before
fun beforeEach() {
baseParser = mockk()
urlConnection = mockk()
}
@Test
@Throws(Exception::class)
fun parse_forwardsResultByDefault() {
every { baseParser.parse(123, urlConnection) } returns "parse result"
val sut = BraintreeHttpResponseParser(baseParser)
val result = sut.parse(123, urlConnection)
assertEquals("parse result", result)
}
@Test
@Throws(Exception::class)
fun parse_propagatesExceptionsByDefault() {
val exception = Exception("error")
every { baseParser.parse(123, urlConnection) } throws exception
val sut = BraintreeHttpResponseParser(baseParser)
try {
sut.parse(123, urlConnection)
fail("should not get here")
} catch (actualException: Exception) {
assertSame(exception, actualException)
}
}
@Test
@Throws(Exception::class)
fun parse_whenBaseParserThrowsAuthorizationException_throwsNewAuthorizationExceptionWithMessage() {
val authorizationException = AuthorizationException(Fixtures.ERROR_RESPONSE)
every { baseParser.parse(123, urlConnection) } throws authorizationException
val sut = BraintreeHttpResponseParser(baseParser)
try {
sut.parse(123, urlConnection)
fail("should not get here")
} catch (actualException: AuthorizationException) {
assertEquals("There was an error", actualException.message)
}
}
@Test
@Throws(Exception::class)
fun parse_whenBaseParserThrowsUnprocessibleEntityException_throwsErrorWithResponseException() {
val unprocessableEntityException = UnprocessableEntityException(Fixtures.ERROR_RESPONSE)
every {
baseParser.parse(123, urlConnection)
} throws unprocessableEntityException
val sut = BraintreeHttpResponseParser(baseParser)
try {
sut.parse(123, urlConnection)
fail("should not get here")
} catch (actualException: ErrorWithResponse) {
assertEquals("There was an error", actualException.message)
}
}
} | 24 | null | 237 | 403 | 3e071c3b297c07cc108df696d96e664e1752a598 | 2,513 | braintree_android | MIT License |
kotlin-native/backend.native/tests/interop/objc/direct/main.kt | JetBrains | 3,432,266 | false | {"Kotlin": 73968610, "Java": 6672141, "Swift": 4257498, "C": 2622360, "C++": 1898765, "Objective-C": 641056, "Objective-C++": 167134, "JavaScript": 135706, "Python": 48402, "Shell": 31423, "TypeScript": 22754, "Lex": 18369, "Groovy": 17265, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | import direct.*
import kotlinx.cinterop.*
import kotlin.test.*
class CallingConventionsNativeHeir() : CallingConventions() {
// nothing
}
typealias CC = CallingConventions
typealias CCH = CallingConventionsHeir
typealias CCN = CallingConventionsNativeHeir
// KT-54610
fun main(args: Array<String>) {
autoreleasepool {
val cc = CC()
val cch = CCH()
val ccn = CCN()
assertEquals(42UL, CC.regular(42))
assertEquals(42UL, cc.regular(42))
assertEquals(42UL, CC.regularExt(42))
assertEquals(42UL, cc.regularExt(42))
assertEquals(42UL, CCH.regular(42))
assertEquals(42UL, cch.regular(42))
assertEquals(42UL, CCH.regularExt(42))
assertEquals(42UL, cch.regularExt(42))
assertEquals(42UL, ccn.regular(42UL))
assertEquals(42UL, ccn.regularExt(42UL))
assertEquals(42UL, CC.direct(42))
assertEquals(42UL, cc.direct(42))
assertEquals(42UL, CC.directExt(42))
assertEquals(42UL, cc.directExt(42))
assertEquals(42UL, CCH.direct(42))
assertEquals(42UL, cch .direct(42))
assertEquals(42UL, CCH.directExt(42))
assertEquals(42UL, cch .directExt(42))
assertEquals(42UL, ccn .direct(42UL))
assertEquals(42UL, ccn .directExt(42UL))
}
}
| 162 | Kotlin | 5729 | 46,436 | c902e5f56504e8572f9bc13f424de8bfb7f86d39 | 1,317 | kotlin | Apache License 2.0 |
libnavigation-base/src/main/java/com/mapbox/navigation/base/route/RouteRefreshCallback.kt | cscharfe | 253,174,152 | true | {"Java Properties": 3, "Markdown": 10, "Gradle": 34, "Shell": 5, "YAML": 2, "Batchfile": 2, "JSON": 22, "Ignore List": 19, "Makefile": 1, "INI": 16, "Proguard": 11, "Kotlin": 428, "XML": 490, "Java": 543, "JavaScript": 2, "Text": 3, "Python": 2} | package com.mapbox.navigation.base.route
import com.mapbox.api.directions.v5.models.DirectionsRoute
interface RouteRefreshCallback {
fun onRefresh(directionsRoute: DirectionsRoute)
fun onError(error: RouteRefreshError)
}
data class RouteRefreshError(
val message: String? = null,
val throwable: Throwable? = null
)
| 0 | null | 0 | 0 | 7b0e6c57cc6878266f0eba5f490ba936ecaeda59 | 335 | mapbox-navigation-android | Apache License 2.0 |
app/src/main/java/xyz/bboylin/dailyandroid/presentation/activity/BaseActivity.kt | bboylin | 120,625,830 | false | null | package xyz.bboylin.dailyandroid.presentation.activity
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.v7.app.ActionBar
import android.support.v7.app.AppCompatActivity
import io.reactivex.disposables.CompositeDisposable
/**
* Created by lin on 2018/2/5.
* 公用的上层activity
*/
abstract class BaseActivity : AppCompatActivity() {
protected val compositeDisposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getLayoutId())
initData()
initView()
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.clear()
}
protected fun setupToolbar(@StringRes res: Int, hasParent: Boolean = true) {
val actionBar = supportActionBar as ActionBar
actionBar?.let {
if (hasParent) {
actionBar.setHomeButtonEnabled(true)
actionBar.setDisplayHomeAsUpEnabled(true);
}
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(res);
}
}
abstract fun getLayoutId(): Int
abstract fun initView()
abstract fun initData()
} | 0 | Kotlin | 0 | 5 | ec9dca120b5ef89c2d8851c4d9c9f86437556696 | 1,240 | DailyAndroid | Apache License 2.0 |
app/src/main/java/me/jagdeep/wikisearch/main/MainActivity.kt | jdsingh | 139,997,216 | false | null | package me.jagdeep.wikisearch.main
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.View
import android.view.ViewConfiguration
import android.view.inputmethod.InputMethodManager
import android.view.inputmethod.InputMethodManager.HIDE_NOT_ALWAYS
import androidx.core.content.systemService
import androidx.core.view.isVisible
import androidx.core.widget.toast
import dagger.android.support.DaggerAppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import me.jagdeep.domain.search.model.SearchResult
import me.jagdeep.presentation.SearchState
import me.jagdeep.presentation.SearchViewModel
import me.jagdeep.wikisearch.R
import me.jagdeep.wikisearch.inject.ViewModelFactory
import me.jagdeep.wikisearch.util.onScroll
import me.jagdeep.wikisearch.util.onTextChanged
import javax.inject.Inject
class MainActivity : DaggerAppCompatActivity() {
@Inject
lateinit var listAdapter: SearchListAdapter
@Inject
lateinit var viewModelFactory: ViewModelFactory
@Inject
lateinit var openWikipediaPageHandler: OpenWikipediaPageHandler
private lateinit var viewModel: SearchViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this, viewModelFactory)
.get(SearchViewModel::class.java)
setupListView()
hideKeyboardOnScroll()
observeState()
observeQueryText()
}
private fun observeQueryText() {
query_input.onTextChanged {
clear_query.isVisible = it.isNotEmpty()
if (it.isBlank()) {
listAdapter.submitList(emptyList())
}
viewModel.search(it.toString())
}
}
private fun observeState() {
viewModel.searchResult().observe(this, Observer { state ->
when (state) {
is SearchState.Error -> {
toast(state.message)
.setGravity(Gravity.CENTER, 0, 0)
}
is SearchState.Success -> {
results.visibility = View.VISIBLE
listAdapter.submitList(state.result)
// TODO: could to scrollToPosition 0 because list is updated in background thread
// Always reset the scroll position to the top when the query changes.
// results.scrollToPosition(0)
}
}
})
}
private fun setupListView() {
clear_query.setOnClickListener {
query_input.setText("")
}
listAdapter.clickListener = searchItemListener
results.apply {
adapter = listAdapter
layoutManager = LinearLayoutManager(context)
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
}
}
private fun hideKeyboardOnScroll() {
val touchSlop = ViewConfiguration.get(this).scaledTouchSlop
var totalDy = 0
results.onScroll { _, dy ->
if (dy > 0) {
totalDy += dy
if (totalDy >= touchSlop) {
totalDy = 0
val inputMethodManager = systemService<InputMethodManager>()
inputMethodManager.hideSoftInputFromWindow(
query_input.windowToken,
HIDE_NOT_ALWAYS
)
}
}
}
}
private val searchItemListener = object : SearchItemListener {
override fun onSearchResultClicked(searchResult: SearchResult) {
openWikipediaPageHandler(searchResult)
}
}
}
| 10 | null | 1 | 1 | 15d1c660c688ef8a9e1539840928598c62e023fa | 3,956 | android-wikisearch | MIT License |
plugins/kotlin/uast/uast-kotlin-base/tests/test/org/jetbrains/uast/test/common/kotlin/LightClassBehaviorTestBase.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.test.common.kotlin
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.psi.*
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import junit.framework.TestCase
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.uast.*
import com.intellij.platform.uast.testFramework.env.findElementByTextFromPsi
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
import org.jetbrains.uast.visitor.AbstractUastVisitor
// NB: Similar to [UastResolveApiFixtureTestBase], but focusing on light classes, not `resolve`
interface LightClassBehaviorTestBase : UastPluginSelection {
// NB: ported [LightClassBehaviorTest#testIdentifierOffsets]
fun checkIdentifierOffsets(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"test.kt", """
class A {
fun foo() {}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val foo = uFile.findElementByTextFromPsi<UMethod>("foo", strict = false)
.orFail("can't find fun foo")
val fooMethodName = foo.javaPsi.nameIdentifier!!
val offset = fooMethodName.textOffset
val range = fooMethodName.textRange
TestCase.assertTrue(offset > 0)
TestCase.assertEquals(offset, range.startOffset)
}
// NB: ported [LightClassBehaviorTest#testPropertyAccessorOffsets]
fun checkPropertyAccessorOffsets(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"test.kt", """
class A {
var a: Int
get() = 5
set(v) {}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val aClass = uFile.findElementByTextFromPsi<UClass>("A", strict = false)
.orFail("can't find class A")
val getAMethod = aClass.javaPsi.findMethodsByName("getA").single() as PsiMethod
val setAMethod = aClass.javaPsi.findMethodsByName("setA").single() as PsiMethod
val ktClass = aClass.sourcePsi as KtClassOrObject
val ktProperty = ktClass.declarations.filterIsInstance<KtProperty>().single()
TestCase.assertNotSame(getAMethod.textOffset, setAMethod.textOffset)
TestCase.assertTrue(getAMethod.textOffset > 0)
TestCase.assertNotSame(getAMethod.textOffset, ktProperty.textOffset)
TestCase.assertEquals(getAMethod.textOffset, ktProperty.getter?.textOffset)
TestCase.assertEquals(getAMethod.textOffset, getAMethod.textRange.startOffset)
TestCase.assertTrue(setAMethod.textOffset > 0)
TestCase.assertNotSame(setAMethod.textOffset, ktProperty.textOffset)
TestCase.assertEquals(setAMethod.textOffset, ktProperty.setter?.textOffset)
TestCase.assertEquals(setAMethod.textOffset, setAMethod.textRange.startOffset)
TestCase.assertEquals("set(v) {}", setAMethod.text)
}
fun checkFunctionModifierListOffsets(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"test.kt", """
annotation class MyAnnotation
class A {
@MyAnnotation
fun foo() {}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val foo = uFile.findElementByTextFromPsi<UMethod>("foo", strict = false)
.orFail("can't find fun foo")
val fooMethodJavaPsiModifierList = foo.javaPsi.modifierList
TestCase.assertTrue(fooMethodJavaPsiModifierList.textOffset > 0)
TestCase.assertFalse(fooMethodJavaPsiModifierList.textRange.isEmpty)
TestCase.assertEquals(fooMethodJavaPsiModifierList.textOffset, fooMethodJavaPsiModifierList.textRange.startOffset)
TestCase.assertEquals("@MyAnnotation", fooMethodJavaPsiModifierList.text)
val fooMethodSourcePsiModifierList = (foo.sourcePsi as KtModifierListOwner).modifierList!!
TestCase.assertTrue(fooMethodSourcePsiModifierList.textOffset > 0)
TestCase.assertFalse(fooMethodSourcePsiModifierList.textRange.isEmpty)
TestCase.assertEquals(fooMethodSourcePsiModifierList.textOffset, fooMethodSourcePsiModifierList.textRange.startOffset)
TestCase.assertEquals("@MyAnnotation", fooMethodSourcePsiModifierList.text)
TestCase.assertEquals(fooMethodJavaPsiModifierList.textOffset, fooMethodSourcePsiModifierList.textOffset)
TestCase.assertEquals(fooMethodJavaPsiModifierList.textRange, fooMethodSourcePsiModifierList.textRange)
}
fun checkLocalClassCaching(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"test.kt",
"""
fun foo() {
class Bar() {
fun baz() {}
val property = 43
constructor(i: Int): this()
init {
42
}
}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
fun findDeclaration(): Set<KtNamedDeclaration> {
val clazz = uFile.findElementByTextFromPsi<UClass>("Bar", strict = false).orFail("can't find class Bar")
return clazz.uastDeclarations.map { it.javaPsi?.unwrapped as KtNamedDeclaration }.toSet()
}
val declarationsBefore = findDeclaration()
val lightElementsBefore = mutableSetOf<PsiElement>()
for (namedDeclaration in declarationsBefore) {
val lightElements = namedDeclaration.toLightElements()
if (lightElements.isEmpty()) error("Light elements for ${namedDeclaration.name} is not found")
lightElementsBefore += lightElements
for (lightElement in lightElements) {
TestCase.assertTrue(lightElement.isValid)
}
runUndoTransparentWriteAction {
val ktPsiFactory = KtPsiFactory(myFixture.project)
val text = namedDeclaration.text
val newDeclaration = when (namedDeclaration) {
is KtPrimaryConstructor -> ktPsiFactory.createPrimaryConstructor(text)
is KtSecondaryConstructor -> ktPsiFactory.createSecondaryConstructor(text)
else -> ktPsiFactory.createDeclaration<KtNamedDeclaration>(text)
}
namedDeclaration.replace(newDeclaration)
}
for (namedElement in lightElements) {
TestCase.assertFalse(namedElement.isValid)
}
}
val recreatedDeclarations = findDeclaration()
for (namedDeclaration in recreatedDeclarations) {
TestCase.assertTrue(namedDeclaration.name, namedDeclaration !in declarationsBefore)
val lightElements = namedDeclaration.toLightElements()
if (lightElements.isEmpty()) error("Light elements for ${namedDeclaration.name} is not found")
for (lightElement in lightElements) {
TestCase.assertTrue(lightElement.isValid)
TestCase.assertTrue(lightElement !in lightElementsBefore)
}
}
}
fun checkPropertyAccessorModifierListOffsets(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"test.kt", """
annotation class MyAnnotation
class Foo {
var a: Int
@MyAnnotation
get() = 5
set(v) {}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val aClass = uFile.findElementByTextFromPsi<UClass>("Foo", strict = false)
.orFail("can't find class Foo")
val getAMethod = aClass.javaPsi.findMethodsByName("getA").single() as PsiMethod
val getAMethodModifierList = getAMethod.modifierList
TestCase.assertTrue(getAMethodModifierList.textOffset > 0)
TestCase.assertFalse(getAMethodModifierList.textRange.isEmpty)
TestCase.assertEquals(getAMethodModifierList.textOffset, getAMethodModifierList.textRange.startOffset)
TestCase.assertEquals("@MyAnnotation", getAMethodModifierList.text)
val ktClass = aClass.sourcePsi as KtClassOrObject
val ktProperty = ktClass.declarations.filterIsInstance<KtProperty>().single()
val ktPropertyAccessorModifierList = ktProperty.getter!!.modifierList!!
TestCase.assertEquals(getAMethodModifierList.textOffset, ktPropertyAccessorModifierList.textOffset)
TestCase.assertEquals(getAMethodModifierList.textRange, ktPropertyAccessorModifierList.textRange)
}
fun checkFinalModifierOnEnumMembers(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
enum class Event {
ON_CREATE, ON_START, ON_STOP, ON_DESTROY;
companion object {
@JvmStatic
fun upTo(state: State): Event? {
return when(state) {
State.ENQUEUED -> ON_CREATE
State.RUNNING -> ON_START
State.BLOCKED -> ON_STOP
else -> null
}
}
}
}
enum class State {
ENQUEUED, RUNNING, SUCCEEDED, FAILED, BLOCKED, CANCELLED;
val isFinished: Boolean
get() = this == SUCCEEDED || this == FAILED || this == CANCELLED
fun isAtLeast(state: State): Boolean {
return compareTo(state) >= 0
}
companion object {
fun done(state: State) = state.isFinished
}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val upTo = uFile.findElementByTextFromPsi<UMethod>("upTo", strict = false)
.orFail("can't find fun upTo")
TestCase.assertTrue(upTo.javaPsi.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(upTo.javaPsi.containingClass!!.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(upTo.javaPsi.parameterList.parameters[0].annotations.any { it.isNotNull })
val isFinished = uFile.findElementByTextFromPsi<UMethod>("isFinished", strict = false)
.orFail("can't find accessor isFinished")
TestCase.assertTrue(isFinished.javaPsi.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(isFinished.javaPsi.containingClass!!.hasModifier(JvmModifier.FINAL))
val isAtLeast = uFile.findElementByTextFromPsi<UMethod>("isAtLeast", strict = false)
.orFail("can't find fun isAtLeast")
TestCase.assertTrue(isAtLeast.javaPsi.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(isAtLeast.javaPsi.containingClass!!.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(isAtLeast.javaPsi.parameterList.parameters[0].annotations.any { it.isNotNull })
val done = uFile.findElementByTextFromPsi<UMethod>("done", strict = false)
.orFail("can't find fun done")
TestCase.assertTrue(done.javaPsi.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(done.javaPsi.containingClass!!.hasModifier(JvmModifier.FINAL))
TestCase.assertTrue(done.javaPsi.parameterList.parameters[0].annotations.any { it.isNotNull })
}
fun checkThrowsList(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
abstract class Base
class MyException : Exception()
class Test
@Throws(MyException::class)
constructor(
private val p1: Int
) : Base() {
@Throws(MyException::class)
fun readSomething(file: File) {
throw MyException()
}
@get:Throws(MyException::class)
val foo : String = "42"
val boo : String = "42"
@Throws(MyException::class)
get
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val aClass = uFile.findElementByTextFromPsi<UClass>("Test", strict = false)
.orFail("can't find class Test")
val visitedMethod = mutableListOf<UMethod>()
aClass.accept(object : AbstractUastVisitor() {
override fun visitMethod(node: UMethod): Boolean {
visitedMethod.add(node)
val throwTypes = node.javaPsi.throwsList.referencedTypes
TestCase.assertEquals(node.name, 1, throwTypes.size)
TestCase.assertEquals("MyException", throwTypes.single().className)
return super.visitMethod(node)
}
})
TestCase.assertNotNull(visitedMethod.singleOrNull { it.isConstructor })
TestCase.assertNotNull(visitedMethod.singleOrNull { it.name == "readSomething" })
TestCase.assertNotNull(visitedMethod.singleOrNull { it.name == "getFoo" })
TestCase.assertNotNull(visitedMethod.singleOrNull { it.name == "getBoo" })
}
fun checkComparatorInheritor(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
class Foo(val x : Int)
class FooComparator : Comparator<Foo> {
override fun compare(firstFoo: Foo, secondFoo: Foo): Int =
firstFoo.x - secondFoo.x
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val fooComparator = uFile.findElementByTextFromPsi<UClass>("FooComparator", strict = false)
.orFail("can't find class FooComparator")
val lc = fooComparator.javaPsi
TestCase.assertTrue(lc.extendsList?.referenceElements?.isEmpty() == true)
TestCase.assertTrue(lc.implementsList?.referenceElements?.size == 1)
TestCase.assertEquals("java.util.Comparator<Foo>", lc.implementsList?.referenceElements?.single()?.reference?.canonicalText)
}
fun checkBoxedReturnTypeWhenOverridingNonPrimitive(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
abstract class ActivityResultContract<I, O> {
abstract fun parseResult(resultCode: Int, intent: Intent?): O
}
interface Intent
class StartActivityForResult : ActivityResultContract<Intent, Boolean>() {
override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
return resultCode == 42
}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val sub = uFile.findElementByTextFromPsi<UClass>("StartActivityForResult", strict = false)
.orFail("can't find class StartActivityForResult")
val mtd = sub.methods.find { it.name == "parseResult" }
.orFail("can't find method parseResult")
TestCase.assertEquals("java.lang.Boolean", mtd.returnType?.canonicalText)
}
private fun checkPsiType(psiType: PsiType, fqName: String = "TypeAnnotation") {
TestCase.assertEquals(1, psiType.annotations.size)
val annotation = psiType.annotations[0]
TestCase.assertEquals(fqName, annotation.qualifiedName)
}
fun checkAnnotationOnPsiType(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
@Target(AnnotationTarget.TYPE)
annotation class TypeAnnotation
interface State<out T> {
val value: T
}
fun test(
i : @TypeAnnotation Int?,
s : @TypeAnnotation String?,
vararg vs : @TypeAnnotation Any,
): @TypeAnnotation State<String> {
return object : State<String> {
override val value: String = i?.toString() ?: s ?: "42"
}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val test = uFile.findElementByTextFromPsi<UMethod>("test", strict = false)
.orFail("can't find fun test")
val lightMethod = test.javaPsi
TestCase.assertNotNull(lightMethod.returnType)
checkPsiType(lightMethod.returnType!!)
lightMethod.parameterList.parameters.forEach { psiParameter ->
val psiTypeToCheck = (psiParameter.type as? PsiArrayType)?.componentType ?: psiParameter.type
checkPsiType(psiTypeToCheck)
}
}
fun checkAnnotationOnPsiTypeArgument(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
@Target(AnnotationTarget.TYPE)
annotation class TypeAnnotation
fun test(
ins : List<@TypeAnnotation Int>,
): Array<@TypeAnnotation String> {
return ins.map { it.toString() }.toTypedArray()
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val test = uFile.findElementByTextFromPsi<UMethod>("test", strict = false)
.orFail("can't find fun test")
val lightMethod = test.javaPsi
fun firstTypeArgument(psiType: PsiType?): PsiType? =
(psiType as? PsiClassType)?.parameters?.get(0)
?: (psiType as? PsiArrayType)?.componentType
TestCase.assertNotNull(lightMethod.returnType)
checkPsiType(firstTypeArgument(lightMethod.returnType)!!)
lightMethod.parameterList.parameters.forEach { psiParameter ->
checkPsiType(firstTypeArgument(psiParameter.type)!!)
}
}
fun checkUpperBoundWildcardForCtor(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
class FrameData(
frameStartNanos: Long,
frameDurationUiNanos: Long,
isJank: Boolean,
val states: List<StateInfo>
)
class StateInfo(val key: String, val value: String)
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val cls = uFile.findElementByTextFromPsi<UClass>("FrameData", strict = false)
.orFail("can't find class FrameData")
val ctor = cls.javaPsi.constructors.single()
val states = ctor.parameterList.parameters.last()
TestCase.assertEquals("java.util.List<StateInfo>", states.type.canonicalText)
}
fun checkUpperBoundWildcardForEnum(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
enum class PowerCategoryDisplayLevel {
BREAKDOWN, TOTAL
}
enum class PowerCategory {
CPU, MEMORY
}
class PowerMetric {
companion object {
@JvmStatic
fun Battery(): Type.Battery {
return Type.Battery()
}
@JvmStatic
fun Energy(
categories: Map<PowerCategory, PowerCategoryDisplayLevel> = emptyMap()
): Type.Energy {
return Type.Energy(categories)
}
@JvmStatic
fun Power(
categories: Map<PowerCategory, PowerCategoryDisplayLevel> = emptyMap()
): Type.Power {
return Type.Power(categories)
}
}
sealed class Type(var categories: Map<PowerCategory, PowerCategoryDisplayLevel> = emptyMap()) {
class Power(
powerCategories: Map<PowerCategory, PowerCategoryDisplayLevel> = emptyMap()
) : Type(powerCategories)
class Energy(
energyCategories: Map<PowerCategory, PowerCategoryDisplayLevel> = emptyMap()
) : Type(energyCategories)
class Battery : Type()
}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
uFile.accept(object : AbstractUastVisitor() {
override fun visitParameter(node: UParameter): Boolean {
val lc = node.javaPsi as? PsiParameter ?: return super.visitParameter(node)
val t = lc.type.canonicalText
if (t.contains("Map")) {
TestCase.assertEquals("java.util.Map<PowerCategory,? extends PowerCategoryDisplayLevel>", t)
}
return super.visitParameter(node)
}
})
}
fun checkUpperBoundWildcardForVar(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
abstract class RoomDatabase {
@JvmField
protected var mCallbacks: List<Callback>? = null
abstract class Callback {
open fun onCreate(db: RoomDatabase) {}
}
}
val sum: (Int) -> Int = { x: Int -> sum(x - 1) + x }
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val fld = uFile.findElementByTextFromPsi<UField>("mCallbacks", strict = false)
.orFail("can't find var mCallbacks")
val mCallbacks = fld.javaPsi as? PsiField
TestCase.assertEquals("java.util.List<? extends RoomDatabase.Callback>", mCallbacks?.type?.canonicalText)
val top = uFile.findElementByTextFromPsi<UField>("sum", strict = false)
.orFail("can't find val sum")
val sum = top.javaPsi as? PsiField
TestCase.assertEquals("kotlin.jvm.functions.Function1<java.lang.Integer,java.lang.Integer>", sum?.type?.canonicalText)
}
fun checkUpperBoundForRecursiveTypeParameter(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
interface Alarm {
interface Builder<Self : Builder<Self>> {
fun build(): Alarm
}
}
abstract class AbstractAlarm<
Self : AbstractAlarm<Self, Builder>, Builder : AbstractAlarm.Builder<Builder, Self>>
internal constructor(
val identifier: String,
) : Alarm {
abstract class Builder<Self : Builder<Self, Built>, Built : AbstractAlarm<Built, Self>> : Alarm.Builder<Self> {
private var identifier: String = ""
fun setIdentifier(text: String): Self {
this.identifier = text
return this as Self
}
final override fun build(): Built = TODO()
}
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val abstractAlarm = uFile.findElementByTextFromPsi<UClass>("AbstractAlarm", strict = false)
.orFail("cant find AbstractAlarm")
val builder = abstractAlarm.innerClasses.find { it.name == "Builder" }
.orFail("cant find AbstractAlarm.Builder")
TestCase.assertEquals(2, builder.javaPsi.typeParameters.size)
val self = builder.javaPsi.typeParameters[0]
TestCase.assertEquals(
"AbstractAlarm.Builder<Self,Built>",
self.bounds.joinToString { (it as? PsiType)?.canonicalText ?: "??" }
)
val built = builder.javaPsi.typeParameters[1]
TestCase.assertEquals(
"AbstractAlarm<Built,Self>",
built.bounds.joinToString { (it as? PsiType)?.canonicalText ?: "??" }
)
}
fun checkDefaultValueOfAnnotation(myFixture: JavaCodeInsightTestFixture) {
myFixture.configureByText(
"main.kt", """
annotation class IntDef(
vararg val value: Int = [],
val flag: Boolean = false,
val open: Boolean = false
)
@IntDef(value = [DisconnectReasons.ENGINE_DIED, DisconnectReasons.ENGINE_DETACHED])
annotation class DisconnectReason
object DisconnectReasons {
const val ENGINE_DIED: Int = 1
const val ENGINE_DETACHED: Int = 2
}
""".trimIndent()
)
val uFile = myFixture.file.toUElement()!!
val klass = uFile.findElementByTextFromPsi<UClass>("class DisconnectReason", strict = false)
.orFail("cant convert to UClass")
val lc = klass.uAnnotations.single().javaPsi!!
val intValues = (lc.findAttributeValue("value") as? PsiArrayInitializerMemberValue)?.initializers
TestCase.assertEquals(
"[1, 2]",
intValues?.joinToString(separator = ", ", prefix = "[", postfix = "]") { annoValue ->
(annoValue as? PsiLiteral)?.value?.toString() ?: annoValue.text
}
)
val flagValue = (lc.findAttributeValue("flag") as? PsiLiteral)?.value
TestCase.assertEquals("false", flagValue?.toString())
}
} | 251 | null | 5079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 26,563 | intellij-community | Apache License 2.0 |
app/src/main/java/com/kyberswap/android/domain/usecase/profile/SubmitUserInfoUseCase.kt | KYRDTeam | 181,612,742 | false | null | package com.kyberswap.android.domain.usecase.profile
import androidx.annotation.VisibleForTesting
import com.kyberswap.android.domain.SchedulerProvider
import com.kyberswap.android.domain.model.KycResponseStatus
import com.kyberswap.android.domain.model.UserInfo
import com.kyberswap.android.domain.repository.UserRepository
import com.kyberswap.android.domain.usecase.SequentialUseCase
import io.reactivex.Single
import javax.inject.Inject
class ReSubmitUserInfoUseCase @Inject constructor(
schedulerProvider: SchedulerProvider,
private val userRepository: UserRepository
) : SequentialUseCase<ReSubmitUserInfoUseCase.Param, KycResponseStatus>(schedulerProvider) {
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
override fun buildUseCaseSingle(param: Param): Single<KycResponseStatus> {
return userRepository.reSubmit(param)
}
class Param(val user: UserInfo)
}
| 1 | null | 10 | 26 | abd4ab033d188918849e5224cc8204409776391b | 913 | android-app | MIT License |
app/src/main/java/br/com/brqtest/viewkotlin/MainActivity.kt | legionario07 | 160,038,188 | false | {"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 16, "Java": 1, "XML": 32} | package br.com.brqtest.viewkotlin
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.widget.AdapterView
import android.widget.ListView
import br.com.brqtest.R
import br.com.brqtest.adapterkotlin.ClienteAdapter
import br.com.brqtest.databasekotlin.DatabaseHelper
import br.com.brqtest.databasekotlin.dao.ClienteDao
import br.com.brqtest.modelkotlin.Cliente
import br.com.brqtest.viewkotlin.ClienteDetailActivity
import java.io.Serializable
import java.sql.SQLException
class MainActivity : AppCompatActivity() {
private var lstView: ListView? = null
private lateinit var clientes: List<Cliente>
private var clienteAdapter: ClienteAdapter? = null
private var dh: DatabaseHelper? = null
private var clienteDao: ClienteDao? = null
private val detailCustomer = AdapterView.OnItemClickListener { parent, view, position, id ->
val cliente = lstView!!.getItemAtPosition(position) as Cliente
val i = Intent(applicationContext, ClienteDetailActivity::class.java)
i.putExtra(CLIENTE_DETAIL, cliente as Serializable)
startActivity(i)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fab = findViewById<FloatingActionButton>(R.id.fabNovoCliente)
fab.setOnClickListener {
val i = Intent(this@MainActivity, ClienteDetailActivity::class.java)
startActivity(i)
}
dh = DatabaseHelper(this@MainActivity)
try {
clienteDao = ClienteDao(dh!!.connectionSource)
clientes = clienteDao!!.queryForAll()
} catch (e: SQLException) {
e.printStackTrace()
}
lstView = findViewById(R.id.lstClientes)
lstView!!.onItemClickListener = detailCustomer
createOrUpdateListView()
}
private fun createOrUpdateListView() {
if (clienteAdapter == null) {
clienteAdapter = ClienteAdapter(this, clientes)
lstView!!.adapter = clienteAdapter
} else {
clienteAdapter!!.notifyDataSetChanged()
}
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
companion object {
private val CLIENTE_DETAIL = "CLIENTE_DETAIL"
}
}
| 0 | Kotlin | 0 | 0 | cde55f2e00fa7a3269493395d9ce567b7f861166 | 2,442 | BrqTestMobile | MIT License |
mqtt/src/main/java/com/song/sunset/mqtt/MqttSongService.kt | songmingwen | 70,653,066 | false | {"Gradle": 28, "Java Properties": 3, "Shell": 3, "Ignore List": 17, "Batchfile": 2, "Markdown": 6, "INI": 13, "Proguard": 12, "Kotlin": 171, "XML": 276, "JSON": 13, "Java": 578, "CMake": 2, "C++": 17, "C": 43, "GLSL": 10, "AIDL": 7, "YAML": 1, "Dart": 11, "OpenStep Property List": 4, "Objective-C": 5, "Ruby": 3, "Groovy": 1} | package com.song.sunset.mqtt
import android.app.Service
import android.content.Intent
import android.os.IBinder
/**
* Desc:
* Author: songmingwen
* Email: [email protected]
* Time: 2021/5/31 10:07
*/
class MqttSongService : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
} | 0 | Java | 0 | 1 | 8735ab6b8bc4d48c38533d6a9b7e88cef18c8389 | 329 | Comic | Apache License 2.0 |
app/src/main/java/kashyap/in/yajurvedaproject/pdfviewer/PdfViewerActivity.kt | KashyapBhat | 249,988,816 | false | {"Gradle": 4, "XML": 189, "Java Properties": 4, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "JSON": 2, "Proguard": 1, "Kotlin": 38, "Java": 11, "INI": 3} | package kashyap.`in`.yajurvedaproject.pdfviewer
import android.annotation.SuppressLint
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.location.Location
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.SeekBar
import androidx.annotation.RequiresApi
import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomnavigation.BottomNavigationView
import kashyap.`in`.yajurvedaproject.R
import kashyap.`in`.yajurvedaproject.base.BaseActivity
import kashyap.`in`.yajurvedaproject.common.*
import kashyap.`in`.yajurvedaproject.custom.CustomPdfAdapter
import kashyap.`in`.yajurvedaproject.custom.CustomPdfViewer
import kashyap.`in`.yajurvedaproject.receivers.NetworkReceiver
import kashyap.`in`.yajurvedaproject.utils.GeneralUtils.Companion.changeButtonPosition
import kashyap.`in`.yajurvedaproject.utils.GeneralUtils.Companion.shareApp
import kashyap.`in`.yajurvedaproject.utils.GeneralUtils.Companion.slideDown
import kashyap.`in`.yajurvedaproject.utils.GeneralUtils.Companion.slideUp
import kashyap.`in`.yajurvedaproject.utils.PrefUtils
import kashyap.`in`.yajurvedaproject.webview.CustomWebViewClient
import kashyap.`in`.yajurvedaproject.worker.AlarmWorker
import kotlinx.android.synthetic.main.activity_pdf_viewer.*
import java.io.File
import java.util.*
class PdfViewerActivity : BaseActivity(), CustomWebViewClient.WebViewClientIntf,
BottomNavigationView.OnNavigationItemSelectedListener, PdfViewerContract.PdfView {
private lateinit var pdfViewerPresenter: PdfViewerPresenterImpl
private lateinit var pdfViewPager: CustomPdfViewer
private lateinit var pdfViewAdapter: CustomPdfAdapter
private var pdfViewPagerPosition: Int = 0
private var brightness: Int = 0
private var navBarShouldGoUp: Boolean = false
private var isShowingSeekbar: Boolean = false
private var loadComplete: Boolean = false
private var file: File? = null
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
setContentView(R.layout.activity_pdf_viewer)
pdfViewerPresenter = PdfViewerPresenterImpl(this, this)
pdfViewerPresenter.setUpWebview(wvPdfRenderer, this)
setBottomNavForFirstTime()
changeSeekBarVisibility(View.GONE)
checkPermissionsAndRun()
}
private fun setBottomNavForFirstTime() {
bottomNav.setOnNavigationItemSelectedListener(this)
showOrHideOptions()
buttonOptions.setOnClickListener {
showOrHideOptions()
}
}
private fun startProcesses() {
if (pdfViewerPresenter.containsFile())
file = File(
context.filesDir,
pdfViewerPresenter.getFilePath()
)
if (NetworkReceiver.isNetworkAvailable(this)) {
if (!loadComplete)
pdfViewerPresenter.getPath()
} else {
if (file != null && file?.exists() == true) {
openViewToShowPdf(file, "")
} else {
showSnackBar(
getString(R.string.internet_not_connected),
getString(
R.string.retry
),
Runnable { startProcesses() })
}
}
}
override fun onDestroy() {
super.onDestroy()
(pdfViewPager.adapter as CustomPdfAdapter)?.close()
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
MENU_ONE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
handleBrightness()
checkSeekbarIsVisibleAndShow()
} else {
changeSeekBarVisibility(View.GONE)
showSnackBar(
getString(R.string.not_below_m),
getString(R.string.sorry),
null
)
}
return true
}
MENU_TWO -> {
changeOrientation()
showOrHideOptions()
return true
}
MENU_THREE -> {
pdfViewerPresenter.checkForReminderAndAdd()
return true
}
MENU_FOUR -> {
shareApp(this)
return true
}
}
return false
}
override fun setRemainder() {
val calendar = Calendar.getInstance()
val timePickerDialog = TimePickerDialog(
context,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE), false
)
timePickerDialog.setTitle("Set Alarm Time")
timePickerDialog.show()
}
private var onTimeSetListener: OnTimeSetListener =
OnTimeSetListener { _, hourOfDay, minute ->
AlarmWorker.startLogoutWorker(
context, hourOfDay, minute, REMINDER_WORKER
)
PrefUtils.saveToPrefs(context, IS_REMINDER_ALREADY_SET, true)
showSnackBar(
"Alarm set for $hourOfDay : $minute",
"Okay",
null
)
}
private fun checkSeekbarIsVisibleAndShow() {
if (pdfViewerPresenter.checkChangeSettingsGranted() && !isShowingSeekbar) {
isShowingSeekbar = true
changeSeekBarVisibility(View.VISIBLE)
} else {
isShowingSeekbar = false
changeSeekBarVisibility(View.GONE)
}
}
override fun openViewToShowPdf(file: File?, url: String) {
hideProgress()
if (file == null || loadComplete)
return
showProgress()
setUpPagerAdapter(url)
}
private fun setUpPagerAdapter(url: String) {
try {
file = File(
context.filesDir,
pdfViewerPresenter.getFilePath()
)
if (file?.exists() == true) {
pdfViewPager = CustomPdfViewer(this, file?.absolutePath)
pdfViewAdapter = pdfViewPager.adapter as CustomPdfAdapter
llPdfRoot.addView(pdfViewPager)
(pdfViewPager as ViewPager).currentItem = 0
(pdfViewPager as ViewPager).setOnPageChangeListener(object :
ViewPager.OnPageChangeListener {
override fun onPageSelected(position: Int) {
pdfViewPagerPosition = position
}
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int, positionOffset: Float,
positionOffsetPixels: Int
) {
}
})
} else {
loadWV(url.trim())
}
} catch (e: Exception) {
loadWV(url.trim())
}
loadComplete = true
}
private fun loadWV(url: String) {
if (url.isEmpty())
return
val endUrl: String = pdfViewerPresenter.getFormattedUrlToRender(url)
llPdfRoot?.visibility = View.GONE
wvPdfRenderer?.visibility = View.VISIBLE
wvPdfRenderer?.loadUrl(endUrl.trim())
}
private fun handleBrightness() {
brightness =
Settings.System.getInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
seekBar.progress = brightness
pdfViewerPresenter.checkChangeSettingsGranted()
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
@RequiresApi(Build.VERSION_CODES.M)
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (pdfViewerPresenter.checkChangeSettingsGranted())
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS, progress
)
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
}
private fun changeSeekBarVisibility(visibility: Int) {
rlSeekBar.visibility = visibility
seekBar.visibility = visibility
}
private fun showOrHideOptions() {
if (navBarShouldGoUp) {
bottomNav.visibility = View.VISIBLE
bottomBar.visibility = View.VISIBLE
slideUp(bottomNav)
changeButtonPosition(this, buttonOptions, 70)
} else {
slideDown(bottomNav)
bottomNav.visibility = View.GONE
bottomBar.visibility = View.GONE
if (isShowingSeekbar) {
changeSeekBarVisibility(View.GONE)
isShowingSeekbar = false
}
changeButtonPosition(this, buttonOptions, 15)
}
navBarShouldGoUp = !navBarShouldGoUp
}
override fun networkChanged() {
checkPermissionsAndRun()
}
override fun onAllPermissionsAcquired() {
startProcesses()
}
override fun onLocationResult(location: Location?) {
}
override fun loadingStarted() {
}
override fun loadingEnded() {
hideProgress()
}
override fun showToast(title: String, actionText: String, runnable: Runnable?) {
showSnackBar(title, actionText, runnable)
}
override fun showLoading() {
showProgress()
}
override fun hideLoading() {
hideProgress()
}
}
| 1 | null | 1 | 1 | b43ff8e66299de744e57d0877fa17cc168f6ea69 | 10,127 | YajurVedaApp | Apache License 2.0 |
src/main/kotlin/com/github/projectsandstone/api/scheduler/SandstoneExecutorService.kt | ProjectSandstone | 65,579,594 | false | null | /*
* SandstoneAPI - Minecraft Server Modding API
*
* The MIT License (MIT)
*
* Copyright (c) Sandstone <https://github.com/ProjectSandstone/>
* Copyright (c) contributors
*
*
* 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.projectsandstone.api.scheduler
import java.util.concurrent.Callable
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
* A [ScheduledExecutorService] backed by Sandstone [Sandstone Scheduler Manager][Scheduler].
*/
interface SandstoneExecutorService : ScheduledExecutorService {
override fun <V : Any?> schedule(callable: Callable<V>, delay: Long, unit: TimeUnit): ScheduledFutureTask<V>
override fun schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFutureTask<*>
override fun scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFutureTask<*>
override fun scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledFutureTask<*>
} | 6 | Kotlin | 0 | 2 | 02d1d0fcc44c8e05741798af5b6f7408ebf48670 | 2,181 | SandstoneAPI | MIT License |
src/main/kotlin/com/github/projectsandstone/api/scheduler/SandstoneExecutorService.kt | ProjectSandstone | 65,579,594 | false | null | /*
* SandstoneAPI - Minecraft Server Modding API
*
* The MIT License (MIT)
*
* Copyright (c) Sandstone <https://github.com/ProjectSandstone/>
* Copyright (c) contributors
*
*
* 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.projectsandstone.api.scheduler
import java.util.concurrent.Callable
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
* A [ScheduledExecutorService] backed by Sandstone [Sandstone Scheduler Manager][Scheduler].
*/
interface SandstoneExecutorService : ScheduledExecutorService {
override fun <V : Any?> schedule(callable: Callable<V>, delay: Long, unit: TimeUnit): ScheduledFutureTask<V>
override fun schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFutureTask<*>
override fun scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFutureTask<*>
override fun scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledFutureTask<*>
} | 6 | Kotlin | 0 | 2 | 02d1d0fcc44c8e05741798af5b6f7408ebf48670 | 2,181 | SandstoneAPI | MIT License |
subprojects/delivery/nupokati/src/gradleTest/kotlin/com/avito/android/NupokatiPluginV3IntegrationTest.kt | avito-tech | 230,265,582 | false | null | package com.avito.android
import com.avito.http.HttpCodes
import com.avito.test.gradle.TestProjectGenerator
import com.avito.test.gradle.git
import com.avito.test.gradle.gradlew
import com.avito.test.gradle.module.AndroidAppModule
import com.avito.test.gradle.plugin.plugins
import com.avito.test.http.Mock
import com.avito.test.http.MockDispatcher
import com.avito.test.http.MockWebServerFactory
import okhttp3.mockwebserver.MockResponse
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
internal class NupokatiPluginV3IntegrationTest {
private val mockDispatcher = MockDispatcher()
private val mockWebServer = MockWebServerFactory.create().apply {
dispatcher = mockDispatcher
}
@AfterEach
fun cleanup() {
mockWebServer.shutdown()
}
@Test
@Disabled("MBSA-743")
fun `uploadCdBuildResult - json contains required data`(@TempDir projectDir: File) {
val outputDescriptorPath =
mockWebServer.url("/artifactory/mobile-releases/avito_android/118.0_2/release_info.json")
val releaseVersion = "118.0"
@Language("json")
val cdConfig = """
|{
| "schema_version": 3,
| "project": "avito",
| "release_version": "$releaseVersion",
| "output_descriptor": {
| "path": "$outputDescriptorPath",
| "skip_upload": false
| },
| "deployments": [
| {
| "type": "app-binary",
| "store": "ru-store",
| "file_type": "apk",
| "build_configuration": "release"
| },
| {
| "type": "app-binary",
| "store": "google-play",
| "file_type": "bundle",
| "build_configuration": "release"
| },
| {
| "type": "artifact",
| "file_type": "json",
| "kind": "feature-toggles"
| }
| ]
|}""".trimMargin()
val cdConfigFile = File(projectDir, "cd-config.json").also { it.writeText(cdConfig) }
val mockWebServerUrl = mockWebServer.url("/")
val reportViewerFrontendUrl = "http://stub.com"
val planSlug = "AvitoAndroid"
val jobSlug = "FunctionalTest"
val runId = "someId"
val teamcityUrl = "http://teamcity.ru"
val versionCode = 122
TestProjectGenerator(
plugins = plugins {
id("com.avito.android.gradle-logger")
},
modules = listOf(
AndroidAppModule(
name = "app",
plugins = plugins {
id("com.avito.android.qapps")
id("com.avito.android.nupokati")
},
versionCode = versionCode,
useKts = true,
imports = listOf(
"import com.avito.reportviewer.model.ReportCoordinates",
"import com.avito.android.artifactory_backup.ArtifactoryBackupTask",
),
buildGradleExtra = """
|android {
| buildTypes {
| getByName("release") {
| isMinifyEnabled = true
| proguardFile("proguard.pro")
| }
| }
|}
|
|androidComponents {
| val release = selector().withBuildType("release")
| onVariants(release) { variant ->
| tasks.withType<ArtifactoryBackupTask>().configureEach {
| this.artifacts.add(
| variant.artifacts.get(com.android.build.api.artifact.SingleArtifact.BUNDLE)
| .map {
| com.avito.android.model.input.DeploymentV3.AppBinary(
| store = "google-play",
| buildConfiguration = "release",
| file = it.asFile,
| )
| }
| )
|
| this.artifacts.add(
| variant.artifacts.get(com.android.build.api.artifact.SingleArtifact.APK)
| .map {
| com.avito.android.model.input.DeploymentV3.AppBinary(
| store = "ru-store",
| buildConfiguration = "release",
| file = it.getApkOrThrow(),
| )
| }
| )
| }
| }
|}
|
|nupokati {
| cdBuildConfigFile.set(rootProject.file("${cdConfigFile.name}"))
| teamcityBuildUrl.set("$teamcityUrl")
|
| artifactory {
| login.set("user")
| password.set("<PASSWORD>")
| }
|
| reportViewer {
| frontendUrl.set("$reportViewerFrontendUrl")
| reportCoordinates.set(ReportCoordinates("$planSlug", "$jobSlug", "$runId"))
| }
|}
|
|afterEvaluate {
| tasks.withType<ArtifactoryBackupTask>().configureEach {
| this.artifacts.add(
| com.avito.android.model.input.DeploymentV3.Artifact(
| kind = "feature-toggles",
| file = layout.projectDirectory.file("feature_toggles.json").asFile,
| )
| )
| }
|}
|
|fun org.gradle.api.file.Directory.getApkOrThrow(): File {
| val dir = asFile
| val apks = dir.listFiles().orEmpty().filter { it.extension == "apk" }
|
| require(apks.size < 2) { "Multiple APK are not supported" }
| return requireNotNull(apks.firstOrNull()) { "APK not found" }
|}
|""".trimMargin()
)
)
).generateIn(projectDir)
File("$projectDir/app/feature_toggles.json").writeText("")
val branchName = "release_11"
projectDir.git("checkout -b $branchName")
val commit = projectDir.git("rev-parse HEAD").trim()
mockDispatcher.registerMock(
Mock(
requestMatcher = {
method == "PUT"
&& path == "/artifactory/mobile-releases/avito_android/118.0_2/app-release.aab"
},
response = MockResponse().setResponseCode(HttpCodes.OK)
)
)
mockDispatcher.registerMock(
Mock(
requestMatcher = {
method == "PUT"
&& path == "/artifactory/mobile-releases/avito_android/118.0_2/app-release-unsigned.apk"
},
response = MockResponse().setResponseCode(HttpCodes.OK)
)
)
mockDispatcher.registerMock(
Mock(
requestMatcher = {
method == "PUT"
&& path == "/artifactory/mobile-releases/avito_android/118.0_2/feature_toggles.json"
},
response = MockResponse().setResponseCode(HttpCodes.OK)
)
)
val contractJson = mockDispatcher.captureRequest(
Mock(
requestMatcher = {
method == "PUT" && path == "/artifactory/mobile-releases/avito_android/118.0_2/release_info.json"
},
response = MockResponse().setResponseCode(200)
)
)
gradlew(
projectDir,
":app:nupokati",
expectFailure = true,
dryRun = false
)
.assertThat()
// TODO replace with success when MBSA-743
.outputContains("Fail to evaluate project. CdBuildConfigV3 currently unsupported")
.buildFailed()
// todo add QAPPS test
val expectedContract = """
|{
| "schema_version": 3,
| "teamcity_build_url": "$teamcityUrl",
| "build_number": "$versionCode",
| "release_version": "$releaseVersion",
| "git_branch": {
| "name": "$branchName",
| "commit_hash": "$commit"
| },
| "test_results": {
| "report_url": "$reportViewerFrontendUrl/report/$planSlug/$jobSlug/$runId?q=eyJmaWx0ZXIiOnsic2tpcCI6MH19",
| "report_coordinates": {
| "plan_slug": "$planSlug",
| "job_slug": "$jobSlug",
| "run_id": "$runId"
| }
| },
| "artifacts": [
| {
| "store": "ru-store",
| "type": "app-binary",
| "file_type": "apk",
| "name": "app-release-unsigned.apk",
| "uri": "${mockWebServerUrl}artifactory/mobile-releases/avito_android/118.0_2/app-release-unsigned.apk",
| "build_configuration": "release"
| },
| {
| "store": "google-play",
| "type": "app-binary",
| "file_type": "bundle",
| "name": "app-release.aab",
| "uri": "${mockWebServerUrl}artifactory/mobile-releases/avito_android/118.0_2/app-release.aab",
| "build_configuration": "release"
| },
| {
| "type": "artifact",
| "file_type": "json",
| "name": "feature_toggles.json",
| "uri": "${mockWebServerUrl}artifactory/mobile-releases/avito_android/118.0_2/feature_toggles.json",
| "kind" : "feature-toggles"
| }
| ]
|}
|""".trimMargin()
contractJson.checks.singleRequestCaptured().jsonEquals(expectedContract)
}
}
| 10 | null | 50 | 414 | 4dc43d73134301c36793e49289305768e68e645b | 11,290 | avito-android | MIT License |
plugins/kotlin/idea/tests/testData/intentions/removeLabeledReturnInLambda/notLastLine.kt | ingokegel | 72,937,917 | false | null | // WITH_STDLIB
// IS_APPLICABLE: FALSE
fun foo() {
listOf(1,2,3).find {
<caret>1
return@find true
}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 126 | intellij-community | Apache License 2.0 |
src/main/kotlin/com/antwerkz/bottlerocket/configuration/types/TlsMode.kt | evanchooly | 36,263,772 | false | {"Kotlin": 95442, "Java": 4726} | package com.antwerkz.bottlerocket.configuration.types
enum class TlsMode {
DISABLED,
ALLOWTLS,
PREFERTLS,
REQUIRETLS
} | 4 | Kotlin | 1 | 2 | d1efedd8ff3424e2c5146f4a6739e3c705aa1a88 | 135 | bottlerocket | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.