path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/tools/translater/voicetranslator/phototranslator/dialog/RateAppDialog.kt
duythanh7903
855,522,486
false
{"Kotlin": 446428, "Java": 14470}
package com.tools.translater.voicetranslator.phototranslator.dialog import android.content.Context import android.graphics.Paint import com.tools.translater.voicetranslator.phototranslator.R import com.tools.translater.voicetranslator.phototranslator.app.AppConstants import com.tools.translater.voicetranslator.phototranslator.databinding.DialogRateAppBinding import com.tools.translater.voicetranslator.phototranslator.ui.bases.BaseDialog import com.tools.translater.voicetranslator.phototranslator.ui.bases.ext.click import com.tools.translater.voicetranslator.phototranslator.utils.SharePreferenceUtil class RateAppDialog(context: Context, val onRating: (star: Int) -> Unit) : BaseDialog<DialogRateAppBinding>( context, R.style.BaseDialog ) { override fun getLayoutDialog(): Int = R.layout.dialog_rate_app override fun initViews() { super.initViews() mBinding.tvLater.paintFlags = Paint.UNDERLINE_TEXT_FLAG } override fun onClickViews() { super.onClickViews() mBinding.imgStart1.click { SharePreferenceUtil.getInstance().setBooleanValue(AppConstants.IS_RATE, true) mBinding.imgStart1.setImageResource(R.drawable.ic_star_active) mBinding.imgStart2.setImageResource(R.drawable.ic_star_inactive) mBinding.imgStart3.setImageResource(R.drawable.ic_star_inactive) mBinding.imgStart4.setImageResource(R.drawable.ic_star_inactive) mBinding.imgStart5.setImageResource(R.drawable.ic_star_inactive) onRating.invoke(1) dismiss() } mBinding.imgStart2.click { SharePreferenceUtil.getInstance().setBooleanValue(AppConstants.IS_RATE, true) mBinding.imgStart1.setImageResource(R.drawable.ic_star_active) mBinding.imgStart2.setImageResource(R.drawable.ic_star_active) mBinding.imgStart3.setImageResource(R.drawable.ic_star_inactive) mBinding.imgStart4.setImageResource(R.drawable.ic_star_inactive) mBinding.imgStart5.setImageResource(R.drawable.ic_star_inactive) onRating.invoke(2) dismiss() } mBinding.imgStart3.click { SharePreferenceUtil.getInstance().setBooleanValue(AppConstants.IS_RATE, true) mBinding.imgStart1.setImageResource(R.drawable.ic_star_active) mBinding.imgStart2.setImageResource(R.drawable.ic_star_active) mBinding.imgStart3.setImageResource(R.drawable.ic_star_active) mBinding.imgStart4.setImageResource(R.drawable.ic_star_inactive) mBinding.imgStart5.setImageResource(R.drawable.ic_star_inactive) onRating.invoke(3) dismiss() } mBinding.imgStart4.click { mBinding.imgStart1.setImageResource(R.drawable.ic_star_active) mBinding.imgStart2.setImageResource(R.drawable.ic_star_active) mBinding.imgStart3.setImageResource(R.drawable.ic_star_active) mBinding.imgStart4.setImageResource(R.drawable.ic_star_active) mBinding.imgStart5.setImageResource(R.drawable.ic_star_inactive) onRating.invoke(4) dismiss() } mBinding.imgStart5.click { mBinding.imgStart1.setImageResource(R.drawable.ic_star_active) mBinding.imgStart2.setImageResource(R.drawable.ic_star_active) mBinding.imgStart3.setImageResource(R.drawable.ic_star_active) mBinding.imgStart4.setImageResource(R.drawable.ic_star_active) mBinding.imgStart5.setImageResource(R.drawable.ic_star_active) onRating.invoke(5) dismiss() } mBinding.tvLater.click { dismiss() } } }
0
Kotlin
0
0
90a8751993394942730a8316ff752720d4077626
3,757
temp
MIT License
src/main/kotlin/C_0073d840.kt
argcc
777,572,651
false
{"Kotlin": 757710}
package org.example class C_0073d840 : C_0073d860 { var hash_map_1 = mutableMapOf<Any, Any>() var vector_1 = mutableListOf<C_0073d880>() constructor(device: IDirect3DDevice7?) : super() { IDirect3DDevice7 = device device?.AddRef() IDirect3DDevice7?.GetCaps(D3DDEVICEDESC7) val data = mutableListOf<TextureStageStateInfo>() for (i in 0..<9) { val ok = GetTextureStageStateInfo(data, i) if (ok != 0) { CreateStates(data, i, 0/*?*/) } } } fun CreateStates(data: MutableList<TextureStageStateInfo>, id: Int, param_3: Int) { var count = 0u if (param_3 == 0) { count = D3DDEVICEDESC7.wMaxSimultaneousTextures.toUInt() if (count >= data.size.toUInt()) { count = data.size.toUInt() } } else { count = data.size.toUInt() if (count > 1u) { count = 1u } } //TODO создание массива val device = IDirect3DDevice7!! device.BeginStateBlock() for (i in 0u..<count) { val info = data[i.toInt()] if (info.color_options_enabled != 0) { val opCaps = D3DDEVICEDESC7.dwTextureOpCaps if ((info.colorop and opCaps) == 0u || (info.alphaop and opCaps) == 0u ) { //TODO расширение массива? count = i break } device.SetTextureStageState(i, D3DTSS_COLOROP, info.colorop) device.SetTextureStageState(i, D3DTSS_COLORARG1, info.colorarg1) device.SetTextureStageState(i, D3DTSS_COLORARG2, info.colorarg2) device.SetTextureStageState(i, D3DTSS_ALPHAOP, info.alphaop) device.SetTextureStageState(i, D3DTSS_ALPHAARG1, info.alphaarg1) device.SetTextureStageState(i, D3DTSS_ALPHAARG2, info.alphaarg2) } } device.SetTextureStageState(count, D3DTSS_COLOROP, D3DTOP_DISABLE) device.SetTextureStageState(count, D3DTSS_ALPHAOP, D3DTOP_DISABLE) var stateBlock = Ptr(0u) device.EndStateBlock(stateBlock) //TODO массив = stateBlock if (count < data.size.toUInt()) { for (i in count..<data.size.toUInt()) { val info = data[i.toInt()] device.BeginStateBlock() if (info.blend_options_enabled != 0) { device.SetRenderState(D3DRENDERSTATE_SRCBLEND, info.srcblend) device.SetRenderState(D3DRENDERSTATE_DESTBLEND, info.dstblend) } device.EndStateBlock(stateBlock) //TODO массив = stateBlock } } val C_0073d880 = C_0073d880() //C_0073d880.vector_1 = //TODO массив C_0073d880.texture_stages = data C_0073d880.count = count vector_1.add(C_0073d880) //TODO } fun GetTextureStageStateInfo(data: MutableList<TextureStageStateInfo>, id: Int): Int { data.clear() return when (id) { 0, 8 -> 1 1 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_MODULATE i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.alphaarg1 = D3DTA_TEXTURE i.alphaarg2 = D3DTA_CURRENT i.blend_options_enabled = 1 i.srcblend = D3DBLEND_DESTCOLOR i.dstblend = D3DBLEND_ZERO data.add(i) 1 } 2 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_MODULATE i.colorarg1 = D3DTA_TEXTURE or D3DTA_ALPHAREPLICATE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.alphaarg1 = D3DTA_TEXTURE i.alphaarg2 = D3DTA_CURRENT i.blend_options_enabled = 1 i.srcblend = D3DBLEND_ZERO i.dstblend = D3DBLEND_SRCALPHA data.add(i) 1 } 3 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_ADD i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.alphaarg1 = D3DTA_TEXTURE i.alphaarg2 = D3DTA_CURRENT i.blend_options_enabled = 1 i.srcblend = D3DBLEND_ONE i.dstblend = D3DBLEND_ONE data.add(i) 1 } 4 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_BLENDTEXTUREALPHA i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.alphaarg1 = D3DTA_TEXTURE i.alphaarg2 = D3DTA_CURRENT i.blend_options_enabled = 1 i.srcblend = D3DBLEND_SRCALPHA i.dstblend = D3DBLEND_INVSRCALPHA data.add(i) 1 } 5 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_ADD i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.blend_options_enabled = 1 i.srcblend = D3DBLEND_ONE i.dstblend = D3DBLEND_ONE data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_MODULATE2X i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.blend_options_enabled = 1 i.srcblend = D3DBLEND_DESTCOLOR i.dstblend = D3DBLEND_SRCCOLOR data.add(i) 1 } 6 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_BUMPENVMAP i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.blend_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_ADD i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.blend_options_enabled = 0 data.add(i) 1 } 7 -> { var i = TextureStageStateInfo() i.blend_options_enabled = 0 i.color_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_BUMPENVMAPLUMINANCE i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.blend_options_enabled = 0 data.add(i) i = TextureStageStateInfo() i.color_options_enabled = 1 i.colorop = D3DTOP_ADD i.colorarg1 = D3DTA_TEXTURE i.colorarg2 = D3DTA_CURRENT i.alphaop = D3DTOP_DISABLE i.blend_options_enabled = 0 data.add(i) 1 } else -> 0 } } } class TextureStageStateInfo { var color_options_enabled = 0 var colorop: DWORD = 0u var colorarg1: DWORD = 0u var colorarg2: DWORD = 0u var alphaop: DWORD = 0u var alphaarg1: DWORD = 0u var alphaarg2: DWORD = 0u var blend_options_enabled = 0 var srcblend: DWORD = 0u var dstblend: DWORD = 0u }
0
Kotlin
0
0
3c4ec99498badc65a728cafc20cb897a2685f6f5
9,385
ei_reverse_consp
MIT License
Android/App_Mix/App/src/main/java/com/zktony/android/ui/components/TopAppBar.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.components import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Reply import androidx.compose.material3.ElevatedButton import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.zktony.android.R import com.zktony.android.data.entities.Calibration import com.zktony.android.data.entities.Program import com.zktony.android.data.entities.internal.Point import com.zktony.android.ui.CalibrationIntent import com.zktony.android.ui.ProgramIntent import com.zktony.android.ui.SettingIntent import com.zktony.android.ui.navigation.TOP_LEVEL_DESTINATIONS import com.zktony.android.ui.utils.LocalNavigationActions import com.zktony.android.ui.utils.PageType import com.zktony.android.utils.extra.dateFormat import kotlinx.coroutines.launch /** * @author 刘贺贺 * @date 2023/8/23 9:03 */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeAppBar( page: Int, navigation: () -> Unit ) { val navigationActions = LocalNavigationActions.current TopAppBar( title = { Image( modifier = Modifier.height(48.dp), painter = painterResource(id = R.mipmap.logo), contentDescription = null ) }, actions = { Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 4.dp) .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = CircleShape ) .padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { AnimatedVisibility(visible = page != PageType.HOME) { ElevatedButton(onClick = navigation) { Icon( imageVector = Icons.Default.Reply, contentDescription = null ) } } TOP_LEVEL_DESTINATIONS.forEach { destination -> ElevatedButton( onClick = { navigationActions.navigateTo(destination) }, ) { Icon( imageVector = destination.icon, contentDescription = stringResource(id = destination.iconTextId) ) } } } } ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsAppBar( page: Int, dispatch: (SettingIntent) -> Unit, navigation: () -> Unit ) { val scope = rememberCoroutineScope() TopAppBar( title = { Text( modifier = Modifier .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.small, ) .padding(horizontal = 32.dp, vertical = 4.dp), text = stringResource(id = R.string.setting), style = MaterialTheme.typography.headlineSmall ) }, actions = { Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 4.dp) .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = CircleShape ) .padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { AnimatedVisibility(visible = page == PageType.MOTOR_LIST) { ElevatedButton(onClick = { scope.launch { dispatch(SettingIntent.Insert) } }) { Icon( imageVector = Icons.Default.Add, contentDescription = null ) } } ElevatedButton(onClick = navigation) { Icon( imageVector = Icons.Default.Reply, contentDescription = null ) } } } ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ProgramAppBar( entities: List<Program>, selected: Long, page: Int, dispatch: (ProgramIntent) -> Unit, navigation: () -> Unit ) { val scope = rememberCoroutineScope() var dialog by rememberSaveable { mutableStateOf(false) } if (dialog) { InputDialog( onConfirm = { scope.launch { dialog = false dispatch(ProgramIntent.Insert(it)) } } ) { dialog = false } } TopAppBar( title = { if (page == PageType.PROGRAM_LIST) { Text( modifier = Modifier .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.small, ) .padding(horizontal = 32.dp, vertical = 4.dp), text = stringResource(id = R.string.program), style = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 24.sp ) ) } else { Column( modifier = Modifier .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.small, ) .padding(horizontal = 32.dp, vertical = 4.dp) ) { val program = entities.find { it.id == selected } ?: Program() Text( text = program.displayText, style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 20.sp, fontStyle = FontStyle.Italic, ) ) Text( text = program.createTime.dateFormat("yyyy/MM/dd"), style = TextStyle( fontFamily = FontFamily.Monospace, fontSize = 12.sp, ), color = Color.Gray, ) } } }, actions = { Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 4.dp) .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = CircleShape ) .padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { ElevatedButton(onClick = { scope.launch { if (page == PageType.PROGRAM_LIST) { dialog = true } else { val program = entities.find { it.id == selected } if (program != null) { val orificePlates = program.orificePlates.toMutableList() orificePlates.add(com.zktony.android.data.entities.internal.OrificePlate()) dispatch(ProgramIntent.Update(program.copy(orificePlates = orificePlates))) } } } }) { Icon( imageVector = Icons.Default.Add, contentDescription = null ) } ElevatedButton(onClick = navigation) { Icon( imageVector = Icons.Default.Reply, contentDescription = null ) } } }, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun CalibrationAppBar( entities: List<Calibration>, selected: Long, page: Int, dispatch: (CalibrationIntent) -> Unit, navigation: () -> Unit ) { val scope = rememberCoroutineScope() var dialog by remember { mutableStateOf(false) } if (dialog) { InputDialog( onConfirm = { dispatch(CalibrationIntent.Insert(it)) dialog = false }, onCancel = { dialog = false } ) } TopAppBar( title = { if (page == PageType.CALIBRATION_LIST) { Text( modifier = Modifier .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.small, ) .padding(horizontal = 32.dp, vertical = 4.dp), text = stringResource(id = R.string.calibration), style = MaterialTheme.typography.headlineSmall ) } else { Column( modifier = Modifier .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.small, ) .padding(horizontal = 32.dp, vertical = 4.dp) ) { val calibration = entities.find { it.id == selected } ?: Calibration( displayText = "None" ) Text( text = calibration.displayText, style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 20.sp, fontStyle = FontStyle.Italic, ) ) Text( text = calibration.createTime.dateFormat("yyyy/MM/dd"), style = TextStyle( fontFamily = FontFamily.Monospace, fontSize = 12.sp, ), color = Color.Gray, ) } } }, actions = { Row( modifier = Modifier .padding(horizontal = 16.dp, vertical = 4.dp) .background( color = MaterialTheme.colorScheme.surfaceVariant, shape = CircleShape ) .padding(horizontal = 4.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { ElevatedButton(onClick = { scope.launch { if (page == PageType.CALIBRATION_LIST) { dialog = true } else { val calibration = entities.find { it.id == selected } ?: Calibration( displayText = "None" ) val points = calibration.points.toMutableList() points.add(Point(0.0, 0.0)) dispatch(CalibrationIntent.Update(calibration.copy(points = points))) } } }) { Icon( imageVector = Icons.Default.Add, contentDescription = null ) } ElevatedButton(onClick = navigation) { Icon( imageVector = Icons.Default.Reply, contentDescription = null ) } } } ) }
0
Kotlin
0
1
bcf0671b9e4ad199e579764f29683c1c575369d2
13,741
ZkTony
Apache License 2.0
feature/search/src/main/kotlin/com/mbmc/template/feature/search/data/entity/Mapper.kt
mbmc
60,234,476
false
null
package com.mbmc.template.feature.search.data.entity import com.mbmc.template.feature.search.di.scope.SearchScope import com.mbmc.template.feature.search.domain.entity.RepoDomain import javax.inject.Inject @SearchScope class Mapper @Inject constructor() { fun dataToDomain(repoData: RepoData): RepoDomain = RepoDomain(repoData.name) }
0
Kotlin
0
3
bfab18b2e28e3383b54d8c6dcd2ac76c3e4c5937
342
Template
Apache License 2.0
pickleperfect-game-example/pickleperfect-game-jre8/src/main/kotlin/net/mostlyoriginal/game/DesktopLauncher.kt
DaanVanYperen
93,187,911
false
null
package net.mostlyoriginal.game import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.utils.viewport.Viewport import net.mostlyoriginal.pickleperfect.Component import net.mostlyoriginal.pickleperfect.System import net.mostlyoriginal.pickleperfect.common.Bits import net.mostlyoriginal.pickleperfect.common.EntityPattern import net.mostlyoriginal.pickleperfect.internal.SubscriptionListener import net.mostlyoriginal.pickleperfect.internal.WorldFacade import net.mostlyoriginal.pickleperfect.jam.api.Application import net.mostlyoriginal.pickleperfect.jam.api.LibGdxApplication import net.mostlyoriginal.pickleperfect.service.ComponentStore import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.OrthographicCamera /** * @author Daan van Yperen */ fun main(args: Array<String>) { LibGdxApplication(TestGame( { c -> c.with(LibGdxSprite::class, ::LibGdxSprite) c.with(LibGdxRenderSystem()) } )).run() } class GdxActor(var region: TextureRegion) : Actor() { @Override override fun draw(batch: Batch, parentAlpha: Float) { batch.setColor(color.r, color.g, color.b, color.a * parentAlpha) batch.draw(region, x, y, originX, originY, width, height, scaleX, scaleY, rotation) } } class LibGdxSprite : Component { lateinit var actor: GdxActor } class LibGdxRenderSystem : System, SubscriptionListener { private lateinit var mLibGdxSprite: ComponentStore<LibGdxSprite> private lateinit var mPos: ComponentStore<TestGame.Pos> private lateinit var mSprite: ComponentStore<TestGame.Sprite> val pattern = EntityPattern() .all(TestGame.Pos::class, TestGame.Sprite::class) private lateinit var stage: Stage override fun added(entities: Bits) { entities.forTrue { val libGdxSprite = mLibGdxSprite.create(it) val region = TextureRegion(Texture(mSprite.get(it).name)) region.flip(false, true) libGdxSprite.actor = GdxActor(region) libGdxSprite.actor.width = region.regionWidth.toFloat() libGdxSprite.actor.height = region.regionHeight.toFloat() stage.addActor(libGdxSprite.actor) } } override fun removed(entities: Bits) { entities.forTrue { mLibGdxSprite.remove(it) } } override fun initialize(w: WorldFacade) { // setup mappers. mLibGdxSprite = w.getMapper(LibGdxSprite::class) mPos = w.getMapper(TestGame.Pos::class) mSprite = w.getMapper(TestGame.Sprite::class) // make sure we get informed of updates. w.getSubscription(pattern).register(this) stage = Stage() (stage.camera as OrthographicCamera).setToOrtho(true) } override fun process(w: WorldFacade) { Application.gfx.clearScreen(0f, 1f, 0f, 1f) // move all sprites around. w.getSubscription(pattern).forEach { val pos = mPos.get(it) val sprite = mLibGdxSprite.create(it) sprite.actor.x = pos.x sprite.actor.y = pos.y } stage.act(w.delta()) stage.draw() } }
0
Kotlin
0
2
b81cff8162943cf7dedab5276a63648446518f65
3,384
pickleperfect-ecs
MIT License
common-ui/src/main/java/com/yuriy/openradio/shared/view/dialog/RemoveStationDialogPresenter.kt
ChernyshovYuriy
679,720,363
false
{"Kotlin": 877885, "Java": 3552}
/* * Copyright 2022 The "Open Radio" Project. Author: <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yuriy.openradio.shared.view.dialog /** * // TODO : Move business logic from Remove Station Dialog here. */ interface RemoveStationDialogPresenter { fun removeRadioStation(mediaId: String?) }
13
Kotlin
0
8
7cfe3b7e55228f14df5f85b8d993db32df771d42
837
OpenRadio
Apache License 2.0
engine/src/main/kotlin/com/delphix/sdk/objects/AppDataContainerRuntime.kt
CloudSurgeon
212,463,880
false
null
/** * Copyright (c) 2019 by Delphix. All rights reserved. */ package com.delphix.sdk.objects /** * Runtime properties of an AppData container. */ open class AppDataContainerRuntime( override val preProvisioningStatus: PreProvisioningRuntime? = null, // The pre-provisioning runtime for the container. override val logSyncActive: Boolean? = null, // True if the LogSync is enabled and running for this container. override val type: String = "AppDataContainerRuntime" ) : DBContainerRuntime { override fun toMap(): Map<String, Any?> { return mapOf( "preProvisioningStatus" to preProvisioningStatus, "logSyncActive" to logSyncActive, "type" to type ) } }
0
null
0
1
819f7e9ea1bb0c675e0d04d61cf05302c488d74f
729
titan-server
Apache License 2.0
app/feature/favorite/src/main/java/com/anotn/flea/favorite/navigation/FavoriteNavigation.kt
Uhjinkim
850,430,659
false
{"Kotlin": 81861}
package com.anotn.flea.favorite.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavOptions import androidx.navigation.compose.composable import com.anotn.flea.favorite.FavoriteScreen import kotlinx.serialization.Serializable @Serializable data object FavoriteRoute fun NavController.navigateToFavorite(navOptions: NavOptions) = navigate(FavoriteRoute, navOptions) fun NavGraphBuilder.favoriteScreen() { composable<FavoriteRoute> { FavoriteScreen() } }
0
Kotlin
0
1
d321af1c24b973faa0345aede4d353ce42e791a8
545
Flea-Market
MIT License
kotlin-inject-compiler/core/src/main/kotlin/me/tatarka/inject/compiler/TypeCollector.kt
CrackerCat
373,143,152
true
{"Kotlin": 197847, "Java": 506}
package me.tatarka.inject.compiler import me.tatarka.inject.compiler.ContainerCreator.mapOf import me.tatarka.inject.compiler.ContainerCreator.setOf private val TYPE_INFO_CACHE = mutableMapOf<AstClass, TypeInfo>() class TypeCollector private constructor(private val provider: AstProvider, private val options: Options) : AstProvider by provider { companion object { operator fun invoke( provider: AstProvider, options: Options, astClass: AstClass, accessor: String? = null, ): TypeCollector = TypeCollector(provider, options).apply { val typeInfo = collectTypeInfo(astClass) collectTypes(astClass, accessor, typeInfo) scopeClass = typeInfo.scopeClass providerMethods = typeInfo.providerMethods } } // Map of types to inject and how to obtain them private val types = mutableMapOf<TypeKey, TypeCreator>() // Map of types that can be provided from abstract methods private val _providerMethods = mutableMapOf<TypeKey, TypeCreator.Method>() // Map of scoped components and the accessors to obtain them private val scopedAccessors = mutableMapOf<AstType, ScopedComponent>() var scopeClass: AstClass? = null private set var providerMethods: List<AstMethod> = emptyList() private set @Suppress("ComplexMethod") private fun collectTypes( astClass: AstClass, accessor: String? = null, typeInfo: TypeInfo, ) { if (typeInfo.elementScope != null) { scopedAccessors[typeInfo.elementScope] = ScopedComponent(astClass, accessor) } for (method in typeInfo.providesMethods) { val scopeType = method.scopeType(options) if (scopeType != null && scopeType != typeInfo.elementScope) { error("@Provides scope:$scopeType must match component scope: ${typeInfo.elementScope}", method) } val scopedComponent = if (scopeType != null) astClass else null if (method.hasAnnotation(INTO_MAP.packageName, INTO_MAP.simpleName)) { // Pair<A, B> -> Map<A, B> val type = method.returnTypeFor(astClass) val resolvedType = type.resolvedType() if (resolvedType.packageName == "kotlin" && resolvedType.simpleName == "Pair") { val typeArgs = resolvedType.arguments val mapType = TypeKey(declaredTypeOf(Map::class, typeArgs[0], typeArgs[1]), method.qualifier(options)) addContainerType(mapType, mapOf, method, accessor, scopedComponent) } else { error("@IntoMap must have return type of type Pair", method) } } else if (method.hasAnnotation(INTO_SET.packageName, INTO_SET.simpleName)) { // A -> Set<A> val setType = TypeKey(declaredTypeOf(Set::class, method.returnTypeFor(astClass))) addContainerType(setType, setOf, method, accessor, scopedComponent) } else { val returnType = method.returnTypeFor(astClass) val key = TypeKey(returnType, method.qualifier(options)) addMethod(key, method, accessor, scopedComponent) } } for (method in typeInfo.providerMethods) { val returnType = method.returnTypeFor(astClass) val key = TypeKey(returnType, method.qualifier(options)) if (typeInfo.isComponent) { addProviderMethod(key, method, accessor) } else { // If we aren't a component ourselves, allow obtaining types from providers as these may be contributed // from the eventual implementation addMethod(key, method, accessor, scopedComponent = null) } } val constructor = astClass.primaryConstructor if (constructor != null) { for (parameter in constructor.parameters) { if (parameter.isComponent()) { val elemAstClass = parameter.type.toAstClass() val elemTypeInfo = collectTypeInfo(elemAstClass) collectTypes( astClass = elemAstClass, accessor = if (accessor != null) "$accessor.${parameter.name}" else parameter.name, typeInfo = elemTypeInfo ) } } } } @Suppress("ComplexMethod", "LongMethod", "LoopWithTooManyJumpStatements") private fun collectTypeInfo(astClass: AstClass): TypeInfo { return TYPE_INFO_CACHE.getOrPut(astClass) { val isComponent = astClass.isComponent() val concreteMethods = mutableSetOf<AstMethod>() val providesMethods = mutableListOf<AstMethod>() val providerMethods = mutableListOf<AstMethod>() var scopeClass: AstClass? = null var elementScope: AstType? = null astClass.visitInheritanceChain { parentClass -> val parentScope = parentClass.scopeType(options) if (parentScope != null) { if (scopeClass == null) { scopeClass = parentClass elementScope = parentScope } else { messenger.error("Cannot apply scope: $parentScope", parentClass) messenger.error( "as scope: $elementScope is already applied", scopeClass ) } } for (method in parentClass.methods) { val abstract = method.isAbstract if (isComponent && !abstract) { concreteMethods.add(method) } if (method.isProvides()) { if (method.visibility == AstVisibility.PRIVATE) { error("@Provides method must not be private", method) continue } if (method.returnType.isUnit()) { error("@Provides method must return a value", method) continue } if (method.returnType.isPlatform()) { val name = method.returnType.simpleName error( """@Provides method must not return a platform type |This can happen when you call a platform method and leave off an explicit return type. |You can fix this be explicitly declaring the return type as $name or $name?""" .trimMargin(), method ) continue } if (isComponent && abstract) { val providesImpl = concreteMethods.find { it.overrides(method) } if (providesImpl == null) { error("@Provides method must have a concrete implementation", method) continue } concreteMethods.remove(providesImpl) providesMethods.add(providesImpl) } else { providesMethods.add(method) } } if (method.isProvider()) { providerMethods.add(method) } } } TypeInfo( isComponent = isComponent, providesMethods = providesMethods, providerMethods = providerMethods, scopeClass = scopeClass, elementScope = elementScope ) } } private fun addContainerType( key: TypeKey, creator: ContainerCreator, method: AstMethod, accessor: String?, scopedComponent: AstClass? ) { val current = types[key] if (current == null) { types[key] = TypeCreator.Container( creator = creator, source = method, args = mutableListOf(method(method, accessor, scopedComponent)) ) } else if (current is TypeCreator.Container && current.creator == creator) { current.args.add(method(method, accessor, scopedComponent)) } else { duplicate(key, newValue = method, oldValue = current.source) } } private fun addMethod(key: TypeKey, method: AstMethod, accessor: String?, scopedComponent: AstClass?) { val oldValue = types[key] if (oldValue == null) { types[key] = method(method, accessor, scopedComponent) } else { duplicate(key, newValue = method, oldValue = oldValue.source) } } private fun addProviderMethod(key: TypeKey, method: AstMethod, accessor: String?) { if (!_providerMethods.containsKey(key)) { _providerMethods[key] = method(method, accessor, scopedComponent = null) } } private fun method(method: AstMethod, accessor: String?, scopedComponent: AstClass?) = TypeCreator.Method( method = method, accessor = accessor, scopedComponent = scopedComponent ) private fun duplicate(key: TypeKey, newValue: AstElement, oldValue: AstElement) { error("Cannot provide: $key", newValue) error("as it is already provided", oldValue) } fun resolve(key: TypeKey): TypeCreator? { val result = types[key] if (result != null) { return result } val astClass = key.type.toAstClass() val injectCtor = astClass.findInjectConstructors(messenger, options) if (injectCtor != null) { val scope = astClass.scopeType(options) val scopedComponent = if (scope != null) scopedAccessors[scope] else null if (scope != null && scopedComponent == null) { error("Cannot find component with scope: @$scope to inject $astClass", astClass) return null } return TypeCreator.Constructor( injectCtor, accessor = scopedComponent?.accessor, scopedComponent = scopedComponent?.type ) } if (astClass.isInject() && astClass.isObject) { return TypeCreator.Object(astClass) } return null } } class TypeInfo( val isComponent: Boolean, val providesMethods: List<AstMethod>, val providerMethods: List<AstMethod>, val scopeClass: AstClass? = null, val elementScope: AstType? = null, ) sealed class TypeCreator(val source: AstElement) { class Object(val astClass: AstClass) : TypeCreator(astClass) class Constructor( val constructor: AstConstructor, val accessor: String? = null, val scopedComponent: AstClass? = null ) : TypeCreator(constructor) class Method( val method: AstMethod, val accessor: String? = null, val scopedComponent: AstClass? = null ) : TypeCreator(method) class Container( val creator: ContainerCreator, val args: MutableList<Method>, source: AstElement ) : TypeCreator(source) } @Suppress("EnumNaming") enum class ContainerCreator { mapOf, setOf } data class ScopedComponent( val type: AstClass, val accessor: String? )
0
null
0
1
4bc9ded8d272183f7eea360a3b50ef1d4488e837
11,846
kotlin-inject
Apache License 2.0
app/src/main/java/com/kotlin/weather/repository/model/weather/Wind.kt
ashk1246
625,470,990
false
null
package com.example.example import com.google.gson.annotations.SerializedName data class Wind( @SerializedName("speed") var speed: Double? = null, @SerializedName("deg") var deg: Int? = null, @SerializedName("gust") var gust: Double? = null )
0
Kotlin
0
0
b265d39331377a59071d09dde8d6d099e663ccaa
259
weatherApp
MIT License
pickpocket/src/main/java/com/evilthreads/pickpocket/FlowPickpocket.kt
evilthreads669966
302,106,521
false
null
/* Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.evilthreads.pickpocket import android.Manifest import android.accounts.AccountManager import android.content.ContentUris import android.content.Context import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.* import android.telephony.TelephonyManager import com.evilthreads.pickpocket.podos.* import com.evilthreads.pickpocket.podos.contactfields.ContactEvent import com.evilthreads.pickpocket.podos.contactfields.InstantMessenger import com.evilthreads.pickpocket.podos.contactfields.PhoneNumber import com.evilthreads.pickpocket.podos.contactfields.Relation import com.google.android.gms.location.LocationServices import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flow import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.yield import java.io.IOException import java.net.NetworkInterface /* ( ( ) ( ( ( )\ ))\ ) * ) ( /( )\ ) ( )\ ) )\ ) ( ( ( (()/(()/( ` ) /( )\()|()/(( )\ (()/( (()/( )\ )\ )\ /(_))(_)) ( )(_)|(_)\ /(_))\((((_)( /(_)) /(_)) ((_)((_)((_|_))(_)) (_(_()) _((_|_))((_))\ _ )(_))_ (_)) | __\ \ / /|_ _| | |_ _|| || | _ \ __(_)_\(_) \/ __| | _| \ V / | || |__ | | | __ | / _| / _ \ | |) \__ \ |___| \_/ |___|____| |_| |_||_|_|_\___/_/ \_\|___/|___/ ....................../´¯/) ....................,/¯../ .................../..../ ............./´¯/'...'/´¯¯`·¸ ........../'/.../..../......./¨¯\ ........('(...´...´.... ¯~/'...') .........\.................'...../ ..........''...\.......... _.·´ ............\..............( ..............\.............\... */ suspend fun Context.calendarFlow() = flow{ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if([email protected](Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) return@flow val projection = arrayOf(CalendarContract.Events._ID, CalendarContract.Events.ACCOUNT_NAME, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.ALL_DAY, CalendarContract.Events.DURATION, CalendarContract.Events.EVENT_TIMEZONE, CalendarContract.Events.EVENT_LOCATION, CalendarContract.Events.ORGANIZER) val sortOrder = "${CalendarContract.Events.DTSTART} DESC" val selection = "${CalendarContract.Events.ORGANIZER} NOT LIKE ?" //filters out holidays from google calendars val selectionArg = arrayOf<EMAIL>") [email protected](CalendarContract.Events.CONTENT_URI, projection, selection, selectionArg, sortOrder)?.use { cur -> if(cur.moveToFirst()) { val idIdx = cur.getColumnIndex(CalendarContract.Events._ID) val accountIdx = cur.getColumnIndex(CalendarContract.Events.ACCOUNT_NAME) val titleIdx = cur.getColumnIndex(CalendarContract.Events.TITLE) val descriptionIdx = cur.getColumnIndex(CalendarContract.Events.DESCRIPTION) val startDateIdx = cur.getColumnIndex(CalendarContract.Events.DTSTART) val endDateIdx = cur.getColumnIndex(CalendarContract.Events.DTEND) val allDayIdx = cur.getColumnIndex(CalendarContract.Events.ALL_DAY) val durationIdx = cur.getColumnIndex(CalendarContract.Events.DURATION) val timeZoneIdx = cur.getColumnIndex(CalendarContract.Events.EVENT_TIMEZONE) val locationIdx = cur.getColumnIndex(CalendarContract.Events.EVENT_LOCATION) val organizerIdx = cur.getColumnIndex(CalendarContract.Events.ORGANIZER) do { val id = cur.getInt(idIdx) val account = cur.getString(accountIdx) val title = cur.getString(titleIdx) val description = cur.getString(descriptionIdx) val startDate = cur.getLong(startDateIdx) val endDate = cur.getLong(endDateIdx) val allDay = cur.getInt(allDayIdx) val duration = cur.getString(durationIdx) val timeZone = cur.getString(timeZoneIdx) val location = cur.getString(locationIdx) val organizer = cur.getString(organizerIdx) val event = CalendarEvent(account, title, description, startDate, endDate, allDay, duration, timeZone, location, organizer) emit(event) yield() } while (cur.moveToNext()) } } return@flow } suspend fun Context.smsFlow() = flow{ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if([email protected](Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) return@flow if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ val projection = arrayOf(Telephony.Sms._ID, Telephony.Sms.THREAD_ID, Telephony.Sms.TYPE, Telephony.Sms.BODY, Telephony.Sms.ADDRESS, Telephony.Sms.DATE) [email protected](Telephony.Sms.CONTENT_URI, projection, null, null, Telephony.Sms.DEFAULT_SORT_ORDER)?.use { cur -> if(cur.moveToFirst()){ val idIdx = cur.getColumnIndex(Telephony.Sms._ID) val threadIdx = cur.getColumnIndex(Telephony.Sms.THREAD_ID) val typeIdx = cur.getColumnIndex(Telephony.Sms.TYPE) val bodyIdx = cur.getColumnIndex(Telephony.Sms.BODY) val addressIdx = cur.getColumnIndex(Telephony.Sms.ADDRESS) val dateIdx = cur.getColumnIndex(Telephony.Sms.DATE) do { val id = cur.getInt(idIdx) val thread = cur.getInt(threadIdx) val type = cur.getInt(typeIdx) val body = cur.getString(bodyIdx) val address = cur.getString(addressIdx) val date = cur.getLong(dateIdx) val message = Sms(thread, address, body, date, type) emit(message) yield() }while (cur.moveToNext()) } } }else{ val projection = arrayOf("_id", "thread_id", "type", "body", "address", "date") [email protected](Uri.parse("content://sms"), projection, null, null, "date DESC")?.use { cur -> if(cur.moveToFirst()){ val idIdx = cur.getColumnIndex("_id") val threadIdx = cur.getColumnIndex("thread_id") val typeIdx = cur.getColumnIndex("type") val bodyIdx = cur.getColumnIndex("body") val addressIdx = cur.getColumnIndex("address") val dateIdx = cur.getColumnIndex("date") do { val id = cur.getInt(idIdx) val thread = cur.getInt(threadIdx) val type = cur.getInt(typeIdx) val body = cur.getString(bodyIdx) val address = cur.getString(addressIdx) val date = cur.getLong(dateIdx) val message = Sms(thread, address, body, date, type) emit(message) yield() }while (cur.moveToNext()) } } } return@flow } suspend fun Context.callLogFlow() = flow{ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if ([email protected](Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) return@flow val projection = arrayOf(CallLog.Calls._ID, CallLog.Calls.TYPE, CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.DURATION) [email protected](CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls.DEFAULT_SORT_ORDER)?.use { cur -> if (cur.moveToFirst()) { val idIdx = cur.getColumnIndex(CallLog.Calls._ID) val typeIdx = cur.getColumnIndex(CallLog.Calls.TYPE) val numberIdx = cur.getColumnIndex(CallLog.Calls.NUMBER) val dateIdx = cur.getColumnIndex(CallLog.Calls.DATE) val durationIdx = cur.getColumnIndex(CallLog.Calls.DURATION) do { val id = cur.getInt(idIdx) val type = cur.getString(typeIdx) val number = cur.getString(numberIdx) val date = cur.getString(dateIdx) val duration = cur.getString(durationIdx) val call = CallLogEntry(type, number, date, duration) emit(call) yield() } while (cur.moveToNext()) } } return@flow } suspend fun Context.contactsFlow() = flow{ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if ([email protected](Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) return@flow //val projection = arrayOf(ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.HAS_PHONE_NUMBER) val projection = arrayOf(ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME) [email protected](ContactsContract.Contacts.CONTENT_URI, projection, null, null, ContactsContract.Contacts.SORT_KEY_PRIMARY)?.use { cur -> if (cur.moveToFirst()) { val idIdx = cur.getColumnIndex(ContactsContract.Contacts._ID) val nameIdx = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) do { val id = cur.getInt(idIdx) val name = cur.getString(nameIdx) val dataProjection = arrayOf(ContactsContract.Data._ID, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.Data.MIMETYPE, ContactsContract.Data.STATUS, ContactsContract.CommonDataKinds.Im.DATA, ContactsContract.CommonDataKinds.Im.TYPE, ContactsContract.CommonDataKinds.Im.PROTOCOL, ContactsContract.CommonDataKinds.Im.LABEL, ContactsContract.CommonDataKinds.Organization.COMPANY, ContactsContract.CommonDataKinds.Website.URL, ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Photo.PHOTO, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS, ContactsContract.CommonDataKinds.Relation.NAME, ContactsContract.CommonDataKinds.Relation.TYPE, ContactsContract.CommonDataKinds.Note.NOTE, ContactsContract.StatusUpdates.PRESENCE, ContactsContract.StatusUpdates.STATUS, ContactsContract.StatusUpdates.STATUS_TIMESTAMP) val imList = mutableSetOf<InstantMessenger>() val notes = mutableSetOf<String>() val websites = mutableSetOf<String>() val companies = mutableSetOf<String>() val relations = mutableSetOf<Relation>() val events = mutableSetOf<ContactEvent>() val postalAddresses = mutableSetOf<String>() val sips = mutableSetOf<String>() val phoneNumbers = mutableSetOf<PhoneNumber>() val emails = mutableSetOf<String>() var nickname: String? = null var photo: ByteArray? = null [email protected](ContactsContract.Data.CONTENT_URI, dataProjection, ContactsContract.Data.CONTACT_ID + "=?", arrayOf("$id"), null)?.use { curs -> if (curs.moveToFirst()) { val contactIdIdx = curs.getColumnIndex(ContactsContract.Data._ID) val mimeIdx = curs.getColumnIndex(ContactsContract.Data.MIMETYPE) val companyIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY) val urlIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL) val relationNameIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Relation.NAME) val relationTypeIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Relation.TYPE) val noteIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE) val imDataIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA) val imTypeIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE) val imLabelIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Im.LABEL) val imProtocolIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL) val eventStartDateIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE) val eventTypeIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE) val eventLabelIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Event.LABEL) val formAddrIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS) val postalTypeIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE) val postalLabelIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.LABEL) val streetIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET) val poboxIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX) val neighborhoodIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD) val cityIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY) val region = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION) val postcodeIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE) val country = curs.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY) val nicknameIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME) val sipAddressIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS) val numberIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) val numberTypeIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE) val photoIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO) val emailAddrIdx = curs.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS) val presenceIdx = curs.getColumnIndex(ContactsContract.StatusUpdates.PRESENCE) val statusIdx = curs.getColumnIndex(ContactsContract.StatusUpdates.STATUS) val statusTimeStampIdx = curs.getColumnIndex(ContactsContract.StatusUpdates.STATUS_TIMESTAMP) do { val contactId = curs.getInt(contactIdIdx) when (curs.getString(mimeIdx)) { ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE -> curs.getString(companyIdx)?.let { companies.add(it) } ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE -> curs.getString(urlIdx)?.let { websites.add(it) } ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE -> { val relationName = curs.getString(relationNameIdx) val relationType = curs.getString(relationTypeIdx) relations.add(Relation(relationName, relationType)) } ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE -> curs.getString(noteIdx)?.let { notes.add(it) } ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE -> { val imData = curs.getString(imDataIdx) val imType = curs.getInt(imTypeIdx) val imLabel = curs.getString(imLabelIdx) val imProtocol = curs.getInt(imProtocolIdx) var protoName: String? = null when (imProtocol) { -1 -> protoName = "custom" 0 -> protoName = "aim" 1 -> protoName = "msn" 2 -> protoName = "yahoo" 3 -> protoName = "skype" 4 -> protoName = "QQ" 5 -> protoName = "Google Talk" 6 -> protoName = "ICQ" 7 -> protoName = "jabber" 8 -> protoName = "netmeeting" else -> protoName = "unknown" } val presence = curs.getInt(presenceIdx) val status = curs.getString(statusIdx) val timeStamp = curs.getLong(statusTimeStampIdx) imList.add(InstantMessenger(imData, imType, imLabel, imProtocol, protoName, presence, status, timeStamp)) } ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE -> { val startDate = curs.getString(eventStartDateIdx) val type = curs.getInt(eventTypeIdx) val label = curs.getString(eventLabelIdx) events.add(ContactEvent(startDate, type, label)) } ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE -> { //todo try { val formAddr = curs.getString(formAddrIdx) /* val type = curs.getInt(postalTypeIdx) val label = curs.getString(postalLabelIdx) val street = curs.getString(streetIdx) //val pobox = curs.getString(poboxIdx) //val neighborhood = curs.getString(neighborhoodIdx) val city = curs.getString(cityIdx) val postcode = curs.getString(postcodeIdx) val postalAddress = PostalAddress(formAddr, type, label, street, null, null, city, null, postcode, null)*/ postalAddresses.add(formAddr) } catch (e: IllegalStateException) { e.printStackTrace() } } ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE -> curs.getString(nicknameIdx)?.let { name -> nickname = name } ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE -> curs.getString(sipAddressIdx)?.let { sip -> sips.add(sip) } ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE -> { val number = curs.getString(numberIdx) val type = curs.getInt(numberTypeIdx) phoneNumbers.add(PhoneNumber(number, type)) } ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE -> curs.getBlob(photoIdx)?.let { blob -> photo = blob } ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE -> curs.getString(emailAddrIdx)?.let { email -> emails.add(email) } } yield() } while (curs.moveToNext()) } } var address: String? = null if (postalAddresses.isNotEmpty()) address = postalAddresses.first() val contact = Contact(name, emails, phoneNumbers, photo, companies, websites, relations, notes, imList, events, address, sips, nickname) emit(contact) yield() } while (cur.moveToNext()) } } return@flow } /* suspend fun getAllStatusUpdates(ctx: Context): MutableList<String> { val statuses = mutableListOf<String>() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if (ctx.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) return statuses val projection = arrayOf(ContactsContract.StatusUpdates.STATUS, ContactsContract.StatusUpdates.STATUS_TIMESTAMP, ContactsContract.StatusUpdates.PRESENCE) ctx.contentResolver.query(ContactsContract.StatusUpdates.CONTENT_URI, null, null, null, null)?.use { cur -> if(cur.moveToFirst()){ val statusIdx = cur.getColumnIndex(ContactsContract.StatusUpdates.STATUS) val timeStampIdx = cur.getColumnIndex(ContactsContract.StatusUpdates.STATUS_TIMESTAMP) val presenceIdx = cur.getColumnIndex(ContactsContract.StatusUpdates.PRESENCE) do { val status = cur.getString(statusIdx) status?.let { statuses.add(it)} val timeStamp = cur.getLong(timeStampIdx) val presence = cur.getInt(presenceIdx) }while (cur.moveToNext()) } } return statuses } */ @Suppress("IMPLICIT_CAST_TO_ANY") suspend fun Context.mmsFlow() = flow{ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if ([email protected](Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) return@flow if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { val projection = arrayOf(Telephony.Mms._ID, Telephony.Mms.DATE, Telephony.Mms.READ, Telephony.Mms.THREAD_ID) [email protected](Telephony.Mms.CONTENT_URI, projection, null, null, Telephony.Mms.DEFAULT_SORT_ORDER)?.use { cur -> if (cur.moveToFirst()) { val idIdx = cur.getColumnIndex(Telephony.Mms._ID) val dateIdx = cur.getColumnIndex(Telephony.Mms.DATE) val hasReadIdx = cur.getColumnIndex(Telephony.Mms.READ) val threadIdx = cur.getColumnIndex(Telephony.Mms.THREAD_ID) do { val id = cur.getInt(idIdx) val date = cur.getLong(dateIdx) val hasRead = cur.getInt(hasReadIdx) val thread = cur.getInt(threadIdx) val partProjection = arrayOf(Telephony.Mms.Part._ID, Telephony.Mms.Part.CONTENT_TYPE, Telephony.Mms.Part._DATA, Telephony.Mms.Part.TEXT) //val images = mutableListOf<ByteArray>() val images = arrayOfNulls<ByteArray?>(5) val imageExts = arrayOfNulls<String?>(5) val fileNames = arrayOfNulls<String?>(5) var count = 0 val texts = mutableSetOf<String>() contentResolver.query(Uri.parse("content://mms/part/"), null, "mId=$id", null, null)?.use { curs -> if (curs.moveToFirst()) { val partIdIdx = curs.getColumnIndex(Telephony.Mms.Part._ID) val typeIdx = curs.getColumnIndex(Telephony.Mms.Part.CONTENT_TYPE) val dataIdx = curs.getColumnIndex(Telephony.Mms.Part._DATA) val textIdx = curs.getColumnIndex(Telephony.Mms.Part.TEXT) val nameIdx = curs.getColumnIndex(Telephony.Mms.Part.NAME) do { curs.getLong(partIdIdx).let { partId -> curs.getString(typeIdx).let { type -> when (type) { "text/plain" -> { if (curs.getString(dataIdx) != null) getMmsText( partId)?.let { txt -> texts.add(txt) } else curs.getString(textIdx)?.let { txt -> texts.add(txt) } } "image/jpeg" -> getMmsImage(partId)?.let { jpeg -> images[count] = jpeg imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/jpg" -> getMmsImage(partId)?.let { jpg -> images[count] = jpg imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/png" -> getMmsImage(partId)?.let { png -> images[count] = png imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/gif" -> getMmsImage(partId)?.let { gif -> images[count] = gif imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/bmp" -> getMmsImage(partId)?.let { bmp -> images[count] = bmp imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } else -> null } } } yield() } while (curs.moveToNext()) } } val msg = Mms(thread, date, hasRead, texts, images[0], images[1], images[2], images[3], images[4], imageExts[0], imageExts[1], imageExts[2], imageExts[3], imageExts[4], fileNames[0], fileNames[1], fileNames[2], fileNames[3], fileNames[4]) emit(msg) yield() } while (cur.moveToNext()) } } return@flow } else{ val projection = arrayOf("_id", "date", "read", "thread_id") contentResolver.query(Uri.parse("content://mms"), projection, null, null, null)?.use { cur -> if (cur.moveToFirst()) { val idIdx = cur.getColumnIndex("_id") val dateIdx = cur.getColumnIndex("date") val hasReadIdx = cur.getColumnIndex("read") val threadIdx = cur.getColumnIndex("thread_id") do { val id = cur.getInt(idIdx) val date = cur.getLong(dateIdx) val hasRead = cur.getInt(hasReadIdx) val thread = cur.getInt(threadIdx) val partProjection = arrayOf("_id", "ct", "_data", "texts") val images = arrayOfNulls<ByteArray?>(5) val imageExts = arrayOfNulls<String?>(5) val fileNames = arrayOfNulls<String?>(5) var count = 0 val texts = mutableSetOf<String>() contentResolver.query(Uri.parse("content://mms/part/"), null, "mId=$id", null, null)?.use { curs -> if (curs.moveToFirst()) { val partIdIdx = curs.getColumnIndex("_id") val typeIdx = curs.getColumnIndex("ct") val dataIdx = curs.getColumnIndex("_data") val textIdx = curs.getColumnIndex("texts") val nameIdx = curs.getColumnIndex("name") do { curs.getLong(partIdIdx).let { partId -> curs.getString(typeIdx)?.let { type -> when (type) { "text/plain" -> { if (curs.getString(dataIdx) != null) getMmsText(partId)?.let { txt -> texts.add(txt) } else curs.getString(textIdx)?.let { txt -> texts.add(txt) } } "image/jpeg" -> getMmsImage(partId)?.let { jpeg -> images[count] = jpeg imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/jpg" -> getMmsImage(partId)?.let { jpg -> images[count] = jpg imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/png" -> getMmsImage(partId)?.let { png -> images[count] = png imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/gif" -> getMmsImage(partId)?.let { gif -> images[count] = gif imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } "image/bmp" -> getMmsImage(partId)?.let { bmp -> images[count] = bmp imageExts[count] = type fileNames[count] = curs.getString(nameIdx) count++ } else -> null } } } yield() } while (curs.moveToNext()) } } val msg = Mms(thread, date, hasRead, texts, images[0], images[1], images[2], images[3], images[4], imageExts[0], imageExts[1], imageExts[2], imageExts[3], imageExts[4], fileNames[0], fileNames[1], fileNames[2], fileNames[3], fileNames[4]) emit(msg) yield() } while (cur.moveToNext()) } } } return@flow } internal fun Context.getMmsImage(partId: Long): ByteArray? { var image: ByteArray? = null if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if(this.checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) return image ContentUris.withAppendedId(Uri.parse("content://mms/part/"),partId).let { uri -> this.contentResolver.openInputStream(uri)?.use { inputStream -> /*image = BitmapFactory.decodeStream(this)*/ image = inputStream.readBytes() } } return image } internal fun Context.getMmsText(partId: Long): String? { return StringBuilder().apply { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if([email protected](Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) return@apply ContentUris.withAppendedId(Uri.parse("content://mms/part/"),partId).let { uri -> [email protected](uri)?.use { inputStream -> inputStream.reader().use { reader -> reader.useLines { lines -> lines.forEach { line -> appendln(line) } } } } } }.toString() } suspend fun Context.filesFlow(driveVolume: String = "external") = flow{ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if([email protected](Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) return@flow lateinit var projection: Array<String> if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) projection = arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATE_ADDED, MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.MIME_TYPE, MediaStore.Files.FileColumns.TITLE,MediaStore.Files.FileColumns.MEDIA_TYPE, MediaStore.Files.FileColumns.WIDTH, MediaStore.Files.FileColumns.HEIGHT, MediaStore.Files.FileColumns.DURATION, MediaStore.Files.FileColumns.VOLUME_NAME, MediaStore.Files.FileColumns.RELATIVE_PATH) else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) projection = arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATE_ADDED, MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.MIME_TYPE, MediaStore.Files.FileColumns.TITLE,MediaStore.Files.FileColumns.MEDIA_TYPE, MediaStore.Files.FileColumns.WIDTH, MediaStore.Files.FileColumns.HEIGHT) else projection = arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATE_ADDED, MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.MIME_TYPE, MediaStore.Files.FileColumns.TITLE,MediaStore.Files.FileColumns.MEDIA_TYPE) var selectionArgs: Array<String>? = null var selection: String? = null //filters out system ringtones val sortOrder = "${MediaStore.Files.FileColumns.DATE_ADDED} DESC" //val uri = MediaStore.Files.getContentUri(driveVolume) var uri = MediaStore.Files.getContentUri("internal") repeat(2){num -> if(num == 0){ selection = "${MediaStore.Files.FileColumns.MIME_TYPE} != ?" selectionArgs = arrayOf("application/ogg") } if(num == 1){ uri = MediaStore.Files.getContentUri("external") selection = null selectionArgs = null } [email protected](uri, projection, selection , selectionArgs , sortOrder)?.use { cur -> if(cur.moveToFirst()){ val idIdx = cur.getColumnIndex(MediaStore.Files.FileColumns._ID) val dateAddedIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.DATE_ADDED) val dateModifiedIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.DATE_MODIFIED) val sizeIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.SIZE) val nameIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME) val titleIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.TITLE) val mediaTypeIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE) val mimeTypeIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE) var durationIdx = -1 var relativePathIdx = -1 var volumeIdx = -1 var widthIdx: Int = -1 var heightIdx: Int = -1 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ durationIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.DURATION) relativePathIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.RELATIVE_PATH) volumeIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.VOLUME_NAME) widthIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.WIDTH) heightIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.HEIGHT) }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){ widthIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.WIDTH) heightIdx = cur.getColumnIndex(MediaStore.Files.FileColumns.HEIGHT) } do{ val id = cur.getLong(idIdx) val dateAdded = cur.getLong(dateAddedIdx) val dateModified = cur.getLong(dateModifiedIdx) val name = cur.getString(nameIdx) val title = cur.getString(titleIdx) val mediaType = cur.getString(mediaTypeIdx) val mimeType = cur.getString(mimeTypeIdx) val size = cur.getInt(sizeIdx) var relativePath: String? = null var duration: Long? = null var volume: String? = null var width: String? = null var height: String? = null if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ relativePath = cur.getString(relativePathIdx) duration = cur.getLong(durationIdx) volume = cur.getString(volumeIdx) width = cur.getString(widthIdx) height = cur.getString(heightIdx) } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){ width = cur.getString(widthIdx) height = cur.getString(heightIdx) } try{ mediaType?.takeUnless { it.equals("0") }?.let { contentResolver.openInputStream(ContentUris.withAppendedId(uri, id))?.use { stream -> emit(stream.readBytes().run { DocumentsFile(this, relativePath, volume, dateAdded, dateModified, name, duration, size, height, width, title, mediaType, mimeType) }) } } }catch (e: IOException){ e.printStackTrace() } yield() }while (cur.moveToNext()) } } } return@flow } suspend fun Context.settingsFlow() = flow{ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) return@flow [email protected](Settings.Global.CONTENT_URI, null, null, null, "${Settings.Global.NAME} DESC")?.use { cur -> if (cur.moveToFirst()) { val idIdx = cur.getColumnIndex(Settings.Global._ID) val nameIdx = cur.getColumnIndex(Settings.Global.NAME) val valueIdx = cur.getColumnIndex(Settings.Global.VALUE) do { val id = cur.getString(idIdx) val name = cur.getString(nameIdx) val value = cur.getString(valueIdx) emit(Setting(id, name, value)) yield() } while (cur.moveToNext()) } } return@flow } suspend fun Context.bookmarksFlow() = flow{ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) return@flow val projection = arrayOf("_id", "title", "url", "bookmark", "visits", "date") [email protected](Uri.parse("content://browser/bookmarks"), projection, null, null, "date DESC")?.use { cur -> if(cur.moveToFirst()){ val titleIdx = cur.getColumnIndex("title") val urlIdx = cur.getColumnIndex("url") val bookmarkIdx = cur.getColumnIndex("bookmark") val visitsIdx = cur.getColumnIndex("visits") val dateIdx = cur.getColumnIndex("date") val idIdx = cur.getColumnIndex("_id") do { val title = cur.getString(titleIdx) val url = cur.getString(urlIdx) val bookmark = cur.getString(bookmarkIdx) val visits = cur.getString(visitsIdx) val date = cur.getString(dateIdx) val id = cur.getInt(idIdx) val browserHistory = Bookmark(title, url, bookmark,visits, date) emit(browserHistory) yield() }while (cur.moveToNext()) } } return@flow } suspend fun Context.dictionaryFlow() = flow{ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) return@flow [email protected](UserDictionary.Words.CONTENT_URI, arrayOf(UserDictionary.Words._ID, UserDictionary.Words.WORD), null, null, UserDictionary.Words.DEFAULT_SORT_ORDER)?.use { cur -> if(cur.moveToFirst()){ val idIdx = cur.getColumnIndex(UserDictionary.Words._ID) val wordIdx = cur.getColumnIndex(UserDictionary.Words.WORD) do{ val id = cur.getInt(idIdx) val word = cur.getString(wordIdx) emit(DictionaryWord(word)) yield() }while (cur.moveToNext()) } } return@flow } suspend fun Context.accountsFlow() = flow{ AccountManager.get([email protected]).accounts.forEach{ account -> emit(UserAccount(account.name, account.type)) } return@flow } internal suspend fun Context.getDeviceNumber(): String?{ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) if(this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) return null return (this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).getLine1Number() } suspend fun Context.deviceFlow() = flow{ var serial: String? = Build.SERIAL var locale: String? = null [email protected] { ctx -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) locale = ctx.resources.configuration.locales.toLanguageTags() val countryCode = (ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).networkCountryIso /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) if (ctx.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) //i hadn't worked on this in a long time and for some reason it is now saying I am missing READ_PRIVELDGED_PHONE_STATE so I commented it out serial = Build.getSerial()*/ val ip = getIpV4() emit(Device(Build.ID, ctx.getDeviceNumber(), ip.first(), locale, countryCode, Build.MANUFACTURER, Build.MODEL, Build.PRODUCT, Build.VERSION.SDK_INT, Build.VERSION.CODENAME, serial, Build.getRadioVersion(), Build.BRAND, Build.BOARD)) } return@flow } internal suspend fun getIpV4():MutableSet<String> { return mutableSetOf<String>().apply { NetworkInterface.getNetworkInterfaces().toList().forEach { network -> network.inetAddresses.toList().filter { addresses -> !addresses.isLoopbackAddress }.filter { it.hostAddress.contains(".") }.forEach { add(it.hostAddress) } } } } suspend fun Context.softwareFlow() = flow{ [email protected](PackageManager.GET_META_DATA).forEach{ app -> emit(Software(app?.packageName ?: "", null)) } return@flow } suspend fun Context.locationFlow() = flow { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ if([email protected](Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) return@flow } withTimeoutOrNull(6000) { val location = async { LocationServices.getFusedLocationProviderClient(this@locationFlow).lastLocation.addOnSuccessListener { } }.await() while (!location.isSuccessful) delay(300) location.result?.let { loc -> emit(RecentLocation(loc.time, loc.latitude, loc.longitude, loc.altitude)) } } return@flow }
0
Kotlin
6
27
6e03d65863507e2a09e3479b6aa23d4ee53de45a
47,586
Pickpocket
Apache License 2.0
test/iii_properties/_20_Delegates_Examples.kt
grmaciel
44,112,142
true
{"XML": 13, "Ignore List": 1, "Text": 1, "Markdown": 1, "Kotlin": 109, "Java": 10}
package iii_properties import junit.framework.Assert import org.junit.Test as test import java.util.HashMap class _20_Delegates_Examples { test fun testCommodity() { val data = hashMapOf<String, Any?>("description" to "snowboard", "price" to 349, "isAvailable" to true) val p = Commodity(data) Assert.assertEquals("snowboard", p.description) Assert.assertEquals(349, p.price) Assert.assertEquals(true, p.isAvailable) data["price"] = 421 Assert.assertEquals("Commodity class should reflect the data in map", 421, p.price) p.isAvailable = false Assert.assertEquals("The data in map should reflect the commodity class", false, data["isAvailable"]) } }
1
Kotlin
1
1
bdfb637b99cb4787f05b05f6db604364b1cb3c0f
732
workshop-jb
MIT License
AlwaysOnKotlin/views/src/main/java/com/example/android/wearable/wear/alwayson/MainActivity.kt
android
192,007,253
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.wear.alwayson import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Color import android.os.Bundle import android.util.Log import androidx.annotation.VisibleForTesting import androidx.core.content.getSystemService import androidx.fragment.app.FragmentActivity import androidx.lifecycle.lifecycleScope import androidx.wear.ambient.AmbientModeSupport import com.example.android.wearable.wear.alwayson.databinding.ActivityMainBinding import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.time.Clock import java.time.Duration import java.time.Instant import java.time.LocalTime import java.time.format.DateTimeFormatter import java.util.Locale import kotlin.random.Random /** * IMPORTANT NOTE: Most apps shouldn't use always on ambient mode, as it drains battery life. Unless * required, it's much better to allow the system to take over after the user stops interacting * with your app. * * Demonstrates support for *Ambient Mode* by attaching ambient mode support to the activity, * and listening for ambient mode updates (onEnterAmbient, onUpdateAmbient, and onExitAmbient) via a * named AmbientCallback subclass. * * Also demonstrates how to update the display more frequently than every 60 seconds, which is * the default frequency, using an AlarmManager. The Alarm code is only necessary for the custom * refresh frequency; it can be ignored for basic ambient mode support where you can simply rely on * calls to onUpdateAmbient() by the system. * * There are two modes: *ambient* and *active*. To trigger future display updates, we * use coroutines for active mode and an Alarm for ambient mode. * * Why not use just one or the other? Coroutines are generally less battery intensive and can be * triggered every second. However, they can not wake up the processor (common in ambient mode). * * Alarms can wake up the processor (what we need for ambient move), but they are less efficient * compared to coroutines when it comes to quick update frequencies. * * Therefore, we use coroutines for active mode (can trigger every second and are better on the * battery), and we use an Alarm for ambient mode (only need to update once every 10 seconds and * they can wake up a sleeping processor). * * The activity waits 10 seconds between doing any processing (getting data, updating display * etc.) while in ambient mode to conserving battery life (processor allowed to sleep). If your app * can wait 60 seconds for display updates, you can disregard the Alarm code and simply use * onUpdateAmbient() to save even more battery life. * * As always, you will still want to apply the performance guidelines outlined in the Watch Faces * documentation to your app. * * Finally, in ambient mode, this activity follows the same best practices outlined in the Watch * Faces API documentation: keeping most pixels black, avoiding large blocks of white pixels, using * only black and white, disabling anti-aliasing, etc. */ class MainActivity : FragmentActivity(), AmbientModeSupport.AmbientCallbackProvider { private lateinit var binding: ActivityMainBinding /** * Ambient mode controller attached to this display. Used by Activity to see if it is in ambient * mode. */ private lateinit var ambientController: AmbientModeSupport.AmbientController /** * Since the coroutine-based update (used in active mode) can't wake up the processor when the * device is in ambient mode and undocked, we use an Alarm to cover ambient mode updates when we * need them more frequently than every minute. Remember, if getting updates once a minute in * ambient mode is enough, you can do away with the Alarm code and just rely on the * onUpdateAmbient() callback. */ private lateinit var ambientUpdateAlarmManager: AlarmManager private lateinit var ambientUpdatePendingIntent: PendingIntent private lateinit var ambientUpdateBroadcastReceiver: BroadcastReceiver private val dateFormat = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US) @Volatile private var drawCount = 0 /** * The [Job] associated with the updates performed while in active mode. */ private var activeUpdateJob: Job = Job().apply { complete() } public override fun onCreate(savedInstanceState: Bundle?) { Log.d(TAG, "onCreate()") super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) ambientController = AmbientModeSupport.attach(this) ambientUpdateAlarmManager = getSystemService()!! /* * Create a PendingIntent which we'll give to the AlarmManager to send ambient mode updates * on an interval which we've define. */ val ambientUpdateIntent = Intent(AMBIENT_UPDATE_ACTION) /* * Retrieves a PendingIntent that will perform a broadcast. You could also use getActivity() * to retrieve a PendingIntent that will start a new activity, but be aware that actually * triggers onNewIntent() which causes lifecycle changes (onPause() and onResume()) which * might trigger code to be re-executed more often than you want. * * If you do end up using getActivity(), also make sure you have set activity launchMode to * singleInstance in the manifest. * * Otherwise, it is easy for the AlarmManager launch Intent to open a new activity * every time the Alarm is triggered rather than reusing this Activity. */ ambientUpdatePendingIntent = PendingIntent.getBroadcast( this, 0, ambientUpdateIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) /* * An anonymous broadcast receiver which will receive ambient update requests and trigger * display refresh. */ ambientUpdateBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { refreshDisplayAndSetNextUpdate() } } } public override fun onResume() { Log.d(TAG, "onResume()") super.onResume() val filter = IntentFilter(AMBIENT_UPDATE_ACTION) registerReceiver(ambientUpdateBroadcastReceiver, filter) refreshDisplayAndSetNextUpdate() } public override fun onPause() { Log.d(TAG, "onPause()") super.onPause() unregisterReceiver(ambientUpdateBroadcastReceiver) activeUpdateJob.cancel() ambientUpdateAlarmManager.cancel(ambientUpdatePendingIntent) } /** * Loads data/updates screen (via method), but most importantly, sets up the next refresh * (active mode = coroutines and ambient mode = Alarm). */ private fun refreshDisplayAndSetNextUpdate() { loadDataAndUpdateScreen() val instant = Instant.now(clock) if (ambientController.isAmbient) { val triggerTime = instant.getNextInstantWithInterval(AMBIENT_INTERVAL) ambientUpdateAlarmManager.setExact( AlarmManager.RTC_WAKEUP, triggerTime.toEpochMilli(), ambientUpdatePendingIntent ) } else { val delay = instant.getDelayToNextInstantWithInterval(ACTIVE_INTERVAL) activeUpdateJob.cancel() activeUpdateJob = lifecycleScope.launch { withContext(activeDispatcher) { // Delay on the active dispatcher for testability delay(delay.toMillis()) } refreshDisplayAndSetNextUpdate() } } } /** * Returns the delay from this [Instant] to the next one that is aligned with the given * [interval]. */ private fun Instant.getDelayToNextInstantWithInterval(interval: Duration): Duration = Duration.ofMillis(interval.toMillis() - toEpochMilli() % interval.toMillis()) /** * Returns the next [Instant] that is aligned with the given [interval]. */ private fun Instant.getNextInstantWithInterval(interval: Duration): Instant = plus(getDelayToNextInstantWithInterval(interval)) /** * Updates display based on Ambient state. If you need to pull data, you should do it here. */ private fun loadDataAndUpdateScreen() { drawCount += 1 val currentInstant = Instant.now(clock) Log.d( TAG, "loadDataAndUpdateScreen(): " + "${currentInstant.toEpochMilli()} (${ambientController.isAmbient})" ) val currentTime = LocalTime.now(clock) binding.time.text = dateFormat.format(currentTime) binding.timeStamp.text = getString(R.string.timestamp_label, currentInstant.toEpochMilli()) binding.state.text = getString( if (ambientController.isAmbient) { R.string.mode_ambient_label } else { R.string.mode_active_label } ) binding.updateRate.text = getString( R.string.update_rate_label, if (ambientController.isAmbient) { AMBIENT_INTERVAL.seconds } else { ACTIVE_INTERVAL.seconds } ) binding.drawCount.text = getString(R.string.draw_count_label, drawCount) } override fun getAmbientCallback(): AmbientModeSupport.AmbientCallback = MyAmbientCallback() private inner class MyAmbientCallback : AmbientModeSupport.AmbientCallback() { /** * If the display is low-bit in ambient mode. i.e. it requires anti-aliased fonts. */ private var isLowBitAmbient = false /** * If the display requires burn-in protection in ambient mode, rendered pixels need to be * intermittently offset to avoid screen burn-in. */ private var doBurnInProtection = false /** * Prepares the UI for ambient mode. */ override fun onEnterAmbient(ambientDetails: Bundle) { super.onEnterAmbient(ambientDetails) isLowBitAmbient = ambientDetails.getBoolean(AmbientModeSupport.EXTRA_LOWBIT_AMBIENT, false) doBurnInProtection = ambientDetails.getBoolean(AmbientModeSupport.EXTRA_BURN_IN_PROTECTION, false) // Cancel any active updates activeUpdateJob.cancel() /* * Following best practices outlined in WatchFaces API (keeping most pixels black, * avoiding large blocks of white pixels, using only black and white, and disabling * anti-aliasing, etc.) */ binding.state.setTextColor(Color.WHITE) binding.updateRate.setTextColor(Color.WHITE) binding.drawCount.setTextColor(Color.WHITE) if (isLowBitAmbient) { binding.time.paint.isAntiAlias = false binding.timeStamp.paint.isAntiAlias = false binding.state.paint.isAntiAlias = false binding.updateRate.paint.isAntiAlias = false binding.drawCount.paint.isAntiAlias = false } refreshDisplayAndSetNextUpdate() } /** * Updates the display in ambient mode on the standard interval. Since we're using a custom * refresh cycle, this method does NOT update the data in the display. Rather, this method * simply updates the positioning of the data in the screen to avoid burn-in, if the display * requires it. */ override fun onUpdateAmbient() { super.onUpdateAmbient() /* * If the screen requires burn-in protection, views must be shifted around periodically * in ambient mode. To ensure that content isn't shifted off the screen, avoid placing * content within 10 pixels of the edge of the screen. * * Since we're potentially applying negative padding, we have ensured * that the containing view is sufficiently padded (see res/layout/activity_main.xml). * * Activities should also avoid solid white areas to prevent pixel burn-in. Both of * these requirements only apply in ambient mode, and only when this property is set * to true. */ if (doBurnInProtection) { binding.container.translationX = Random.nextInt(-BURN_IN_OFFSET_PX, BURN_IN_OFFSET_PX + 1).toFloat() binding.container.translationY = Random.nextInt(-BURN_IN_OFFSET_PX, BURN_IN_OFFSET_PX + 1).toFloat() } } /** * Restores the UI to active (non-ambient) mode. */ override fun onExitAmbient() { super.onExitAmbient() /* Clears out Alarms since they are only used in ambient mode. */ ambientUpdateAlarmManager.cancel(ambientUpdatePendingIntent) binding.state.setTextColor(Color.GREEN) binding.updateRate.setTextColor(Color.GREEN) binding.drawCount.setTextColor(Color.GREEN) if (isLowBitAmbient) { binding.time.paint.isAntiAlias = true binding.timeStamp.paint.isAntiAlias = true binding.state.paint.isAntiAlias = true binding.updateRate.paint.isAntiAlias = true binding.drawCount.paint.isAntiAlias = true } /* Reset any random offset applied for burn-in protection. */ if (doBurnInProtection) { binding.container.translationX = 0f binding.container.translationY = 0f } refreshDisplayAndSetNextUpdate() } } companion object { private const val TAG = "MainActivity" /** * Duration between updates while in active mode. */ private val ACTIVE_INTERVAL = Duration.ofSeconds(1) /** * Duration between updates while in ambient mode. */ private val AMBIENT_INTERVAL = Duration.ofSeconds(10) /** * Action for updating the display in ambient mode, per our custom refresh cycle. */ const val AMBIENT_UPDATE_ACTION = "com.example.android.wearable.wear.alwayson.action.AMBIENT_UPDATE" /** * Number of pixels to offset the content rendered in the display to prevent screen burn-in. */ private const val BURN_IN_OFFSET_PX = 10 } } /** * The [Clock] driving the time information. Overridable only for testing. */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var clock: Clock = Clock.systemDefaultZone() /** * The dispatcher used for delaying in active mode. Overridable only for testing. */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var activeDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate
28
null
523
891
75f23734cd594732cb6ff10b62478ceeac75d793
16,140
wear-os-samples
Apache License 2.0
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/actions/TogglePackageDetailsAction.kt
nymanjens
381,464,645
false
{"Text": 6282, "XML": 6311, "YAML": 418, "Ant Build System": 12, "Shell": 563, "Markdown": 564, "Ignore List": 95, "Git Attributes": 10, "EditorConfig": 233, "Batchfile": 27, "SVG": 2361, "Java": 74703, "C++": 34, "HTML": 2881, "Kotlin": 39755, "DTrace": 1, "Gradle": 447, "Java Properties": 205, "INI": 418, "JFlex": 31, "CSS": 56, "Groovy": 3454, "XSLT": 112, "JavaScript": 207, "JSON": 858, "desktop": 1, "Python": 12143, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 277, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 5, "C#": 37, "Smalltalk": 17, "Diff": 131, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "Objective-C": 22, "CoffeeScript": 3, "HTTP": 2, "JSON with Comments": 59, "GraphQL": 49, "OpenStep Property List": 46, "Tcl": 1, "fish": 1, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 86, "Vim Script": 7, "Vim Snippet": 3, "Vim Help File": 2, "Starlark": 2, "E-mail": 18, "Roff": 245, "Roff Manpage": 39, "Swift": 3, "Maven POM": 76, "C": 48, "TOML": 47, "Proguard": 2, "Checksums": 58, "Java Server Pages": 8, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 15, "VBScript": 1, "NSIS": 5, "PlantUML": 5, "Thrift": 3, "Cython": 14, "reStructuredText": 56, "Regular Expression": 3, "JSON5": 4}
package com.jetbrains.packagesearch.intellij.plugin.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.fus.FUSGroupIds import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger class TogglePackageDetailsAction( private val project: Project, private val selectedCallback: (Boolean) -> Unit ) : ToggleAction( PackageSearchBundle.message("packagesearch.actions.showDetails.text"), PackageSearchBundle.message("packagesearch.actions.showDetails.description"), AllIcons.Actions.PreviewDetails ) { override fun isSelected(e: AnActionEvent) = PackageSearchGeneralConfiguration.getInstance(project).packageDetailsVisible override fun setSelected(e: AnActionEvent, state: Boolean) { PackageSearchGeneralConfiguration.getInstance(project).packageDetailsVisible = state selectedCallback.invoke(state) PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.PackageDetails, state) } }
1
null
1
1
2b16830726679d2ba0c82a4d246af467819c826a
1,326
intellij-community
Apache License 2.0
idea/testData/quickfix/increaseVisibility/exposedSuperClassProtectedInAnother.kt
JakeWharton
99,388,807
true
null
// "Make 'Data' public" "true" // ACTION: Make 'First' private class Other { internal open class Data(val x: Int) } class Another { protected class First : Other.<caret>Data(42) }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
189
kotlin
Apache License 2.0
screensadaptermvp/src/main/java/com/e16din/screensadapter/mvp/helpers/Utils.kt
e16din
150,167,755
false
null
package com.e16din.screensadapter.mvp.helpers import android.app.Activity import android.content.Context import android.content.res.Resources import android.graphics.drawable.Drawable import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.e16din.screensadapter.mvp.binders.android.BaseAndroidScreenBinder fun BaseAndroidScreenBinder<*>.showToastMessage(message: CharSequence) = Toast.makeText(this.screensAdapter.getAndroidApp(), message, Toast.LENGTH_SHORT).show() fun BaseAndroidScreenBinder<*>.showToastMessageLong(message: CharSequence?) = Toast.makeText(this.screensAdapter.getAndroidApp(), message, Toast.LENGTH_LONG).show() fun Int.getDrawable(context: Context): Drawable? { return ContextCompat.getDrawable(context, this) } fun FragmentManager.replaceNow(containerId: Int, fragment: Fragment, tag: String) { this.beginTransaction().replace(containerId, fragment, tag) .addToBackStack(null) .commit() } fun FragmentManager.addNow(containerId: Int, fragment: Fragment, tag: String, name: String?) { this.beginTransaction().add(containerId, fragment, tag) .addToBackStack(name) .commit() } fun FragmentManager.removeNow(fragment: Fragment) { this.beginTransaction().remove(fragment) .commit() } fun FragmentManager.removeNow(fragmentTag: String) { val fragment = this.findFragmentByTag(fragmentTag) fragment?.let { this.beginTransaction().remove(fragment) .commit() } } fun View.hideKeyboard() { val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(windowToken, 0) } val Int.pxToDp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt() val Int.dpToPx: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt() inline fun <K, V> Map<out K, V>.foreach(action: (Map.Entry<K, V>) -> Unit) { with(this.iterator()) { forEach { action.invoke(it) } } }
0
Kotlin
0
0
f427ee19faf6929cd0e51ea6850d75fe8c8f5aee
2,270
ScreensAdapter
Apache License 2.0
ui/ui-core/src/commonMain/kotlin/androidx/ui/core/OnPositionedDispatcher.kt
Sathawale27
282,379,594
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.ui.core /** * Tracks the nodes being positioned and dispatches OnPositioned callbacks when we finished * the measure/layout pass. */ @OptIn(ExperimentalLayoutNodeApi::class) internal class OnPositionedDispatcher { private var topDepth = Int.MAX_VALUE private var topNode: LayoutNode? = null fun onNodePositioned(node: LayoutNode) { if (node.depth < topDepth) { topDepth = node.depth topNode = node } } fun dispatch() { topNode?.also { it.dispatchOnPositionedCallbacks() topNode = null topDepth = Int.MAX_VALUE } } }
1
null
1
1
549e3e3003cd308939ff31799cf1250e86d3e63e
1,273
androidx
Apache License 2.0
software-design/event-sourcing/src/main/kotlin/com/github/nothingelsematters/design/event_sourcing/turnstile/Application.kt
nothingelsematters
135,926,684
false
null
package com.github.nothingelsematters.design.event_sourcing.turnstile import com.github.nothingelsematters.design.event_sourcing.common.database.DatabaseConfiguration import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import @Configuration @Import(DatabaseConfiguration::class) open class ApplicationConfiguration { @Bean open fun turnstileService() = TurnstileServiceImpl() } @SpringBootApplication open class Application fun main(args: Array<String>) { runApplication<Application>(*args) }
1
null
3
5
d442a3d25b579b96c6abda13ed3f7e60d1747b53
730
university
Do What The F*ck You Want To Public License
app/src/main/java/net/blakelee/coinprofits/base/BaseLifecycleActivity.kt
blakelee
96,650,297
false
null
package net.blakelee.coinprofits.base import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.LifecycleRegistry import android.arch.lifecycle.LifecycleRegistryOwner import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity //This code written by <NAME> as part of Android-Architecture-Components @Suppress("LeakingThis") abstract class BaseLifecycleActivity<T : AndroidViewModel> : AppCompatActivity(), LifecycleRegistryOwner { abstract val viewModelClass: Class<T> protected lateinit var viewModel: T private val registry = LifecycleRegistry(this) override fun getLifecycle(): LifecycleRegistry = registry override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this).get(viewModelClass) } }
2
null
1
4
152bf37a11f0da2da7ff91d9493fb2334da5ba59
887
CoinProfits
MIT License
app/src/main/java/com/solarexsoft/mpandroidchartdemo/utils/FoodMeals.kt
flyfire
196,355,714
false
null
package com.solarexsoft.mpandroidchartdemo.utils /** * <pre> * Author: houruhou * CreatAt: 17:09/2019-07-11 * Desc: * </pre> */ enum class FoodMeals { BREAKFAST,LUNCH,HIGHTEA,DINNER,SUPPER; }
1
null
1
1
c67baf6f79809e9563789f425e7a72a61fb1ff61
212
MPAndroidChartDemo
MIT License
plugins/kotlin/idea/tests/testData/inspectionsLocal/unnecessaryOptInAnnotation/necessaryArraySet.kt
ingokegel
72,937,917
true
null
// PROBLEM: none // WITH_STDLIB // COMPILER_ARGUMENTS: -Xopt-in=kotlin.RequiresOptIn @RequiresOptIn annotation class Marker class Foo() { val bar = Array<Int>(5) { 0 } @Marker operator fun set(index: Int, value: Int) { bar[index] = value } } @OptIn(<caret>Marker::class) fun baz(foo: Foo) { foo[2] = 1 }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
336
intellij-community
Apache License 2.0
library/src/main/java/com/victor/kplayer/library/data/SubTitleListInfo.kt
Victor2018
154,598,071
false
null
package com.victor.kplayer.library.data /* * ----------------------------------------------------------------- * Copyright (C) 2018-2028, by longtv, All rights reserved. * ----------------------------------------------------------------- * File: SubTitleListInfo.java * Author: Victor * Date: 2018/10/25 14:38 * Description: * ----------------------------------------------------------------- */ class SubTitleListInfo { var id: Int = 0 var name: String? = null var lang_code: String? = null var lang_original: String? = null var lang_translated: String? = null var lang_default: Boolean = false }
1
Kotlin
1
1
0e7fa0c74616f666d2109a99ffea250c617ff6d9
632
KPlayer
Apache License 2.0
plugins/kotlin/idea/tests/testData/inspectionsLocal/usePropertyAccessSyntax/dotQualifiedExpressions/dontReplaceSetterForFunctionWithExpressionBody.kt
JetBrains
2,489,216
false
null
// PROBLEM: none fun setValue(x: Int) = J().<caret>setX(x)
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
59
intellij-community
Apache License 2.0
app/src/main/java/com/example/bubblelayout/api/RetrofitManager.kt
shenhaizhumin
277,843,652
false
null
package com.example.bubblelayout.api import android.util.Log import com.blankj.utilcode.util.SPUtils import com.example.bubblelayout.utils.UserInfoUtil import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import okhttp3.* import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.File import java.io.UnsupportedEncodingException import java.net.URLDecoder import java.util.concurrent.TimeUnit class RetrofitManager { private val tokenHeader = Interceptor { val request = it.request().newBuilder() .addHeader("Authorization", UserInfoUtil.getAccessToken()) .addHeader("client-type", "app") .build() return@Interceptor it.proceed(request) } companion object { private var instance: RetrofitManager? = null fun getInstance(): RetrofitManager { if (instance == null) { instance = RetrofitManager() instance!!.init() } return instance!! } } private lateinit var mOkHttpClient: OkHttpClient fun init() { val loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> try { Log.e("OKHttp-----", message+"") } catch (e: UnsupportedEncodingException) { e.printStackTrace() Log.e("OKHttp-----", message) } }) loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY // val cacheFile = File(context.cacheDir, "cache") // val cache = Cache(cacheFile, (1024 * 1024 * 100).toLong()) //100Mb // val cookieJar = // PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(context)) val builder = OkHttpClient.Builder() .readTimeout(20, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS) .addInterceptor(tokenHeader) // .cookieJar(JavaNetCookieJar()) // .cookieJar(cookieJar) // .addInterceptor(cookie) // .addInterceptor(offlineCacheInterceptor) // .addInterceptor(netCacheInterceptor) .addInterceptor(loggingInterceptor) // .sslSocketFactory(TrustAllCerts.createSSLSocketFactory()) // .hostnameVerifier(TrustAllCerts.TrustAllHostnameVerifier()) // .cache(cache) // builder.interceptors().add(cookie) mOkHttpClient = builder.build() } fun <T> createService(clazz: Class<T>, baseUrl: String = Urls.BASE_URL): T { return Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(mOkHttpClient) .baseUrl(baseUrl) .build() .create(clazz) } }
1
null
1
1
cf892fe664605873d24b4c3cbb4c4cd4bbcc8acb
2,920
fastapi-study
Apache License 2.0
js/js.translator/testData/inlineStdlib/cases/thisInExtension.kt
staltz
38,581,975
true
{"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831}
package foo // CHECK_CONTAINS_NO_CALLS: testImplicitThis // CHECK_CONTAINS_NO_CALLS: testExplicitThis class A(var value: Int) fun testImplicitThis(a: A, newValue: Int) { with (a) { value = newValue } } fun testExplicitThis(a: A, newValue: Int) { with (a) { this.value = newValue } } fun box(): String { val a = A(0) assertEquals(0, a.value) testImplicitThis(a, 10) assertEquals(10, a.value) testExplicitThis(a, 20) assertEquals(20, a.value) return "OK" }
0
Java
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
522
kotlin
Apache License 2.0
clouddb-kotlin/app/src/main/java/com/huawei/agc/clouddb/quickstart/model/StorageLocationHelper.kt
justSmallBaiCai
553,558,656
true
{"Markdown": 21, "Text": 12, "Java Properties": 23, "JSON": 2, "Gradle": 46, "Shell": 12, "Batchfile": 14, "Proguard": 20, "XML": 315, "Kotlin": 48, "Java": 62, "Ignore List": 30, "JavaScript": 1, "CMake": 8, "C++": 6, "INI": 2, "C": 2}
package com.huawei.agc.clouddb.quickstart.model import com.huawei.agc.clouddb.quickstart.CloudDBQuickStartApplication import com.huawei.agconnect.AGCRoutePolicy import java.util.ArrayList class StorageLocationHelper { private val mCallbacks: MutableList<StorageLocationChangeCallback> = ArrayList() fun changeLocation(routePolicy: AGCRoutePolicy?) { if (CloudDBQuickStartApplication.regionRoutePolicy === routePolicy) { return } if (routePolicy != null) { CloudDBQuickStartApplication.regionRoutePolicy = routePolicy } for (callback in mCallbacks) { callback.onStorageLocationChanged() } } fun addCallback(callback: StorageLocationChangeCallback) { mCallbacks.add(callback) } interface StorageLocationChangeCallback { fun onStorageLocationChanged() } }
0
null
0
0
efd082996b5d1c2405937675fc810c2325ef5d7f
885
agc-android-demos
Apache License 2.0
app/src/main/kotlin/kr/ac/snu/hcil/omnitrack/core/calculation/expression/expressions/LatestItemTimestampExpression.kt
yghokim
62,933,149
false
null
package kr.ac.snu.hcil.omnitrack.core.calculation.expression.expressions import android.content.Context import com.udojava.evalex.Expression import kr.ac.snu.hcil.omnitrack.core.calculation.expression.ExpressionConstants import kr.ac.snu.hcil.omnitrack.core.calculation.expression.ExpressionConstants.Companion.EXPRESSION_ZERO import kr.ac.snu.hcil.omnitrack.core.calculation.expression.LongLazyNumber import kr.ac.snu.hcil.omnitrack.core.database.BackendDbManager import kr.ac.snu.hcil.omnitrack.core.types.TimePoint import kr.ac.snu.hcil.omnitrack.core.types.TimeSpan /** * Created by younghokim on 2017. 11. 14.. */ class LatestItemTimestampExpression(context: Context) : RealmLazyFunction(context, ExpressionConstants.COMMAND_TRACKER_LATEST_ITEM_TIME, 2) { override fun lazyEval(lazyParams: MutableList<Expression.LazyNumber>?): Expression.LazyNumber { realmProvider.get().use { realm -> val trackerId = lazyParams?.get(0)?.string val queryBase = dbManager.get().makeItemsQuery(trackerId, null, null, realm) val overrideAttributeLocalId = lazyParams?.get(1)?.string if (overrideAttributeLocalId == null) { return LongLazyNumber(queryBase.max(BackendDbManager.FIELD_TIMESTAMP_LONG)?.toLong() ?: 0) } else { val latestItem = queryBase.findAll().maxBy { val value = it.getValueOf(overrideAttributeLocalId) if (value is TimePoint) { return@maxBy value.timestamp } else if (value is TimeSpan) { return@maxBy value.to } else return@maxBy 0L } if (latestItem == null) { return EXPRESSION_ZERO } else { val value = latestItem.getValueOf(overrideAttributeLocalId) return LongLazyNumber(if (value is TimePoint) { value.timestamp } else if (value is TimeSpan) { value.to } else 0L) } } } } }
9
Kotlin
4
8
f13e5c157d5646c3f9493c4fdc25ed3b1fc2e296
2,160
omnitrack_android
MIT License
px-services/src/main/java/com/mercadopago/android/px/internal/tracking/TrackingRepository.kt
mmunozpatinomeli
281,752,383
true
{"Java": 2839539, "Kotlin": 288781, "Python": 4215}
package com.mercadopago.android.px.internal.tracking interface TrackingRepository { val sessionId: String val flowId: String val flowDetail: Map<String, Any> fun configure(model: Model) fun reset() data class Model(val sessionId: String, val flowId: String?, val flowDetail: Map<String, Any>?) { constructor(sessionId: String) : this(sessionId, null, null) } companion object { @JvmStatic var OLD_STATIC_FLOW_ID: String? = null @JvmStatic var OLD_STATIC_FLOW_DETAIL: Map<String, Any>? = null } }
0
Java
0
0
8fba15dc7beb07f537d85f8be11070e5876a4028
559
px-android
MIT License
module/job/src/main/kotlin/rain/job/CronInvoker.kt
IceCream-QAQ
208,843,258
false
null
package rain.job import java.lang.reflect.Method import kotlin.reflect.KFunction import kotlin.reflect.full.callSuspend fun interface CronInvoker { suspend operator fun invoke() companion object { fun reflect(instance: Any, method: Method) = CronInvoker { method.invoke(instance) } fun kFun(instance: Any, method: KFunction<*>) = CronInvoker { method.call(instance) } fun suspendFun(instance: Any, method: KFunction<*>) = CronInvoker { method.callSuspend(instance) } fun dsl(function: suspend () -> Unit) = CronInvoker(function) fun runnable(runnable: Runnable) = CronInvoker { runnable.run() } } }
9
null
12
60
c2f92f2d0b942f59773f27208663e24991ca4562
653
Rain
Apache License 2.0
src/main/kotlin/com/exactpro/th2/sim/util/StringUtils.kt
th2-net
314,269,846
false
{"Java": 60123, "Kotlin": 27306, "Dockerfile": 303}
/* * Copyright 2020-2021 Exactpro (Exactpro Systems Limited) * * 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.exactpro.th2.sim.util fun findSubstring(charSequence: CharSequence, regex: String, fromIndex: Int): String { val pattern = regex.toRegex() return pattern.find(charSequence, fromIndex)?.value ?: "" } fun findSubstring(charSequence: CharSequence, regex: String): String { return findSubstring(charSequence, regex, 0) }
3
null
2
1
d93f345b2b058f3c6f34b56b7797ad0f79208b3b
967
th2-sim
Apache License 2.0
app/src/main/java/org/apache/fineract/data/models/customer/Address.kt
gen8tech
141,942,064
true
{"Java Properties": 3, "YAML": 1, "XML": 139, "Gradle": 4, "Markdown": 6, "Shell": 1, "Batchfile": 1, "Ignore List": 2, "Proguard": 1, "Java": 206, "Kotlin": 42, "JSON": 11}
package org.apache.fineract.data.models.customer import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Address( @SerializedName("street") var street: String? = null, @SerializedName("city") var city: String? = null, @SerializedName("region") var region: String? = null, @SerializedName("postalCode") var postalCode: String? = null, @SerializedName("countryCode") var countryCode: String? = null, @SerializedName("country") var country: String? = null ) : Parcelable
0
Java
0
0
f9b01d3634f66dd34609ba671e38aa7b65bbe53a
578
fineract-cn-mobile
Apache License 2.0
plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/tree/workspace/ContentRootCollectorTest.kt
cxrvh
200,416,113
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.idea.maven.importing.tree.workspace import com.intellij.maven.testFramework.MavenTestCase import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.junit.Assert import org.junit.Test class ContentRootCollectorTest : MavenTestCase() { @Test fun `test simple content root`() { val baseContentRoot = "/home/a/b/c/maven" val sourceMain = "/home/a/b/c/maven/src/main/java" val resourceMain = "/home/a/b/c/maven/src/main/resources" val sourceTest = "/home/a/b/c/maven/src/test/java" val target = "/home/a/b/c/maven/target" val generatedSourceFolder = "/home/a/b/c/maven/target/generated-sources/java" val generatedTestSourceFolder = "/home/a/b/c/maven/target/generated-sources-test/java" val annotationProcessorDirectory = "/home/a/b/c/maven/target/annotation-processor/java" val annotationProcessorTestDirectory = "/home/a/b/c/maven/target/annotation-processor-test/java" val contentRoots = ContentRootCollector.collect( baseContentRoot, mapOf( sourceMain to JavaSourceRootType.SOURCE, resourceMain to JavaResourceRootType.RESOURCE, sourceTest to JavaSourceRootType.TEST_SOURCE, ), listOf(target), GeneratedFoldersHolder(annotationProcessorDirectory, annotationProcessorTestDirectory, generatedSourceFolder, generatedTestSourceFolder) ) Assert.assertEquals(1, contentRoots.size) val map = contentRootsHolder2Map(contentRoots) assertContentRoot(map, sourceMain, baseContentRoot) assertContentRoot(map, resourceMain, baseContentRoot) assertContentRoot(map, sourceTest, baseContentRoot) assertContentRoot(map, target, baseContentRoot) assertContentRoot(map, generatedSourceFolder, baseContentRoot) assertContentRoot(map, generatedTestSourceFolder, baseContentRoot) assertContentRoot(map, annotationProcessorDirectory, baseContentRoot) assertContentRoot(map, annotationProcessorTestDirectory, baseContentRoot) } @Test fun `test multiply content roots and empty exclude root and generated sources`() { val baseContentRoot = "/home/a/b/c/maven/src/main" val sourceMain = "/home/a/b/c/maven/src/main/java" val sourceMain2 = "/home/a/b/c/maven/java2" val target = "/home/a/b/c/maven/target" val generatedSourceFolder = "/home/a/b/c/maven/target/generated-sources/java" val generatedTestSourceFolder = "/home/a/b/c/maven/target/generated-sources-test/java" val contentRoots = ContentRootCollector.collect( baseContentRoot, mapOf( sourceMain to JavaSourceRootType.SOURCE, sourceMain2 to JavaSourceRootType.SOURCE ), listOf(target), GeneratedFoldersHolder(null, null, generatedSourceFolder, generatedTestSourceFolder) ) Assert.assertEquals(4, contentRoots.size) val map = contentRootsHolder2Map(contentRoots) assertContentRoot(map, sourceMain, baseContentRoot) assertContentRoot(map, sourceMain2, sourceMain2) assertContentRoot(map, target, null) assertContentRoot(map, generatedSourceFolder, generatedSourceFolder) assertContentRoot(map, generatedTestSourceFolder, generatedTestSourceFolder) } @Test fun `test that target root created if needed`() { val baseContentRoot = "/home/a/b/c/maven" val target = "/home/a/b/c/maven/target" val contentRoots = ContentRootCollector.collect( baseContentRoot, emptyMap(), listOf(target), GeneratedFoldersHolder(null, null, null, null), true ) Assert.assertEquals(1, contentRoots.size) val map = contentRootsHolder2Map(contentRoots) assertContentRoot(map, target, baseContentRoot) } @Test fun `test multiply source and resources content roots and annotation processor sources`() { val baseContentRoot = "/home/a/b/c/maven/src/main" val sourceMain = "/home/a/b/c/maven/src/main/java" val sourceMain2 = "/home/a/b/c/maven/java2" val sourceMain3 = "/home/a/b/c/maven/main/java3" val sourceMain4 = "/home/a/b/c/other/java4" val resourceMain = "/home/a/b/c/maven/src/main/resource" val resourceMain2 = "/home/a/b/c/maven/resource2" val resourceMain3 = "/home/a/b/c/maven/main/resource3" val resourceMain4 = "/home/a/b/c/other/resource4" val annotationProcessorDirectory = "/home/a/b/c/maven/target/annotation-processor/java" val annotationProcessorTestDirectory = "/home/a/b/c/maven/target/annotation-processor-test/java" val contentRoots = ContentRootCollector.collect( baseContentRoot, mapOf( sourceMain4 to JavaSourceRootType.SOURCE, sourceMain3 to JavaSourceRootType.SOURCE, sourceMain2 to JavaSourceRootType.SOURCE, sourceMain to JavaSourceRootType.SOURCE, resourceMain4 to JavaResourceRootType.RESOURCE, resourceMain3 to JavaResourceRootType.RESOURCE, resourceMain2 to JavaResourceRootType.RESOURCE, resourceMain to JavaResourceRootType.RESOURCE, ), emptyList(), GeneratedFoldersHolder(annotationProcessorDirectory, annotationProcessorTestDirectory, null, null) ) Assert.assertEquals(9, contentRoots.size) val map = contentRootsHolder2Map(contentRoots) assertContentRoot(map, sourceMain, baseContentRoot) assertContentRoot(map, sourceMain2, sourceMain2) assertContentRoot(map, sourceMain3, sourceMain3) assertContentRoot(map, sourceMain4, sourceMain4) assertContentRoot(map, resourceMain, baseContentRoot) assertContentRoot(map, resourceMain2, resourceMain2) assertContentRoot(map, resourceMain3, resourceMain3) assertContentRoot(map, resourceMain4, resourceMain4) assertContentRoot(map, annotationProcessorDirectory, annotationProcessorDirectory) assertContentRoot(map, annotationProcessorTestDirectory, annotationProcessorTestDirectory) } private fun assertContentRoot(rootMap: Map<String, String>, path: String, root: String?) { Assert.assertEquals(root, rootMap.get(path)) } private fun contentRootsHolder2Map(dataHolders: Collection<ContentRootDataHolder>): Map<String, String> { val contentRootByPath = mutableMapOf<String, String>() for (each in dataHolders) { for (sourceFolder in each.sourceFolders) { contentRootByPath.put(sourceFolder.path, each.contentRoot) } for (sourceFolder in each.generatedFolders) { contentRootByPath.put(sourceFolder.path, each.contentRoot) } for (sourceFolder in each.annotationProcessorFolders) { contentRootByPath.put(sourceFolder.path, each.contentRoot) } for (path in each.excludedPaths) { contentRootByPath.put(path, each.contentRoot) } } return contentRootByPath; } }
1
null
1
1
8cf0b2f400dd492ebba45b175c044c14f053a15f
6,919
intellij-community
Apache License 2.0
bbfgradle/tmp/results/JVM-Xuse-fir/BACKEND_qkoekxc_FILE.kt
DaniilStepanov
346,008,310
false
{"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1}
// Bug happens on JVM -Xuse-fir // WITH_RUNTIME // TARGET_BACKEND: JVM // FILE: tmp0.kt fun = fu6(TODO) fun fu6(
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
226
kotlinWithFuzzer
Apache License 2.0
src/main/kotlin/com/vdsirotkin/telegrambot/localization/MessageSourceProvider.kt
vdsirotkin
704,079,036
false
{"Kotlin": 27794}
package com.vdsirotkin.telegrambot.localization import com.vdsirotkin.telegrambot.user.Language import com.vdsirotkin.telegrambot.user.UsersRepository import org.springframework.context.MessageSource import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service @Service class MessageSourceProvider( private val messageSource: MessageSource, private val usersRepository: UsersRepository, ) { fun getMessageSource(chatId: Long): MessageSourceWrapper { val user = usersRepository.findByIdOrNull(chatId) ?: throw IllegalArgumentException("Can't find user with chat id = '$chatId' in database") return MessageSourceWrapper(messageSource, user.language.locale) } fun getMessageSource(language: Language): MessageSourceWrapper = MessageSourceWrapper(messageSource, language.locale) }
0
Kotlin
0
0
23395a7ac63841699aae7f6e0201f6f22848f939
860
kotlin_telegram_bot_template
Apache License 2.0
app/src/main/java/com/a/getmimo/ui/MainViewModel.kt
CabezasGonzalezJavier
257,917,247
false
null
package com.a.getmimo.ui import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.a.getmimo.domain.entity.Lesson import com.a.getmimo.domain.entity.networking.Status import com.a.getmimo.domain.usecases.GetLessons import com.a.getmimo.ui.common.Event import com.a.getmimo.ui.common.ScopedViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.launch import java.util.* class MainViewModel( private val getLessons: GetLessons, uiDispatcher: CoroutineDispatcher ) : ScopedViewModel(uiDispatcher) { lateinit var lessons: List<Lesson> private var solution = "" var myIterator = 0 private val _model = MutableLiveData<UiModel>() val model: LiveData<UiModel> get() { if (_model.value == null) refresh() return _model } private val _navigation = MutableLiveData<Event<Lesson>>() val navigation: LiveData<Event<Lesson>> = _navigation sealed class UiModel { object Loading : UiModel() object ShowCanCheckYourInternet : UiModel() object ShowErrorCall : UiModel() object ShowEmptyData : UiModel() object RequestCheckInternet : UiModel() object EnableButton : UiModel() object DisableButton : UiModel() object ShowEmptyInput : UiModel() data class Done(val idLesson: Int, val startLesson: Long) : UiModel() data class ShowText(val firstText: String, val secondText: String) : UiModel() } init { initScope() } fun myLaunch() { launch { _model.value = UiModel.Loading val resource = getLessons.invoke() when (resource.status) { Status.SUCCESS -> { if (resource.data != null) { if (resource.data.isEmpty()) { _model.value = UiModel.ShowEmptyData } else { lessons = resource.data checkInput() } } else { _model.value = UiModel.ShowErrorCall } } else -> { _model.value = UiModel.ShowErrorCall } } } } fun refresh() { _model.value = UiModel.RequestCheckInternet } fun checkInternet(continuation: Boolean) { if (continuation) { myLaunch() } else { _model.value = UiModel.ShowCanCheckYourInternet } } private fun checkInput() { if (myIterator < lessons.size) { if (lessons[myIterator].startIndex != null && lessons[myIterator].startIndex != null && lessons[myIterator].content != null ) { if (lessons[myIterator].id != null) { lessons[myIterator].startDate = Calendar.getInstance().timeInMillis if (lessons[myIterator].content!!.size > 1) { _model.value = UiModel.ShowText( lessons[myIterator].content!![0].text!!, lessons[myIterator].content!![2].text!! ) solution = lessons[myIterator].content!![1].text!! } else { checkOneContent( lessons[myIterator].content!![0].text!!, lessons[myIterator].startIndex!!, lessons[myIterator].endIndex!!, lessons[myIterator].content!![0].text!!.length ) } } } else { myIterator += 1 checkInput() } } } fun lessonDone() { _navigation.value = Event(lessons[myIterator]) } private fun checkOneContent(text: String, startIndex: Int, endIndex: Int, finish: Int) { solution = text.substring( startIndex, endIndex ) _model.value = UiModel.ShowText( text.subSequence( 0, startIndex ).toString(), text.subSequence( endIndex, finish ).toString() ) } fun checkSolution(userSolution: String) { if (userSolution.isNotEmpty()) { if (solution == userSolution) { _model.value = UiModel.EnableButton } else { _model.value = UiModel.DisableButton } } else { _model.value = UiModel.ShowEmptyInput } } }
0
Kotlin
1
0
0458b3af097e6f2d1c4fcf02164e29ebcbd412ee
4,757
GetMimo
Apache License 2.0
tbs/src/main/java/com/angcyo/tbs/core/dslitem/DslBaseWebMenuItem.kt
angcyo
229,037,684
false
null
package com.angcyo.tbs.core.dslitem import com.angcyo.dsladapter.DslAdapterItem import com.angcyo.library.ex._drawable import com.angcyo.tbs.R import com.angcyo.widget.DslViewHolder /** * * Email:<EMAIL> * @author angcyo * @date 2020/04/22 * Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved. */ open class DslBaseWebMenuItem : DslAdapterItem() { var menuText: CharSequence? = null var menuIcon: Int = -1 init { itemLayoutId = R.layout.tbs_web_menu_item } override fun onItemBind( itemHolder: DslViewHolder, itemPosition: Int, adapterItem: DslAdapterItem, payloads: List<Any> ) { super.onItemBind(itemHolder, itemPosition, adapterItem, payloads) //文本 itemHolder.tv(R.id.lib_text_view)?.apply { text = menuText } //图标 itemHolder.img(R.id.lib_image_view)?.apply { setImageDrawable(_drawable(menuIcon)) } } }
0
Kotlin
4
3
13dc66c06abd72995fb8393655bb69544c259248
975
UICoreEx
MIT License
acornui-utils/src/commonMain/kotlin/com/acornui/collection/ConcurrentListIterator.kt
fuzzyweapon
130,889,917
true
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
/* * Copyright 2018 Poly Forest * * 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.acornui.collection import com.acornui.core.Disposable import com.acornui.recycle.Clearable interface ConcurrentList<out E> : List<E> { fun concurrentIterator(): ConcurrentListIterator<E> } interface MutableConcurrentList<E> : ConcurrentList<E>, MutableList<E> { override fun concurrentIterator(): MutableConcurrentListIterator<E> } /** * A ConcurrentListIterator watches concurrent add and remove changes on the list and moves the cursor logically * so that items are neither skipped nor repeated. */ interface ConcurrentListIterator<out E> : Clearable, ListIterator<E>, Iterable<E>, Disposable { /** * The size of the list. */ val size: Int /** * The current cursor index. */ var cursor: Int } inline fun <E> ConcurrentListIterator<E>.iterate(body: (E) -> Boolean) { clear() while (hasNext()) { val shouldContinue = body(next()) if (!shouldContinue) break } } inline fun <E> ConcurrentListIterator<E>.iterateReversed(body: (E) -> Boolean) { clear() cursor = size while (hasPrevious()) { val shouldContinue = body(previous()) if (!shouldContinue) break } } fun <E> ConcurrentListIteratorImpl( list: ObservableList<E> ) : ConcurrentListIterator<E> { return WatchedConcurrentListIteratorImpl(ConcurrentListIteratorImpl(list as List<E>), list) } private open class WatchedConcurrentListIteratorImpl<out E>(private val impl: ConcurrentListIteratorImpl<E>, private val list: ObservableList<E>) : ConcurrentListIterator<E> by impl { private val addedHandler = { index: Int, _: E -> impl.notifyAddedAt(index) } private val removedHandler = { index: Int, _: E -> impl.notifyRemovedAt(index) } init { list.added.add(addedHandler) list.removed.add(removedHandler) } override fun dispose() { list.added.remove(addedHandler) list.removed.remove(removedHandler) } } fun <E> MutableConcurrentListIteratorImpl( list: MutableObservableList<E> ) : MutableConcurrentListIterator<E> { return WatchedMutableConcurrentListIteratorImpl(MutableConcurrentListIteratorImpl(list as MutableList<E>), list) } private open class WatchedMutableConcurrentListIteratorImpl<E>(private val impl: MutableConcurrentListIteratorImpl<E>, private val list: MutableObservableList<E>) : WatchedConcurrentListIteratorImpl<E>(impl, list), MutableConcurrentListIterator<E> { override fun iterator(): MutableIterator<E> = list.iterator() override fun add(element: E) { impl.add(element) } override fun remove() { impl.remove() } override fun set(element: E) { impl.set(element) } } open class ConcurrentListIteratorImpl<out E>( private val list: List<E> ) : ConcurrentListIterator<E> { override val size: Int get() = list.size /** * Index of next element to return */ override var cursor: Int = 0 /** * Index of last element returned; -1 if no such */ protected var lastRet: Int = -1 fun notifyAddedAt(index: Int) { if (cursor > index) cursor++ if (lastRet > index) lastRet++ } fun notifyRemovedAt(index: Int) { if (cursor > index) cursor-- if (lastRet > index) lastRet-- } fun notifyCleared() { cursor = Int.MAX_VALUE } override fun hasNext(): Boolean { return cursor < list.size } override fun next(): E { val i = cursor if (i >= list.size) throw NoSuchElementException() cursor = i + 1 lastRet = i return list[i] } override fun nextIndex(): Int { return cursor } override fun hasPrevious(): Boolean { return cursor > 0 } override fun previous(): E { val i = cursor - 1 if (i < 0) throw NoSuchElementException() cursor = i lastRet = i return list[i] } override fun previousIndex(): Int { return cursor - 1 } override fun clear() { cursor = 0 lastRet = -1 } override fun iterator(): Iterator<E> { return this } override fun dispose() { } } interface MutableConcurrentListIterator<E> : ConcurrentListIterator<E>, MutableListIterator<E>, MutableIterable<E> /** * A ConcurrentListIterator watches concurrent changes on the list and moves the cursor logically * so that items are neither skipped nor repeated. */ open class MutableConcurrentListIteratorImpl<E>( private val list: MutableList<E> ) : ConcurrentListIteratorImpl<E>(list), MutableConcurrentListIterator<E> { override fun iterator(): MutableIterator<E> { return this } override fun remove() { if (lastRet < 0) throw NoSuchElementException() list.removeAt(lastRet) cursor = lastRet lastRet = -1 } override fun set(element: E) { if (lastRet < 0) throw IllegalStateException() list[lastRet] = element } override fun add(element: E) { val i = cursor list.add(i, element) cursor = i + 1 lastRet = -1 } }
0
Kotlin
1
0
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
5,273
acornui
Apache License 2.0
src/test/kotlin/ToolsEnd2End.kt
NexSabre
304,905,839
false
null
import khttp.post import khttp.responses.Response import java.net.HttpURLConnection import java.net.URL fun makeGetRequest(baseUrl: String = "http://localhost:8080", endpoint: String, method: String = "GET"): String { val url = URL(baseUrl + endpoint) with(url.openConnection() as HttpURLConnection) { requestMethod = method return inputStream.bufferedReader().readText() } } fun makePostRequest(baseUrl: String = "http://localhost:8080", endpoint: String, payload: Any?): Response = post(baseUrl + endpoint, data = payload)
2
Kotlin
0
0
120f5f8049fcec11e4de2805518bf838eab0b8c4
563
hardware-reservation-tool
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/report/chart/ChartBuilder.kt
atlassian
171,860,470
false
{"HTML": 661490, "Kotlin": 336680, "Java": 35695}
package com.atlassian.performance.tools.report.chart import com.atlassian.performance.tools.jiraactions.api.ActionMetric import com.atlassian.performance.tools.jiraactions.api.ActionResult import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit import java.util.* internal class ChartBuilder { private val bucketSize = Duration.ofMinutes(1) fun build( metrics: List<ActionMetric> ): Chart<Instant> { val buckets = aggregate(metrics) val slicedBuckets = aggregate(slice(metrics)) val lines = mutableListOf<ChartLine<Instant>>() lines += averageLatencies(buckets, label = "Mean latency") lines += averageLatenciesPerLabel(metrics) lines += countActions(buckets) lines += countEncounteredVirtualUsers(buckets) lines += countActiveVirtualUsers(slicedBuckets) lines += countAliveVirtualUsers(slicedBuckets) lines += getErrorRate(buckets) return Chart(lines) } private fun aggregate( metrics: List<ActionMetric> ): List<Bucket> { return metrics .groupBy { it.start.truncatedTo(ChronoUnit.MINUTES) } .entries .map { Bucket(it.key, it.value) } .sorted() } private fun averageLatenciesPerLabel( metrics: List<ActionMetric> ): List<ChartLine<Instant>> = metrics .map { it.label } .toSet() .sorted() .map { label -> averageLatencies( aggregate(metrics.filter { metric -> metric.label == label }), label, hidden = true ) } private fun countEncounteredVirtualUsers( buckets: List<Bucket> ): ChartLine<Instant> { val totalEncountered = mutableSetOf<UUID>() return ChartLine( label = "Encountered Virtual Users", yAxisId = "count-axis", type = "line", hidden = true, data = buckets.map { bucket -> bucket.toPoint { metrics -> val encountered = metrics .asSequence() .map { it.virtualUser } .toSet() totalEncountered.addAll(encountered) return@toPoint totalEncountered.size.toDouble() } } ) } private fun countAliveVirtualUsers( buckets: List<Bucket> ): ChartLine<Instant> = ChartLine( label = "Alive Virtual Users", yAxisId = "count-axis", type = "line", hidden = true, data = buckets.map { bucket -> bucket.toPoint { metrics -> metrics .map { it.virtualUser } .toSet() .count() .toDouble() } } ) private fun countActiveVirtualUsers( buckets: List<Bucket> ): ChartLine<Instant> = ChartLine( label = "Active Virtual Users", yAxisId = "count-axis", type = "line", hidden = false, data = buckets.map { bucket -> bucket.toPoint { metrics -> metrics .groupBy { it.virtualUser } .values .flatMap { compact(it) } .map { it.duration } .fold(Duration.ZERO) { total, duration -> total + duration } .toMillis() .toDouble() .div(bucketSize.toMillis()) } } ) /** * Slices wide metrics to thinner metrics, each fitting into a bucket. */ private fun slice( metrics: List<ActionMetric> ): List<ActionMetric> = metrics.flatMap { whole -> val slices = mutableListOf<ActionMetric>() var sliceStart = whole.start val wholeEnd = whole.end while (sliceStart < wholeEnd) { val sliceEnd = minOf( sliceStart.truncatedTo(ChronoUnit.MINUTES) + bucketSize, wholeEnd ) slices += whole.copy( start = sliceStart, duration = Duration.between(sliceStart, sliceEnd) ) sliceStart = sliceEnd } return@flatMap slices } /** * Compacts overlapping metrics. */ private fun compact( metrics: List<ActionMetric> ): List<ActionMetric> = metrics .sortedBy { it.start } .fold(listOf()) { compacted, metric -> return@fold when { compacted.isEmpty() -> listOf(metric) metric.end < compacted.last().end -> compacted else -> compacted + metric } } private fun countActions( buckets: List<Bucket> ): ChartLine<Instant> = ChartLine( label = "Actions", yAxisId = "count-axis", type = "line", hidden = false, data = buckets.map { bucket -> bucket.toPoint { metrics -> metrics .count() .toDouble() } } ) private fun getErrorRate( buckets: List<Bucket> ): ChartLine<Instant> = ChartLine( label = "Error rate", yAxisId = "percentage-axis", type = "line", hidden = false, data = buckets.map { bucket -> bucket.toPoint { metrics -> val errors = metrics .filter { it.result == ActionResult.ERROR } .count() .toDouble() val total = metrics .count() .toDouble() return@toPoint (errors / total) * 100.0 } } ) private fun averageLatencies( buckets: List<Bucket>, label: String, hidden: Boolean = false ): ChartLine<Instant> = ChartLine( label = label, yAxisId = "duration-axis", type = "line", hidden = hidden, data = buckets.map { bucket -> bucket.toPoint { metrics -> metrics .map { it.duration.toMillis() } .average() } } ) } private data class Bucket( private val start: Instant, private val metrics: List<ActionMetric> ) : Comparable<Bucket> { fun toPoint( metricsReduction: (List<ActionMetric>) -> Double ): Tick = Tick( time = start, value = metricsReduction(metrics) ) override fun compareTo( other: Bucket ): Int = compareBy<Bucket> { it.start }.compare(this, other) }
0
HTML
25
6
49bb05fc540d4ee3133bbc9e85db796f141a93a1
6,744
report
Apache License 2.0
common-base/src/main/java/com/king/mvvm/base/BaseApplicationInjector.kt
jenly1314
274,194,244
false
null
package com.king.mvvm.base /** * @author <a href="mailto:<EMAIL>">Jenly</a> */ interface BaseApplicationInjector { fun inject(app: BaseApp) }
0
Kotlin
4
26
dc51cbb32251354d40c292a9864cedbe92671f0b
150
MVVMFrameComponent
MIT License
src/commonMain/kotlin/com/mugames/vidsnapkit/extractor/LinkedIn.kt
Udhayarajan
582,397,133
false
null
/* * Copyright (c) 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.mugames.vidsnapkit.extractor import com.mugames.vidsnapkit.Util import com.mugames.vidsnapkit.dataholders.* import com.mugames.vidsnapkit.network.HttpRequest import org.json.JSONArray import java.util.regex.Pattern /** * @author Udhaya * Created on 24-05-2022 */ class LinkedIn internal constructor(url: String) : Extractor(url) { private val formats = Formats() override suspend fun analyze() { formats.url = inputUrl formats.src = "LinkedIn" onProgress(Result.Progress(ProgressState.Start)) scratchWebpage(HttpRequest(inputUrl).getResponse()) } private suspend fun scratchWebpage(page: String) { val matcher = Pattern.compile("data-sources=\"(.*?)\"").matcher(page) if (matcher.find()) { fun findTitle(vararg regexes: Regex, defaultTitle: String):String{ for (regex in regexes){ val m = Pattern.compile(regex.toString()).matcher(page) if (m.find()){ return m.group(1)?:defaultTitle } } return defaultTitle } val jsonString = Util.decodeHTML(matcher.group(1)) val jsonArray = JSONArray(jsonString) for (i in 0 until jsonArray.length()) { val data = jsonArray.getJSONObject(i) formats.videoData.add( VideoResource( data.getString("src"), data.getString("type"), getResolutionFromVideoUrl(data.getString("src")) ) ) } formats.title = findTitle( Regex("\"twitter:title\"\\s*content\\s*=\\s*\"(.*?)\">"), Regex("\"og:title\"\\s*content\\s*=\\s*\"(.*?)\">"), Regex("\"twitter:description\"\\s*content\\s*=\\s*\"([\\w\\W]*?)\">"), Regex("\"og:description\"\\s*content\\s*=\\s*\"([\\w\\W]*?)\">"), defaultTitle = "LinkedIn_Video" ) getThumbnailData(page) videoFormats.add(formats) finalize() } } private fun getThumbnailData(page: String){ fun findThumbnail(vararg regexes: Regex): String? { for (regex in regexes) { val matcher = Pattern.compile(regex.toString()).matcher(page) if (matcher.find()) return Util.decodeHTML(matcher.group(1)) } return null } val thumbnailUrl = findThumbnail( Regex("\"twitter:image\"\\s*content\\s*=\\s*\"(.*?)\">"), Regex("\"og:image\"\\s*content\\s*=\\s*\"(.*?)\">") ) thumbnailUrl?.let { formats.imageData.add(ImageResource(it)) } } private fun getResolutionFromVideoUrl(url: String): String { val matcher = Pattern.compile("mp4-(.*?)-").matcher(url) if (matcher.find()) { return matcher.group(1) ?: "--" } return "--" } }
1
null
1
2
4ad7f5690148f4acd84187cad20f4487c0766cb9
3,692
VidSnapKit-Ultimate
Apache License 2.0
src/main/kotlin/io/lexadiky/pokeapi/network/CacheSettings.kt
lexa-diky
551,074,701
false
null
package io.lexadiky.pokeapi.network import java.io.File /** * Specifies how client will store request cache */ sealed interface CacheSettings { /** * Requests will not be cached */ object Disabled: CacheSettings /** * Requests will be cached on disc at [directory] */ data class FileStorage(val directory: File): CacheSettings }
0
Kotlin
0
2
d4fa57d81fa6b5c13346c835d5d9bc4b3fb0f585
371
pokeapi-kotlin
MIT License
app/src/main/java/com/example/android/politicalpreparedness/MainActivity.kt
tnanhd
851,046,480
false
{"Kotlin": 51785}
package com.example.android.politicalpreparedness import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onSupportNavigateUp(): Boolean { return findNavController().navigateUp() || super.onSupportNavigateUp() } private fun findNavController(): NavController { return (supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment).navController } }
0
Kotlin
0
0
463e626e2e2815544637fa12d70ffcacda621d47
726
uda-political-preparedness
Apache License 2.0
native_library/android/FirebaseANE/VisionBarcode/src/main/java/com/tuarua/firebase/vision/barcode/extensions/FreVisionBarcodeEmail.kt
morristech
190,721,056
true
{"ActionScript": 600651, "Swift": 387718, "Kotlin": 345447, "Shell": 118960, "Objective-C": 70526, "Java": 61410, "Batchfile": 18834, "PowerShell": 15037, "C": 2596}
/* * Copyright 2018 Tua Rua Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuarua.firebase.vision.barcode.extensions import com.adobe.fre.FREObject import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.tuarua.frekotlin.FREObject import com.tuarua.frekotlin.set import com.tuarua.frekotlin.toFREObject fun FirebaseVisionBarcode.Email.toFREObject(): FREObject? { val ret = FREObject("com.tuarua.firebase.vision.BarcodeEmail") ret["address"] = this.address?.toFREObject() ret["body"] = this.body?.toFREObject() ret["subject"] = this.subject?.toFREObject() ret["type"] = this.type.toFREObject() return ret }
0
ActionScript
0
0
75b2f39cc3a3f25563d7741e92f8a12d3c1eace4
1,192
Firebase-ANE
Apache License 2.0
app/src/test/java/com/marknkamau/justjava/ui/addressBook/AddressBookViewModelTest.kt
MarkNjunge
86,477,705
false
null
package com.marknkamau.justjava.ui.addressBook import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.marknjunge.core.data.model.Address import com.marknjunge.core.data.model.Resource import com.marknjunge.core.data.model.User import com.marknjunge.core.data.repository.UsersRepository import com.marknkamau.justjava.utils.SampleData import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.impl.annotations.MockK import io.mockk.spyk import io.mockk.verify import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule class AddressBookViewModelTest { @get:Rule var rule: TestRule = InstantTaskExecutorRule() @ExperimentalCoroutinesApi private val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher() @MockK private lateinit var usersRepository: UsersRepository private lateinit var viewModel: AddressBookViewModel @ExperimentalCoroutinesApi @Before fun setup() { MockKAnnotations.init(this, relaxUnitFun = true) Dispatchers.setMain(testDispatcher) viewModel = AddressBookViewModel(usersRepository) } @ExperimentalCoroutinesApi @After fun teardown() { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } @Test fun `can get addresses`() { val resource = Resource.Success(SampleData.user) coEvery { usersRepository.getCurrentUser() } returns flow { emit(resource) } val observer = spyk<Observer<Resource<User>>>() viewModel.user.observeForever(observer) viewModel.getAddresses() verify { observer.onChanged(resource) } } @Test fun `can add address`() { val resource = Resource.Success(SampleData.address) coEvery { usersRepository.addAddress(any()) } returns resource val observer = spyk<Observer<Resource<Address>>>() viewModel.addAddress(SampleData.address).observeForever(observer) verify { observer.onChanged(resource) } } @Test fun `can delete address`() { val resource = Resource.Success(Unit) coEvery { usersRepository.deleteAddress(any()) } returns resource val observer = spyk<Observer<Resource<Unit>>>() viewModel.deleteAddress(SampleData.address).observeForever(observer) verify { observer.onChanged(resource) } } }
1
null
36
74
e3811f064797d50fadef4033bf1532b3c2ceef8d
2,732
JustJava-Android
Apache License 2.0
src/test/kotlin/me/haroldmartin/detektrules/WhenBranchSingleLineOrBracesTest.kt
hbmartin
671,255,622
false
{"Kotlin": 39931}
package me.haroldmartin.detektrules import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.rules.KotlinCoreEnvironmentTest import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import io.kotest.matchers.collections.shouldHaveSize import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.junit.jupiter.api.Test @KotlinCoreEnvironmentTest internal class WhenBranchSingleLineOrBracesTest(private val env: KotlinCoreEnvironment) { @Test fun `reports on branches with newline and no brace`() { val code = """ val a = 1 val b = when (a) { 1 -> "yes" else -> "no" } """ val findings = WhenBranchSingleLineOrBraces(Config.empty).compileAndLintWithContext(env, code) findings shouldHaveSize 2 } @Test fun `does not report on branches with braces`() { val code = """ val a = 1 val b = when (a) { 1 -> { "yes" } else -> { "no" } } """ val findings = WhenBranchSingleLineOrBraces(Config.empty).compileAndLintWithContext(env, code) findings shouldHaveSize 0 } @Test fun `does not report on branches on the same line`() { val code = """ val a = 1 val b = when (a) { 1 -> "yes" else -> "no" } """ val findings = WhenBranchSingleLineOrBraces(Config.empty).compileAndLintWithContext(env, code) findings shouldHaveSize 0 } @Test fun `report on branches on the same line with excess spacing`() { val code = """ val a = 1 val b = when (a) { 1 -> "yes" else -> "no" } """ val findings = WhenBranchSingleLineOrBraces(Config.empty).compileAndLintWithContext(env, code) findings shouldHaveSize 2 } @Test fun `report on branches on the same line with no spacing`() { val code = """ val a = 1 val b = when (a) { 1 ->"yes" else ->"no" } """ val findings = WhenBranchSingleLineOrBraces(Config.empty).compileAndLintWithContext(env, code) findings shouldHaveSize 2 } }
0
Kotlin
0
5
3c3afa0a29f74ed06db61163c6b7b1b1b5ed1550
2,376
hbmartin-detekt-rules
Apache License 2.0
appactions/interaction/interaction-capabilities-core/src/main/java/androidx/appactions/interaction/capabilities/core/task/EntitySearchResult.kt
androidx
256,589,781
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.appactions.interaction.capabilities.core.task import java.util.Objects /** * Represents results from searching for ungrounded value(s). * * Returning exactly 1 result means the value will be immediately accepted by the session. * Returning multiple values will leave the argument in disambiguation state, and Assistant should * ask for clarification from the user. * * @property possibleValues The possible values for grounding. * */ class EntitySearchResult<V> internal constructor( val possibleValues: List<V>, ) { override fun toString() = "EntitySearchResult(possibleValues=$possibleValues)" override fun equals(other: Any?): Boolean { return other is EntitySearchResult<*> && possibleValues == other.possibleValues } override fun hashCode() = Objects.hash(possibleValues) /** * Builder for the EntitySearchResult. */ class Builder<V> { private val possibleValues = mutableListOf<V>() /** Sets the search result values. */ fun setPossibleValues(possibleValues: List<V>) = apply { this.possibleValues.clear() this.possibleValues.addAll(possibleValues) } /** * Add one or more search result values. */ fun addPossibleValue(vararg value: V) = apply { possibleValues.addAll(value) } fun build() = EntitySearchResult(possibleValues.toList()) } companion object { /** * Returns an EntitySearchResult with no possible values. */ @JvmStatic fun <V> empty() = EntitySearchResult.Builder<V>().build() } }
23
Kotlin
740
4,353
3492e5e1782b1524f2ab658f1728c89a35c7336d
2,278
androidx
Apache License 2.0
domain/auth/src/main/kotlin/io/github/siyual_park/auth/domain/token/ClaimEmbedder.kt
siyul-park
403,557,925
false
null
package io.github.siyual_park.auth.domain.token import org.springframework.stereotype.Component @Suppress("UNCHECKED_CAST") @Component class ClaimEmbedder { private val processors = mutableListOf<Pair<ClaimEmbedFilter, ClaimEmbeddingStrategy<*>>>() fun <T : Any> register(filter: ClaimEmbedFilter, processor: ClaimEmbeddingStrategy<T>): ClaimEmbedder { processors.add(filter to processor) return this } suspend fun <PRINCIPAL : Any> embedding(principal: PRINCIPAL): Map<String, Any> { val processors = processors .filter { (_, strategy) -> strategy.clazz.isInstance(principal) } .filter { (filter, _) -> filter.isSubscribe(principal) } .map { (_, strategy) -> strategy } return processors.map { it as ClaimEmbeddingStrategy<PRINCIPAL> it.embedding(principal) }.fold(mutableMapOf()) { acc, cur -> acc.also { it.putAll(cur) } } } }
8
Kotlin
0
18
332711a52465e0a10c0125aecf52dd00e247cf58
955
spring-webflux-multi-module-boilerplate
MIT License
kompat/src/main/kotlin/info/ericlin/kompat/net/TrafficStatsCompat.kt
nohitme
92,627,032
false
null
package info.ericlin.kompat.net import android.support.v4.net.TrafficStatsCompat import java.net.DatagramSocket import java.net.Socket import java.net.SocketException /** * Call through [TrafficStatsCompat.tagSocket] */ @Throws(SocketException::class) fun Socket.tagSocketCompat() = TrafficStatsCompat.tagSocket(this) /** * Call through [TrafficStatsCompat.untagSocket] */ @Throws(SocketException::class) fun Socket.untagSocketCompat() = TrafficStatsCompat.untagSocket(this) /** * Call through [TrafficStatsCompat.tagDatagramSocket] */ @Throws(SocketException::class) fun DatagramSocket.tagDatagramSocketCompat() = TrafficStatsCompat.tagDatagramSocket(this) /** * Call through [TrafficStatsCompat.untagDatagramSocket] */ @Throws(SocketException::class) fun DatagramSocket.untagDatagramSocketCompat() = TrafficStatsCompat.untagDatagramSocket(this)
1
Kotlin
0
5
cba832ffa4fbf38a82b535aefda5d39c754e3166
859
android-kompat
Apache License 2.0
litunyi/src/main/java/com/edorin/litunyi/coroutines/SchedulerProvider.kt
Edorin9
182,257,201
false
null
package com.edorin.litunyi.coroutines import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * Rx Scheduler Provider */ interface SchedulerProvider { fun io(): Scheduler fun ui(): Scheduler fun computation(): Scheduler } class AppSchedulerProvider : SchedulerProvider { override fun io(): Scheduler = Schedulers.io() override fun ui(): Scheduler = AndroidSchedulers.mainThread() override fun computation(): Scheduler = Schedulers.computation() }
0
Kotlin
1
0
344bb4554abc554207ccdb245543f7fffe0f0a83
552
android-mvvm
MIT License
client/src/commonMain/kotlin/hu/bme/aut/ixnoyb/kotlinclothingwebshop/client/ordering/ui/BasketScreen.kt
Balintus00
631,205,444
false
{"Kotlin": 778352, "Jupyter Notebook": 202103, "Swift": 1556, "Dockerfile": 485, "HTML": 444}
package hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.ordering.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.Button import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.COMMON_BUTTON_CONTENT_SPACE import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.COMMON_BUTTON_ICON_EDGE_SIZE import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.LoadingSection import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.PlatformSpecificVerticalListScrollbar import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.collectAsStateWithLifecycle import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.formatAmount import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.common.ui.getStandardSpace import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.ordering.viewlogic.BasketComponent import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.ordering.viewlogic.BasketComponent.ViewState.BasketItemsAvailable import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.ordering.viewlogic.BasketComponent.ViewState.Loading import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.ordering.viewlogic.model.OrderItem import hu.bme.aut.ixnoyb.kotlinclothingwebshop.client.root.ui.theme.Material3Typography import kotlinclothingwebshop.client.generated.resources.Res import kotlinclothingwebshop.client.generated.resources.basket_screen_amount_template import kotlinclothingwebshop.client.generated.resources.basket_screen_content_label import kotlinclothingwebshop.client.generated.resources.basket_screen_cta_button_text import kotlinclothingwebshop.client.generated.resources.basket_screen_top_appbar_title import kotlinclothingwebshop.client.generated.resources.basket_screen_total_amount_label import kotlinclothingwebshop.client.generated.resources.ic_shopping_cart_checkout import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import org.jetbrains.compose.resources.stringResource @Composable @OptIn(ExperimentalMaterial3Api::class, ExperimentalResourceApi::class) internal fun BasketScreenTopAppbar( topAppBarScrollBehavior: TopAppBarScrollBehavior, modifier: Modifier = Modifier, ) { CenterAlignedTopAppBar( modifier = modifier, scrollBehavior = topAppBarScrollBehavior, title = { Text(stringResource(Res.string.basket_screen_top_appbar_title)) }, ) } @Composable @OptIn(ExperimentalMaterial3WindowSizeClassApi::class, ExperimentalResourceApi::class) internal fun BasketScreen(component: BasketComponent, modifier: Modifier = Modifier) { val viewState by component.viewState.collectAsStateWithLifecycle() val standardSpace = getStandardSpace(calculateWindowSizeClass().widthSizeClass) (viewState as? Loading)?.let { LoadingSection(modifier) } ?: (viewState as? BasketItemsAvailable)?.let { basketItemsAvailableState -> Box { val lazyListState = rememberLazyListState() LazyColumn( modifier = modifier.padding(standardSpace), state = lazyListState, verticalArrangement = object : Arrangement.Vertical { override fun Density.arrange( totalSize: Int, sizes: IntArray, outPositions: IntArray ) { // https://stackoverflow.com/questions/68959841 var currentOffset = 0 sizes.forEachIndexed { index, size -> if (index == sizes.lastIndex) { outPositions[index] = totalSize - size } else { outPositions[index] = currentOffset currentOffset += size } } } }, ) { item { Text( style = Material3Typography.labelMedium, text = stringResource(Res.string.basket_screen_content_label), ) Spacer(Modifier.height(8.dp)) } items(basketItemsAvailableState.items, key = { it.id }) { basketItem -> BasketItemListItem( orderItem = basketItem, deleteItemAction = { itemID -> component.deleteBasketItem(itemID) }, modifier = Modifier.fillMaxWidth(), ) } item { Spacer(Modifier.height(standardSpace)) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(standardSpace), ) { Row( horizontalArrangement = Arrangement.spacedBy(standardSpace), modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Text( style = Material3Typography.labelSmall, text = stringResource(Res.string.basket_screen_total_amount_label) ) Text( style = Material3Typography.bodyLarge, text = stringResource( Res.string.basket_screen_amount_template, basketItemsAvailableState .items .fold(0) { acc, basketItem -> acc + basketItem.price } .formatAmount() ) ) } Button( modifier = Modifier.fillMaxWidth(), onClick = { component.navigateToOrderFinalization() }, ) { Icon( contentDescription = null, modifier = Modifier .width(COMMON_BUTTON_ICON_EDGE_SIZE) .height(COMMON_BUTTON_ICON_EDGE_SIZE), painter = painterResource(Res.drawable.ic_shopping_cart_checkout), ) Spacer(Modifier.width(COMMON_BUTTON_CONTENT_SPACE)) Text(stringResource(Res.string.basket_screen_cta_button_text)) } } } } PlatformSpecificVerticalListScrollbar( listState = lazyListState, modifier = Modifier .align(Alignment.CenterEnd) .fillMaxHeight(), ) } } } @Composable @OptIn(ExperimentalResourceApi::class) internal fun BasketItemListItem( orderItem: OrderItem, modifier: Modifier = Modifier, deleteItemAction: (String) -> Unit = {}, ) { Column(modifier) { with(orderItem) { ListItem( headlineContent = { Text( maxLines = 1, overflow = TextOverflow.Ellipsis, style = Material3Typography.bodyLarge, text = name, ) }, leadingContent = { AsyncImage( contentDescription = null, model = imageUrl, modifier = Modifier.size(56.dp), ) }, supportingContent = { Text( color = MaterialTheme.colorScheme.onSurfaceVariant, style = Material3Typography.bodyMedium, text = stringResource( Res.string.basket_screen_amount_template, price.formatAmount(), ), ) }, trailingContent = { IconButton( onClick = { deleteItemAction(id) } ) { Icon( contentDescription = null, imageVector = Icons.Default.Delete, ) } }, ) } HorizontalDivider() } }
2
Kotlin
0
0
083046fdf62edc1da0cae6898120bba8487601f6
10,517
kotlin-clothing-webshop
MIT License
app/src/main/java/com/mburakcakir/taketicket/util/enums/EntryType.kt
mburakcakir
319,590,139
false
null
package com.mburakcakir.taketicket.util.enums enum class EntryType { LOGIN, REGISTER }
0
Kotlin
2
3
d8f1c95a6acac306d349d82c2d1fe91fcb739f09
95
TakeTicket
Apache License 2.0
HelloArchitectureRetrofit/app/src/main/java/dev/seabat/android/helloarchitectureretrofit/ui/pages/TopFragment.kt
seabat
636,759,391
false
null
package dev.seabat.android.helloarchitectureretrofit.ui.pages import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import dagger.hilt.android.AndroidEntryPoint import dev.seabat.android.helloarchitectureretrofit.R import dev.seabat.android.helloarchitectureretrofit.databinding.PageTopBinding import dev.seabat.android.helloarchitectureretrofit.ui.dialog.showSimpleErrorDialog @AndroidEntryPoint class TopFragment : Fragment(R.layout.page_top) { companion object { val TAG: String = TopFragment::class.java.simpleName } private var binding: PageTopBinding? = null private val viewModel: TopViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = PageTopBinding.bind(view) initView() initObserver() viewModel.loadRepositories() return } private fun initView() { binding?.recyclerview?.apply { layoutManager = LinearLayoutManager(requireContext()) val decoration = DividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL) addItemDecoration(decoration) adapter = RepositoryListAdapter() } } private fun initObserver() { viewModel.repositories.observe(viewLifecycleOwner) { (binding?.recyclerview?.adapter as RepositoryListAdapter)?.updateRepositoryList(it) } viewModel.progressVisible.observe(viewLifecycleOwner) { if(it) { binding?.progressbar?.visibility = View.VISIBLE } else { binding?.progressbar?.visibility = View.GONE } } viewModel.errorMessage.observe(viewLifecycleOwner) { if(it != null) { showSimpleErrorDialog( message = it, requestKey = TAG, requestBundle = bundleOf("errorMessage" to it), onClickCallback = { key, bundle -> if (key == TAG) { android.util.Log.d("Hello", "Error dialog closed(${bundle.getString("errorMessage")})") viewModel.clearError() } } ) } } } override fun onDestroyView() { super.onDestroyView() binding = null } }
0
Kotlin
0
0
c2c4f036825640aab138dcb14727eaf711308160
2,657
hello-architecture-retrofit
Apache License 2.0
app/src/main/kotlin/com/github/jbarr21/wearscreenshotsaver/MyFileProvider.kt
jbarr21
28,576,994
false
null
package com.github.jbarr21.wearscreenshotsaver import android.support.v4.content.FileProvider class MyFileProvider : FileProvider()
0
Kotlin
0
0
4193981829b87a7c98ee50f6f11bf7376a826046
134
WearScreenshotSaver
Apache License 2.0
src/test/kotlin/com/theapache64/automotion/core/VideoMergerTest.kt
theapache64
340,878,933
false
{"Kotlin": 92039, "Shell": 6177}
package com.theapache64.automotion.core import com.github.theapache64.expekt.should import org.junit.Test import java.io.File class VideoMergerTest { @Test fun testMergeVideoSuccess() { val lionVideo = File("lab/lion.mp4") val inputVideoDuration = FileUtils.getDuration(lionVideo) + FileUtils.getDuration(lionVideo) val inputVideos = listOf( lionVideo, lionVideo ) val outputVideo = VideoMerger.mergeVideo(inputVideos) val outputVideoLength = FileUtils.getDuration(outputVideo) kotlin.math.floor(inputVideoDuration).should.equal(kotlin.math.floor(outputVideoLength)) } @Test fun testMergeVideoDiffFormatFailure() { val lionVideo = File("lab/lion.mp4") val sharkVideo = File("lab/comma.mp4") val inputVideoDuration = FileUtils.getDuration(lionVideo) + FileUtils.getDuration(sharkVideo) val inputVideos = listOf( lionVideo, sharkVideo ) val outputVideo = VideoMerger.mergeVideo(inputVideos) val outputVideoLength = FileUtils.getDuration(outputVideo) kotlin.math.floor(inputVideoDuration).should.not.equal(kotlin.math.floor(outputVideoLength)) } }
0
Kotlin
1
4
ef27ec3a14818d6551b70edd98bc1976647b9a4b
1,248
auto-motion
Apache License 2.0
app/src/main/java/com/kyawhtut/test/adapter/viewholder/TableColumnHeaderViewHolder.kt
kyawhtut-cu
253,677,572
false
null
package com.kyawhtut.test.adapter.viewholder import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import com.evrencoskun.tableview.ITableView import com.evrencoskun.tableview.adapter.recyclerview.holder.AbstractSorterViewHolder import com.evrencoskun.tableview.sort.SortState import com.kyawhtut.test.R import com.kyawhtut.test.vo.TableColumnHeaderVO import kotlinx.android.synthetic.main.table_column_header_layout.view.* /** * @author kyawhtut * @date 07/04/2020 */ class TableColumnHeaderViewHolder(private val view: View, private val table: ITableView) : AbstractSorterViewHolder(view) { private val container: ConstraintLayout by lazy { view.column_header_container } private val tvCellData: TextView by lazy { view.column_header_textView } fun bind(data: TableColumnHeaderVO, columnPosition: Int) { tvCellData.apply { text = data.data } container.layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT container.maxWidth = 400 requestLayout() } private fun requestLayout() { tvCellData.requestLayout() container.requestLayout() view.requestLayout() } override fun setSelected(selectionState: SelectionState?) { super.setSelected(selectionState) container.setBackgroundColor( ContextCompat.getColor( view.context, when (selectionState) { SelectionState.SELECTED -> R.color.selected_background_color SelectionState.UNSELECTED -> R.color.unselected_background_color else -> R.color.unselected_background_color } ) ) tvCellData.setTextColor( ContextCompat.getColor( view.context, when (selectionState) { SelectionState.SELECTED -> R.color.colorBlack else -> R.color.colorBlack } ) ) } override fun onSortingStatusChanged(pSortState: SortState) { super.onSortingStatusChanged(pSortState) container.layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT controlSortState(pSortState) requestLayout() } private fun controlSortState(stortState: SortState) { /*btnSort.apply { visibility = View.GONE when (stortState) { SortState.ASCENDING -> { setImageResource(R.drawable.ic_arrow_drop_down_black) } SortState.DESCENDING -> { setImageResource(R.drawable.ic_arrow_drop_up_black) } else -> visibility = View.GONE } }*/ } }
0
Kotlin
1
2
2d74c1e819126b7c18f238411bbc5abffe3f9638
2,920
Sheet2Json
Apache License 2.0
zircon.jvm/src/main/kotlin/org/hexworks/zircon/api/StyleSets.kt
ahmedolaibrahim
147,102,847
true
{"Kotlin": 826245, "Java": 98220}
package org.hexworks.zircon.api import org.hexworks.zircon.api.builder.graphics.StyleSetBuilder import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.graphics.StyleSet object StyleSets { /** * Shorthand for the default style which is: * - default foreground color (white) * - default background color (black) * - no modifiers */ @JvmStatic fun defaultStyle() = StyleSet.defaultStyle() /** * Shorthand for the empty style which has: * - transparent foreground * - and transparent background * - and no modifiers. */ @JvmStatic fun empty() = newBuilder() .backgroundColor(TileColor.transparent()) .foregroundColor(TileColor.transparent()) .modifiers(setOf()) .build() /** * Creates a new [StyleSetBuilder] for creating [org.hexworks.zircon.api.graphics.StyleSet]s. */ @JvmStatic fun newBuilder() = StyleSetBuilder() }
0
Kotlin
0
0
1331f79a03d3c84e7888ab2aa9dd4f7c9338013d
990
zircon
MIT License
src/test/kotlin/com/aeolus/app/entrypoint/comparator/validator/ComparisonRequestValidatorTest.kt
team-aeolus
668,382,094
false
null
package com.aeolus.app.entrypoint.comparator.validator import com.aeolus.app.entrypoint.comparator.payload.ComparisonRequest import com.aeolus.core.common.exception.RequestValidationException import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.assertDoesNotThrow import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test class ComparisonRequestValidatorTest { private val validator: ComparisonRequestValidator = ComparisonRequestValidator() @Test fun `Given invalid data on object When process validation Then should throw exception`() { val request = buildRequest( location = "EU", timeUsed = 0, memory = 15, cpuCount = 5, operatingSystem = "MAC", providers = listOf("IBM"), offerType = "SPOT" ) val exception: RequestValidationException = assertThrows(RequestValidationException::class.java) { validator.processValidationsRules(request) } assertThat(exception) .isNotNull() .hasMessage("Data inconsistency") .extracting("errorCode.code", "errorCode.httpStatus") .containsExactly("ALS-SVC-998", 400) assertThat(exception.errors.map { it.message }) .usingRecursiveComparison() .isEqualTo(listOf( "The content of the field 'operatingSystem' should be [WINDOWS,LINUX] but it is [MAC]", "The content of the field 'location' should be [US] but it is [EU]", "The content of the field 'timeUsed' should be between '1' and '730' but it is '0'", "The content of the field 'providers' should be [AWS,AZURE,GCP] but it is [IBM]", "The content of the field 'offerType' should be [ONDEMAND,RESERVED] but it is [SPOT]" )) } @Test fun `Given empty data on object When process validation Then should throw exception`() { val request = buildRequest( timeUsed = null, location = null, memory = null, cpuCount = null, operatingSystem = null, providers = null ) val exception: RequestValidationException = assertThrows(RequestValidationException::class.java) { validator.processValidationsRules(request) } assertThat(exception) .isNotNull() .hasMessage("Data inconsistency") .extracting("errorCode.code", "errorCode.httpStatus") .containsExactly("ALS-SVC-998", 400) assertThat(exception.errors.map { it.message }) .usingRecursiveComparison() .isEqualTo(listOf( "The required field 'memory' is missing", "The required field 'cpuCount' is missing", "The required field 'operatingSystem' is missing", "The required field 'location' is missing", "The required field 'timeUsed' is missing", "The required field 'providers' is missing" )) } @Test fun `Given valid object When process validation Then should not throw exception`() { val request = buildRequest() assertDoesNotThrow { validator.processValidationsRules(request) } } private fun buildRequest(memory: Int? = 2, cpuCount: Int? = 2, operatingSystem: String? = "LINUX", location: String? = "US", timeUsed: Int? = 24, providers: List<String>? = listOf("AWS", "AZURE"), offerType: String = "RESERVED", ) = ComparisonRequest ( memory = memory, cpuCount = cpuCount, operatingSystem = operatingSystem, location = location, timeUsed = timeUsed, providers = providers, offerType = offerType ) }
0
Kotlin
0
0
be9bca77f166baa339962c6f3264beb164f91dfb
4,055
aeolus-service
MIT License
src/main/kotlin/network/commercio/sacco/models/types/StdSignatureMessage.kt
commercionetwork
206,345,711
false
null
package network.commercio.sacco.models.types import com.fasterxml.jackson.annotation.JsonProperty /** * Contains the data of a message signature. * More on this type can be found on the Cosmos.network official documentation at * https://cosmos.network/docs/spec/auth/03_types.html#stdsigndoc */ data class StdSignatureMessage( @JsonProperty("account_number") val accountNumber: Any, @JsonProperty("chain_id") val chainId: String, @JsonProperty("fee") val fee: StdFee, @JsonProperty("memo") val memo: String?, @JsonProperty("msgs") val msgs: List<StdMsg>, @JsonProperty("sequence") val sequence: Any )
1
Kotlin
5
4
473a86adcab2377ff607e0b732741bb7035a9d37
631
sacco.kt
Apache License 2.0
local/src/main/java/com/vlad1m1r/bltaxi/local/database/TaxiDao.kt
VladimirWrites
192,170,187
false
{"Kotlin": 150749, "HTML": 15579}
package com.vlad1m1r.bltaxi.local.database import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import androidx.room.Transaction import com.vlad1m1r.bltaxi.taxi.domain.Language @Dao interface TaxiDao { @Query("SELECT * FROM taxis WHERE language LIKE :language") fun getAll(language: Language): List<Taxi> @Insert fun insertAll(taxis: List<Taxi>) @Query("DELETE FROM taxis WHERE language LIKE :language") fun deleteAll(language: Language) @Transaction fun replaceAll(taxis: List<Taxi>, language: Language) { deleteAll(language) insertAll(taxis) } }
0
Kotlin
39
350
33b03dbdf4f7c2b7384ffa6259de52a813673c77
685
BLTaxi
Apache License 2.0
api/src/main/kotlin/io/github/wulkanowy/api/school/Teacher.kt
wulkanowy
145,134,008
false
null
package io.github.wulkanowy.api.school import com.google.gson.annotations.SerializedName data class Teacher( @SerializedName("Nauczyciel") val name: String, val short: String, @SerializedName("Nazwa") val subject: String )
0
Kotlin
1
12
3e8cdb8a27cdfcd734000d54c946f4b4e2002794
248
api
Apache License 2.0
src/main/kotlin/no/nav/su/person/sts/StsConsumer.kt
navikt
246,253,670
false
null
package no.nav.su.person.sts import com.github.kittinunf.fuel.core.extensions.authentication import com.github.kittinunf.fuel.httpGet import io.ktor.http.ContentType.Application.Json import io.ktor.http.HttpHeaders.Accept import no.nav.su.person.sts.StsToken.Companion.isValid import org.json.JSONObject import java.time.LocalDateTime class StsConsumer(private val baseUrl: String, private val username: String, private val password: String){ private var stsToken: StsToken? = null fun token(): String { if (!isValid(stsToken)) { val (_, _, result) = "$baseUrl/rest/v1/sts/token?grant_type=client_credentials&scope=openid".httpGet() .authentication().basic(username, password) .header(Accept, Json) .responseString() stsToken = result.fold( { StsToken(JSONObject(it)) }, { throw RuntimeException("Error while getting token from STS, message:${it.message}, error:${String(it.errorData)}") } ) } return stsToken?.accessToken!! } } data class StsToken( private val json: JSONObject ) { val accessToken: String = json.getString("access_token") private val expiresIn: Int = json.getInt("expires_in") private val expirationTime = LocalDateTime.now().plusSeconds(expiresIn - 20L) companion object { fun isValid(token: StsToken?): Boolean { return when (token) { null -> false else -> !isExpired(token) } } private fun isExpired(token: StsToken) = token.expirationTime.isBefore(LocalDateTime.now()) } }
0
Kotlin
0
0
53c33989f825f1a09191b14485f7f84ed0c0ed9c
1,594
su-person
MIT License
app/src/main/java/srimani7/apps/feedfly/navigation/FeedsScreen.kt
SriMani-7
664,648,685
false
{"Kotlin": 151018}
package srimani7.apps.feedfly.navigation import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import srimani7.apps.feedfly.R import srimani7.apps.feedfly.database.FeedDto import srimani7.apps.rssparser.DateParser @Composable fun FeedGroupList( groups: List<FeedDto>, state: LazyListState = rememberLazyListState(), onClick: (Long) -> Unit ) { LazyColumn( contentPadding = PaddingValues(top = 14.dp, bottom = 80.dp), verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxSize(), state = state ) { items(groups, key = {it.id}) { feedDto -> FeedCard(feedDto) { onClick(feedDto.id) } } } } @Composable fun FeedCard(feedDto: FeedDto, onClick: () -> Unit) { Surface( onClick = onClick, shape = RectangleShape, color = MaterialTheme.colorScheme.background, contentColor = MaterialTheme.colorScheme.onBackground, modifier = Modifier.fillMaxWidth(), ) { Column { Row( horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.padding(14.dp, 14.dp), ) { AsyncImage( model = feedDto.feedImageDto?.imageUrl, contentDescription = "image", contentScale = ContentScale.FillHeight, filterQuality = FilterQuality.Medium, alignment = Alignment.CenterStart, modifier = Modifier .size(42.dp) .background(Color.LightGray, CircleShape) .clip(CircleShape), placeholder = painterResource(R.drawable.rss_feed_24px), ) Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( text = feedDto.title, style = MaterialTheme.typography.titleSmall, maxLines = 2, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight.Medium, ) DateParser.formatDate(feedDto.lastBuildDate)?.let { Text( text = it, style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.Light, ) } } } Divider() } } }
0
Kotlin
0
1
ef215443c5ad18e28c3c95f71b8d227a5aee05e2
3,951
FeedFly
MIT License
app/src/main/java/com/alexsci/android/lambdarunner/ui/scan_qr/ScanQRActivity.kt
ralexander-phi
218,896,059
false
null
package com.alexsci.android.lambdarunner.ui.scan_qr import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.SparseArray import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.alexsci.android.lambdarunner.R import com.alexsci.android.lambdarunner.ui.add_key.dialogs.QRCodeHelpDialog import com.google.android.gms.vision.barcode.Barcode import com.google.gson.JsonParser import com.google.gson.JsonSyntaxException import info.androidhive.barcode.BarcodeReader class ScanQRActivity: AppCompatActivity(), BarcodeReader.BarcodeReaderListener { companion object { const val SCAN_REQUIREMENTS_EXTRA = "ScanRequirements" const val DETECTED_JSON_EXTRA = "DetectedJSON" const val DETECTED_ACCESS_KEY_ID = "AccessKeyId" const val DETECTED_SECRET_ACCESS_KEY = "SecretAccessKey" } enum class ScanRequirements { IS_AWS_CREDS, IS_JSON } private lateinit var barcodeReader: BarcodeReader private lateinit var scanRequirements: ScanRequirements override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scan_qr) setSupportActionBar(findViewById(R.id.toolbar)) scanRequirements = ScanRequirements.valueOf(intent.getStringExtra( SCAN_REQUIREMENTS_EXTRA)!!) when (scanRequirements) { ScanRequirements.IS_JSON -> supportActionBar?.title = "Scan JSON QR Code" ScanRequirements.IS_AWS_CREDS -> supportActionBar?.title = "Scan AWS Creds QR Code" } barcodeReader = supportFragmentManager.findFragmentById(R.id.barcode_fragment) as BarcodeReader } override fun onBitmapScanned(sparseArray: SparseArray<Barcode>?) {} override fun onScannedMultiple(barcodes: MutableList<Barcode>?) {} override fun onScanned(barcode: Barcode?) { val scannedText = barcode?.rawValue when (scanRequirements) { ScanRequirements.IS_AWS_CREDS -> { if (scannedText != null && scannedText.contains("\n")) { val parts = scannedText.split("\n") if (parts.size >= 2) { val ak = parts[0] val sec = parts[1] // https://docs.aws.amazon.com/IAM/latest/APIReference/API_AccessKey.html // Guess generously for Secret Key if (ak.length in 16..128 && sec.length > 5) { // Success! Send the credentials back val intent = Intent() intent.putExtra(DETECTED_ACCESS_KEY_ID, ak) intent.putExtra(DETECTED_SECRET_ACCESS_KEY, sec) setResult(Activity.RESULT_OK, intent) finish() return } } } runOnUiThread { QRCodeHelpDialog.showQRCodeHint(this) } } ScanRequirements.IS_JSON -> { try { JsonParser().parse(scannedText) // Success! Send the JSON back val intent = Intent() intent.putExtra(DETECTED_JSON_EXTRA, scannedText) setResult(Activity.RESULT_OK, intent) finish() return } catch (e: JsonSyntaxException) { runOnUiThread { Toast.makeText(applicationContext, "Found QR Code, but content is not JSON", Toast.LENGTH_SHORT).show() } } } } } override fun onCameraPermissionDenied() { Toast.makeText(applicationContext, "Camera permission was not granted", Toast.LENGTH_SHORT).show() } override fun onScanError(errorMessage: String?) { Toast.makeText(applicationContext, errorMessage, Toast.LENGTH_SHORT).show() } }
4
Kotlin
0
3
d74c85c7873668dda49305985c24ed7de926ed7a
4,112
android-aws-lambda-runner
MIT License
ok2curl/src/main/java/com/moczul/ok2curl/Header.kt
mrmike
43,089,983
false
null
package com.moczul.ok2curl data class Header(val name: String, val value: String)
3
Kotlin
30
393
26e2718b899322b5f75fce7f4166c4913b4eedc8
82
Ok2Curl
Apache License 2.0
app/src/main/java/dev/hadrosaur/videodecodeencodedemo/VideoHelpers/VideoMediaCodecVideoRenderer.kt
marcouberti
315,270,403
true
{"Kotlin": 100611}
/* * Copyright (c) 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.hadrosaur.videodecodeencodedemo.VideoHelpers import android.media.MediaCodec import android.media.MediaFormat import android.os.Build import androidx.annotation.Nullable import com.google.android.exoplayer2.Format import com.google.android.exoplayer2.PlaybackParameters import com.google.android.exoplayer2.mediacodec.MediaCodecSelector import com.google.android.exoplayer2.util.MediaClock import com.google.android.exoplayer2.video.MediaCodecVideoRenderer import dev.hadrosaur.videodecodeencodedemo.MainActivity import dev.hadrosaur.videodecodeencodedemo.MainActivity.Companion.LOG_EVERY_N_FRAMES import java.nio.ByteBuffer class VideoMediaCodecVideoRenderer(val mainActivity: MainActivity, val internalSurfaceTextureComponent: InternalSurfaceTextureComponent, enableDecoderFallback: Boolean, val streamNumber: Int, val minFps: Int = 1) : MediaCodecVideoRenderer(mainActivity, MediaCodecSelector.DEFAULT, 0, enableDecoderFallback, null, null, -1), MediaClock { var decodeCounter = 0 var startTime = 0L var droppedFrames = 0 var lastProcessedFrameUs = 0L var internalPlaybackParameters = PlaybackParameters(1f) /** * Keep track of dropped frames */ override fun dropOutputBuffer(codec: MediaCodec, index: Int, presentationTimeUs: Long) { droppedFrames++ mainActivity.updateLog("Dropped frame in surface 1. Total dropped: ${droppedFrames}") super.dropOutputBuffer(codec, index, presentationTimeUs) } /** * Override default decoding flags here */ override fun getMediaFormat(format: Format, codecMimeType: String, codecMaxValues: CodecMaxValues, codecOperatingRate: Float, deviceNeedsNoPostProcessWorkaround: Boolean, tunnelingAudioSessionId: Int): MediaFormat { // Get default mediaFormat val mediaFormat = super.getMediaFormat(format, codecMimeType, codecMaxValues, codecOperatingRate, deviceNeedsNoPostProcessWorkaround, tunnelingAudioSessionId) // This decoding flag removes the necessity to manually block the render pipeline. It only // works in Android 10 and greater // Prevent frames from being dropped // if (Build.VERSION.SDK_INT >= 29) { // mediaFormat.setInteger("allow-frame-drop", 0) //} return mediaFormat } /** * Use an internal MediaClock that renders as fast as possible, instead of in real-time */ override fun getMediaClock(): MediaClock? { return this } /** * If the render pipeline is free, returns true here. If a frame is already in flight, returns * false to wait and prevent frame drops. */ override fun processOutputBuffer( positionUs: Long, elapsedRealtimeUs: Long, codec: MediaCodec, buffer: ByteBuffer, bufferIndex: Int, bufferFlags: Int, bufferPresentationTimeUs: Long, isDecodeOnlyBuffer: Boolean, isLastBuffer: Boolean, format: Format ): Boolean { if (buffer == null) { return false } // Check the atomic lock to see if a frame can be rendered. If not, return false and wait if (internalSurfaceTextureComponent.renderer.frameLedger.shouldBlockRender()) { return false } return super.processOutputBuffer(positionUs, elapsedRealtimeUs, codec, buffer, bufferIndex, bufferFlags, bufferPresentationTimeUs, isDecodeOnlyBuffer, isLastBuffer, format) } /** * Adds some logging after each buffer processed to keep track of decode */ override fun onProcessedOutputBuffer(presentationTimeUs: Long) { if (startTime == 0L) { startTime = System.currentTimeMillis() } decodeCounter++ if (decodeCounter % LOG_EVERY_N_FRAMES == 0) { val currentFPS = decodeCounter / ((System.currentTimeMillis() - startTime) / 1000.0) val FPSString = String.format("%.2f", currentFPS) mainActivity.updateLog("Stream ${streamNumber}: ${FPSString}fps @frame $decodeCounter.") } lastProcessedFrameUs = presentationTimeUs super.onProcessedOutputBuffer(presentationTimeUs) } override fun shouldDropBuffersToKeyframe(earlyUs: Long, elapsedRealtimeUs: Long, isLastBuffer: Boolean): Boolean { return false } override fun shouldDropOutputBuffer(earlyUs: Long, elapsedRealtimeUs: Long, isLastBuffer: Boolean): Boolean { return false } // MediaClock implementation. Render as fast as possible: use last rendered frame + 1 as current // position. See: https://github.com/google/ExoPlayer/issues/3978#issuecomment-372709173 // Note: no frames should be dropped so minFps just makes sure clock advances far enough to // include the next frame. Too far is ok in this case. override fun getPositionUs(): Long { return lastProcessedFrameUs + ((1 / minFps) * 100000) } override fun getPlaybackParameters(): PlaybackParameters { return internalPlaybackParameters } // Note: this implementation actually ignores parameters like speed. override fun setPlaybackParameters(playbackParameters: PlaybackParameters) { internalPlaybackParameters = playbackParameters } }
0
null
0
0
b1ff58e2f24eb516dbd7d903f6df52dfb2275da7
5,952
video-decode-encode-demo
Apache License 2.0
library/modulon/src/main/java/modulon/layout/coordinator/behavior/OffsetBehavior.kt
huskcasaca
464,732,039
false
null
package modulon.layout.coordinator.behavior import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat open class OffsetBehavior<V : View> : CoordinatorLayout.Behavior<V>() { val topAndBottomOffset: Int get() = offsetHelper?.topAndBottomOffset ?: 0 val leftAndRightOffset: Int get() = offsetHelper?.leftAndRightOffset ?: 0 var isVerticalOffsetEnabled: Boolean get() = offsetHelper?.isVerticalOffsetEnabled ?: false set(verticalOffsetEnabled) { offsetHelper?.isVerticalOffsetEnabled = verticalOffsetEnabled } var isHorizontalOffsetEnabled: Boolean get() = offsetHelper?.isHorizontalOffsetEnabled ?: false set(horizontalOffsetEnabled) { offsetHelper?.isHorizontalOffsetEnabled = horizontalOffsetEnabled } private var offsetHelper: OffsetHelper? = null private var tempTopBottomOffset = 0 private var tempLeftRightOffset = 0 override fun onLayoutChild(parent: CoordinatorLayout, child: V, layoutDirection: Int): Boolean { // First let lay the child out layoutChild(parent, child, layoutDirection) if (offsetHelper == null) offsetHelper = OffsetHelper(child) offsetHelper?.onViewLayout() offsetHelper?.applyOffsets() if (tempTopBottomOffset != 0) { offsetHelper?.setTopAndBottomOffset(tempTopBottomOffset) tempTopBottomOffset = 0 } if (tempLeftRightOffset != 0) { offsetHelper?.setLeftAndRightOffset(tempLeftRightOffset) tempLeftRightOffset = 0 } return true } protected open fun layoutChild(parent: CoordinatorLayout, child: V, layoutDirection: Int) { // Let the parent lay it out by default parent.onLayoutChild(child, layoutDirection) } fun setTopAndBottomOffset(offset: Int): Boolean { // TODO: 27/12/2021 equals? // tempTopBottomOffset = if (offsetHelper != null) { // return offsetHelper!!.setTopAndBottomOffset(offset) // } else { // offset // } // return false return offsetHelper?.setTopAndBottomOffset(offset) ?: false.also { tempTopBottomOffset = offset } } fun setLeftAndRightOffset(offset: Int): Boolean { // tempLeftRightOffset = if (offsetHelper != null) { // return offsetHelper!!.setLeftAndRightOffset(offset) // } else { // offset // } // return false return offsetHelper?.setLeftAndRightOffset(offset) ?: false.also { tempTopBottomOffset = offset } } internal class OffsetHelper(private val view: View) { var layoutTop = 0 private set var layoutLeft = 0 private set var topAndBottomOffset = 0 private set var leftAndRightOffset = 0 private set var isVerticalOffsetEnabled = true var isHorizontalOffsetEnabled = true fun onViewLayout() { // Grab the original top and left layoutTop = view.top layoutLeft = view.left } fun applyOffsets() { ViewCompat.offsetTopAndBottom(view, topAndBottomOffset - (view.top - layoutTop)) ViewCompat.offsetLeftAndRight(view, leftAndRightOffset - (view.left - layoutLeft)) } /** * Set the top and bottom offset for this [OffsetHelper]'s view. * * @param offset the offset in px. * @return true if the offset has changed */ fun setTopAndBottomOffset(offset: Int): Boolean { if (isVerticalOffsetEnabled && topAndBottomOffset != offset) { topAndBottomOffset = offset applyOffsets() return true } return false } /** * Set the left and right offset for this [OffsetHelper]'s view. * * @param offset the offset in px. * @return true if the offset has changed */ fun setLeftAndRightOffset(offset: Int): Boolean { if (isHorizontalOffsetEnabled && leftAndRightOffset != offset) { leftAndRightOffset = offset applyOffsets() return true } return false } } }
0
Kotlin
4
5
2522ec7169a5fd295225caf936bae2edf09b157e
4,390
bitshares-oases-android
MIT License
src/main/kotlin/com/mirkoalicastro/mavenversionrefactor/xml/Extensions.kt
mirkoalicastro
315,396,544
false
null
@file:JvmName("Extensions") package com.mirkoalicastro.mavenversionrefactor.xml import com.intellij.psi.xml.XmlTag fun XmlTag.getChildTag(name: String) = children .filterIsInstance<XmlTag>() .firstOrNull { name.equals(it.name, ignoreCase = true) } val XmlTag.textValue get() = value.textElements.getOrNull(0)
0
Kotlin
1
2
df4ecb48ebacb4f55394d33aded510ea6e1a7bda
320
maven-version-refactor-plugin
Apache License 2.0
src/main/java/de/hpled/threadtostl/Main.kt
fwiecz
216,279,453
false
null
package de.hpled.threadtostl import javafx.application.Application import javafx.application.Platform import javafx.fxml.FXMLLoader import javafx.scene.Parent import javafx.scene.Scene import javafx.stage.Stage import java.util.* class Main : Application() { @Throws(Exception::class) override fun start(primaryStage: Stage) { val res = ResourceBundle.getBundle("strings") val root = FXMLLoader.load<Parent>(javaClass.getResource("/main.fxml"), res) primaryStage.apply { title = "Thread2STL" scene = Scene(root, 800.0, 600.0) minWidth = 400.0 minHeight = 300.0 show() } } companion object { @JvmStatic fun main(args: Array<String>) { launch(Main::class.java, *args) } } }
0
Kotlin
0
0
399513a45121e18967171d7ef794afd31914cef1
824
Thread2STL
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/inspectors/InntektsopplysningInspektør.kt
navikt
193,907,367
false
null
package no.nav.helse.inspectors import java.time.LocalDate import java.time.LocalDateTime import java.util.UUID import no.nav.helse.hendelser.Subsumsjon import no.nav.helse.person.inntekt.IkkeRapportert import no.nav.helse.person.inntekt.InntektsopplysningVisitor import no.nav.helse.person.inntekt.Infotrygd import no.nav.helse.person.inntekt.Inntektsmelding import no.nav.helse.person.inntekt.Inntektsopplysning import no.nav.helse.person.inntekt.Saksbehandler import no.nav.helse.person.inntekt.SkattSykepengegrunnlag import no.nav.helse.økonomi.Inntekt import no.nav.helse.økonomi.Inntekt.Companion.INGEN internal val Inntektsopplysning.inspektør get() = InntektsopplysningInspektør(this) internal class InntektsopplysningInspektør(inntektsopplysning: Inntektsopplysning) : InntektsopplysningVisitor { internal lateinit var beløp: Inntekt private set internal lateinit var hendelseId: UUID private set internal lateinit var tidsstempel: LocalDateTime private set internal var overstyrtInntekt: Inntektsopplysning? = null private set private var tilstand: Tilstand = Tilstand.FangeInntekt init { inntektsopplysning.accept(this) } override fun preVisitSaksbehandler( saksbehandler: Saksbehandler, id: UUID, dato: LocalDate, hendelseId: UUID, beløp: Inntekt, forklaring: String?, subsumsjon: Subsumsjon?, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, saksbehandler, beløp, hendelseId, tidsstempel) } override fun visitInntektsmelding( inntektsmelding: Inntektsmelding, id: UUID, dato: LocalDate, hendelseId: UUID, beløp: Inntekt, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, inntektsmelding, beløp, hendelseId, tidsstempel) } override fun visitIkkeRapportert( ikkeRapportert: IkkeRapportert, id: UUID, hendelseId: UUID, dato: LocalDate, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, ikkeRapportert, INGEN, hendelseId, tidsstempel) } override fun visitInfotrygd( infotrygd: Infotrygd, id: UUID, dato: LocalDate, hendelseId: UUID, beløp: Inntekt, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, infotrygd, beløp, hendelseId, tidsstempel) } override fun preVisitSkattSykepengegrunnlag( skattSykepengegrunnlag: SkattSykepengegrunnlag, id: UUID, hendelseId: UUID, dato: LocalDate, beløp: Inntekt, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, skattSykepengegrunnlag, beløp, hendelseId, tidsstempel) } private sealed interface Tilstand { fun lagreInntekt( inspektør: InntektsopplysningInspektør, inntektsopplysning: Inntektsopplysning, beløp: Inntekt, hendelseId: UUID, tidsstempel: LocalDateTime ) object FangeInntekt : Tilstand { override fun lagreInntekt( inspektør: InntektsopplysningInspektør, inntektsopplysning: Inntektsopplysning, beløp: Inntekt, hendelseId: UUID, tidsstempel: LocalDateTime ) { inspektør.beløp = beløp inspektør.hendelseId = hendelseId inspektør.tidsstempel = tidsstempel inspektør.tilstand = HarFangetInntekt } } object HarFangetInntekt : Tilstand { override fun lagreInntekt( inspektør: InntektsopplysningInspektør, inntektsopplysning: Inntektsopplysning, beløp: Inntekt, hendelseId: UUID, tidsstempel: LocalDateTime ) { inspektør.overstyrtInntekt = inntektsopplysning } } } }
2
null
7
5
2f940cad2bc6a756033a4e19edc5236a0648c971
4,044
helse-spleis
MIT License
sykepenger-model/src/test/kotlin/no/nav/helse/inspectors/InntektsopplysningInspektør.kt
navikt
193,907,367
false
null
package no.nav.helse.inspectors import java.time.LocalDate import java.time.LocalDateTime import java.util.UUID import no.nav.helse.hendelser.Subsumsjon import no.nav.helse.person.inntekt.IkkeRapportert import no.nav.helse.person.inntekt.InntektsopplysningVisitor import no.nav.helse.person.inntekt.Infotrygd import no.nav.helse.person.inntekt.Inntektsmelding import no.nav.helse.person.inntekt.Inntektsopplysning import no.nav.helse.person.inntekt.Saksbehandler import no.nav.helse.person.inntekt.SkattSykepengegrunnlag import no.nav.helse.økonomi.Inntekt import no.nav.helse.økonomi.Inntekt.Companion.INGEN internal val Inntektsopplysning.inspektør get() = InntektsopplysningInspektør(this) internal class InntektsopplysningInspektør(inntektsopplysning: Inntektsopplysning) : InntektsopplysningVisitor { internal lateinit var beløp: Inntekt private set internal lateinit var hendelseId: UUID private set internal lateinit var tidsstempel: LocalDateTime private set internal var overstyrtInntekt: Inntektsopplysning? = null private set private var tilstand: Tilstand = Tilstand.FangeInntekt init { inntektsopplysning.accept(this) } override fun preVisitSaksbehandler( saksbehandler: Saksbehandler, id: UUID, dato: LocalDate, hendelseId: UUID, beløp: Inntekt, forklaring: String?, subsumsjon: Subsumsjon?, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, saksbehandler, beløp, hendelseId, tidsstempel) } override fun visitInntektsmelding( inntektsmelding: Inntektsmelding, id: UUID, dato: LocalDate, hendelseId: UUID, beløp: Inntekt, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, inntektsmelding, beløp, hendelseId, tidsstempel) } override fun visitIkkeRapportert( ikkeRapportert: IkkeRapportert, id: UUID, hendelseId: UUID, dato: LocalDate, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, ikkeRapportert, INGEN, hendelseId, tidsstempel) } override fun visitInfotrygd( infotrygd: Infotrygd, id: UUID, dato: LocalDate, hendelseId: UUID, beløp: Inntekt, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, infotrygd, beløp, hendelseId, tidsstempel) } override fun preVisitSkattSykepengegrunnlag( skattSykepengegrunnlag: SkattSykepengegrunnlag, id: UUID, hendelseId: UUID, dato: LocalDate, beløp: Inntekt, tidsstempel: LocalDateTime ) { this.tilstand.lagreInntekt(this, skattSykepengegrunnlag, beløp, hendelseId, tidsstempel) } private sealed interface Tilstand { fun lagreInntekt( inspektør: InntektsopplysningInspektør, inntektsopplysning: Inntektsopplysning, beløp: Inntekt, hendelseId: UUID, tidsstempel: LocalDateTime ) object FangeInntekt : Tilstand { override fun lagreInntekt( inspektør: InntektsopplysningInspektør, inntektsopplysning: Inntektsopplysning, beløp: Inntekt, hendelseId: UUID, tidsstempel: LocalDateTime ) { inspektør.beløp = beløp inspektør.hendelseId = hendelseId inspektør.tidsstempel = tidsstempel inspektør.tilstand = HarFangetInntekt } } object HarFangetInntekt : Tilstand { override fun lagreInntekt( inspektør: InntektsopplysningInspektør, inntektsopplysning: Inntektsopplysning, beløp: Inntekt, hendelseId: UUID, tidsstempel: LocalDateTime ) { inspektør.overstyrtInntekt = inntektsopplysning } } } }
2
null
7
5
2f940cad2bc6a756033a4e19edc5236a0648c971
4,044
helse-spleis
MIT License
library/src/test/kotlin/me/proxer/library/internal/adapter/ConferenceAdapterTest.kt
proxer
43,981,937
false
{"Kotlin": 492567}
package me.proxer.library.internal.adapter import me.proxer.library.entity.messenger.Conference import me.proxer.library.internal.adapter.ConferenceAdapter.IntermediateConference import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test import java.util.Date /** * @author <NAME> */ class ConferenceAdapterTest { private val intermediateConferenceWithImage = IntermediateConference( id = "123", topic = "something", customTopic = "somethingElse", participantAmount = 13, isGroup = true, isRead = false, date = Date(123456L), unreadMessageAmount = 2, lastReadMessageId = "321", rawImage = "avatar:http://example.com/image.png" ) private val conferenceWithImage = Conference( id = "123", topic = "something", customTopic = "somethingElse", participantAmount = 13, image = "http://example.com/image.png", imageType = "avatar", isGroup = true, isRead = false, date = Date(123456L), unreadMessageAmount = 2, lastReadMessageId = "321" ) private val intermediateConferenceWithoutImage = intermediateConferenceWithImage.copy(rawImage = "") private val conferenceWithoutImage = conferenceWithImage.copy(image = "", imageType = "") private val adapter = ConferenceAdapter() @Test fun testFromJson() { adapter.fromJson(intermediateConferenceWithImage) shouldBeEqualTo conferenceWithImage } @Test fun testFromJsonWithoutImage() { adapter.fromJson(intermediateConferenceWithoutImage) shouldBeEqualTo conferenceWithoutImage } }
0
Kotlin
2
13
f55585b485c8eff6da944032690fe4de40a58e65
1,558
ProxerLibJava
MIT License
src/Main.kt
YUUSUKE18
302,576,707
false
null
fun main() { val hoge = false; val hogehoge = true; val hhh = (hoge == hogehoge); println(hhh) }
0
Kotlin
0
0
e7ffc486957a2b0ae905837b041a9076aff2a849
113
Kotlin_Project
MIT License
app/src/main/java/com/UMC/zipdabang/config/src/main/Home/Scrap/My_Scrapp.kt
TeamZipdabang-UMC
585,966,195
false
{"Kotlin": 1461828}
package com.UMC.zipdabang.config.src.main.Home.Scrap import java.io.Serializable data class My_Scrapp (var id : Int? ,var heart : Int?,var ImageUrl: String?, var title : String?) : Serializable
0
Kotlin
2
0
cbb8399ee418515d282de05876b33fc8de27aa70
199
Zipdabang-Frontend
The Unlicense
app/src/main/java/com/UMC/zipdabang/config/src/main/Home/Scrap/My_Scrapp.kt
TeamZipdabang-UMC
585,966,195
false
{"Kotlin": 1461828}
package com.UMC.zipdabang.config.src.main.Home.Scrap import java.io.Serializable data class My_Scrapp (var id : Int? ,var heart : Int?,var ImageUrl: String?, var title : String?) : Serializable
0
Kotlin
2
0
cbb8399ee418515d282de05876b33fc8de27aa70
199
Zipdabang-Frontend
The Unlicense
src/main/kotlin/com/github/kotlin_di/annotation_processor/dependencies/CommandWrapperNew.kt
Kotlin-DI
539,439,647
false
null
package com.github.kotlin_di.annotation_processor.dependencies import com.github.kotlin_di.annotation_processor.files.CommandWrapperFile import com.github.kotlin_di.annotation_processor.files.Files import com.github.kotlin_di.common.types.Dependency import com.google.devtools.ksp.symbol.KSFunctionDeclaration class CommandWrapperNew(private val container: Files) : Dependency<Pair<KSFunctionDeclaration, String>, CommandWrapperFile> { override fun invoke(args: Pair<KSFunctionDeclaration, String>): CommandWrapperFile { val (fn, name) = args return container.file("${fn.simpleName}Wrapper") { CommandWrapperFile(it, fn, name) } } }
0
Kotlin
0
0
06dc8bb9704397ee871d5f6f1a2a763c2e24b14e
660
annotation-processor
MIT License
ficbookApi/src/commonMain/kotlin/ru/blays/ficbookapi/api/CollectionsApi.kt
B1ays
710,470,973
false
{"Kotlin": 907460}
package ru.blays.ficbookapi.api import kotlinx.coroutines.coroutineScope import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import org.jsoup.Jsoup import ru.blays.ficbookapi.data.SectionWithQuery import ru.blays.ficbookapi.dataModels.* import ru.blays.ficbookapi.ficbookExtensions.ficbookUrl import ru.blays.ficbookapi.okHttpDsl.* import ru.blays.ficbookapi.parsers.CollectionListParser import ru.blays.ficbookapi.parsers.CollectionSortParamsParser import ru.blays.ficbookapi.parsers.checkPageButtonsExists import ru.blays.ficbookapi.result.ApiResult interface CollectionsApi { suspend fun getCollections(section: SectionWithQuery, page: Int): ApiResult<ListResult<CollectionModel>> suspend fun getCollectionSortParams(collectionID: String): ApiResult<CollectionSortParams> suspend fun getAvailableCollections(fanficID: String): ApiResult<AvailableCollectionsModel> suspend fun addToCollection(collectionID: String, fanficID: String): Boolean suspend fun removeFromCollection(collectionID: String, fanficID: String): Boolean } class CollectionsApiImpl( private val client: OkHttpClient ): CollectionsApi { private val collectionsListParser = CollectionListParser() private val collectionSortParamsParser = CollectionSortParamsParser() override suspend fun getCollections( section: SectionWithQuery, page: Int ): ApiResult<ListResult<CollectionModel>> = coroutineScope { return@coroutineScope try { val response = client.get( url = ficbookUrl { href(section.path) section.queryParameters?.let { queryParams(it) } page(page) } ) val body = response.body.stringOrThrow() val document = Jsoup.parse(body) val collections = collectionsListParser.parse(document) val pageButtons = checkPageButtonsExists(document) ApiResult.success( ListResult( list = collections, hasNextPage = pageButtons.hasNext ) ) } catch (e: Exception) { ApiResult.failure(e) } } override suspend fun getCollectionSortParams( collectionID: String ): ApiResult<CollectionSortParams> = coroutineScope { return@coroutineScope try { val response = client.get( url = ficbookUrl { href("collections/$collectionID") } ) val body: String = response.body.stringOrThrow() val document = Jsoup.parse(body) val result = collectionSortParamsParser.parse(document) ApiResult.success(result) } catch (e: Exception) { ApiResult.failure(e) } } override suspend fun getAvailableCollections( fanficID: String ): ApiResult<AvailableCollectionsModel> = coroutineScope { return@coroutineScope try { val response = client.post( body = formBody { add("fanficId", fanficID) }, url = ficbookUrl { href("ajax/collections/listforfanfic") } ) val body: String = response.body.stringOrThrow() val model: AvailableCollectionsModel = Json.decodeFromString(body) ApiResult.success(model) } catch (e: Exception) { ApiResult.failure(e) } } override suspend fun addToCollection( collectionID: String, fanficID: String ): Boolean = coroutineScope { return@coroutineScope try { val response = client.post( body = formBody { add("collection_id", collectionID) add("fanfic_id", fanficID) }, url = ficbookUrl { href("ajax/collections/addfanfic") } ) val body = response.body.stringOrThrow() val result: AjaxSimpleResult = Json.decodeFromString(body) result.result } catch (e: Exception) { e.printStackTrace() false } } override suspend fun removeFromCollection( collectionID: String, fanficID: String ): Boolean = coroutineScope { return@coroutineScope try { val response = client.post( body = formBody { add("collection_id", collectionID) add("fanfic_id", fanficID) add("action", "delete") }, url = ficbookUrl { href("ajax/collection") } ) val body = response.body.stringOrThrow() val result: AjaxSimpleResult = Json.decodeFromString(body) result.result } catch (e: Exception) { e.printStackTrace() false } } }
0
Kotlin
1
9
478a79286c952c7d1e001b4a0d9075e3fccd4f18
5,060
ficbook-reader
MIT License
composeApp/src/commonMain/kotlin/repository/SportEventRepository.kt
spoonofcode
829,948,208
false
{"Kotlin": 96677, "Swift": 621}
package repository import fakeData.getFakeSportEvents import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get import model.Profile import model.SportEvent class SportEventRepository( // val httpClient: HttpClient ) { // TODO #12 Connect with backend // suspend fun getProfile(): Profile { // val profile = httpClient // .get("http://$HOST:$PORT/profiles/1") // .body<List<Task>>() // return profile // } suspend fun getAll(): List<SportEvent> { return getFakeSportEvents() } }
11
Kotlin
0
0
5233af10246b1b0b1c268ec666afd70c21f80be9
588
dojo-pro
Apache License 2.0
core/src/main/kotlin/io/github/legion2/tosca_orchestrator/tosca/model/Csar.kt
Legion2
350,881,803
false
null
package io.github.legion2.tosca_orchestrator.tosca.model import com.fasterxml.jackson.module.kotlin.readValue import io.github.legion2.tosca_orchestrator.tosca.definitions.ServiceTemplateDefinition import io.github.legion2.tosca_orchestrator.tosca.definitions.toscaYamlMapper import java.io.InputStream import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.util.zip.ZipInputStream data class ToscaMetaFile( val metaFileVersion: String, val CsarVersion: String, val createdBy: String, val entryDefinitions: URI ) fun loadMetadata(csarBasePath: Path): ToscaMetaFile { val toscaMetaFile = csarBasePath.resolve("TOSCA-Metadata").resolve("TOSCA.meta") return if (Files.exists(toscaMetaFile)) { val lines = Files.readAllLines(toscaMetaFile).associate { it.substringBefore(": ") to it.substringAfter(": ") } val entryDefinitions = (lines["Entry-Definitions"] ?: throw IllegalArgumentException("Entry-Definitions not defined in TOSCA Meta File.")) val uri = csarBasePath.resolve(entryDefinitions).toUri() ToscaMetaFile( lines["TOSCA-Meta-File-Version"] ?: throw IllegalArgumentException("TOSCA-Meta-File-Version not defined in TOSCA Meta File."), lines["CSAR-Version"] ?: throw IllegalArgumentException("CSAR-Version not defined in TOSCA Meta File."), lines["Created-By"] ?: throw IllegalArgumentException("Created-By not defined in TOSCA Meta File."), uri ) } else { val yamlFile = Files.newDirectoryStream(csarBasePath, "*.{yaml,yml}").use { it.toList() }.single().toUri() val serviceTemplateDefinition = toscaYamlMapper.readValue<ServiceTemplateDefinition>(yamlFile.toURL()) val metadata = serviceTemplateDefinition.metadata.orEmpty() ToscaMetaFile( "1.1", metadata["template_version"] ?: throw IllegalArgumentException("template_version not defined in TOSCA Meta File."), metadata["template_author"] ?: throw IllegalArgumentException("template_author not defined in metadata."), yamlFile ) } } fun storeCsar(inputStream: InputStream): Path { val outputDir = Files.createTempDirectory("orchestration-upload-csar-") val zipInputStream = ZipInputStream(inputStream) zipInputStream.use { while (true) { val entry = it.nextEntry ?: break val outputFile = outputDir.resolve(entry.name).normalize() if (!outputFile.startsWith(outputDir)) { throw IllegalArgumentException("Entry is outside of the target dir: ${entry.name}") } if (entry.isDirectory) { Files.createDirectories(outputFile) } else { Files.copy(it, outputFile) } } } return outputDir }
6
Kotlin
0
3
fb4ef1a7bf3d79d258da2b6779381a87e0c435e9
2,943
ritam
Apache License 2.0
core/src/main/kotlin/io/github/legion2/tosca_orchestrator/tosca/model/Csar.kt
Legion2
350,881,803
false
null
package io.github.legion2.tosca_orchestrator.tosca.model import com.fasterxml.jackson.module.kotlin.readValue import io.github.legion2.tosca_orchestrator.tosca.definitions.ServiceTemplateDefinition import io.github.legion2.tosca_orchestrator.tosca.definitions.toscaYamlMapper import java.io.InputStream import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.util.zip.ZipInputStream data class ToscaMetaFile( val metaFileVersion: String, val CsarVersion: String, val createdBy: String, val entryDefinitions: URI ) fun loadMetadata(csarBasePath: Path): ToscaMetaFile { val toscaMetaFile = csarBasePath.resolve("TOSCA-Metadata").resolve("TOSCA.meta") return if (Files.exists(toscaMetaFile)) { val lines = Files.readAllLines(toscaMetaFile).associate { it.substringBefore(": ") to it.substringAfter(": ") } val entryDefinitions = (lines["Entry-Definitions"] ?: throw IllegalArgumentException("Entry-Definitions not defined in TOSCA Meta File.")) val uri = csarBasePath.resolve(entryDefinitions).toUri() ToscaMetaFile( lines["TOSCA-Meta-File-Version"] ?: throw IllegalArgumentException("TOSCA-Meta-File-Version not defined in TOSCA Meta File."), lines["CSAR-Version"] ?: throw IllegalArgumentException("CSAR-Version not defined in TOSCA Meta File."), lines["Created-By"] ?: throw IllegalArgumentException("Created-By not defined in TOSCA Meta File."), uri ) } else { val yamlFile = Files.newDirectoryStream(csarBasePath, "*.{yaml,yml}").use { it.toList() }.single().toUri() val serviceTemplateDefinition = toscaYamlMapper.readValue<ServiceTemplateDefinition>(yamlFile.toURL()) val metadata = serviceTemplateDefinition.metadata.orEmpty() ToscaMetaFile( "1.1", metadata["template_version"] ?: throw IllegalArgumentException("template_version not defined in TOSCA Meta File."), metadata["template_author"] ?: throw IllegalArgumentException("template_author not defined in metadata."), yamlFile ) } } fun storeCsar(inputStream: InputStream): Path { val outputDir = Files.createTempDirectory("orchestration-upload-csar-") val zipInputStream = ZipInputStream(inputStream) zipInputStream.use { while (true) { val entry = it.nextEntry ?: break val outputFile = outputDir.resolve(entry.name).normalize() if (!outputFile.startsWith(outputDir)) { throw IllegalArgumentException("Entry is outside of the target dir: ${entry.name}") } if (entry.isDirectory) { Files.createDirectories(outputFile) } else { Files.copy(it, outputFile) } } } return outputDir }
6
Kotlin
0
3
fb4ef1a7bf3d79d258da2b6779381a87e0c435e9
2,943
ritam
Apache License 2.0
utbot-python/src/main/kotlin/org/utbot/python/framework/codegen/model/PythonDomain.kt
UnitTestBot
480,810,501
false
null
package org.utbot.python.framework.codegen.model import org.utbot.framework.codegen.domain.TestFramework import org.utbot.framework.plugin.api.BuiltinClassId import org.utbot.framework.plugin.api.ClassId import org.utbot.framework.plugin.api.MethodId import org.utbot.framework.plugin.api.util.methodId import org.utbot.framework.plugin.api.util.objectClassId import org.utbot.framework.plugin.api.util.voidClassId import org.utbot.python.framework.api.python.PythonClassId import org.utbot.python.framework.api.python.util.pythonAnyClassId import org.utbot.python.framework.api.python.util.pythonNoneClassId object Pytest : TestFramework(displayName = "pytest", id = "pytest") { override val mainPackage: String = "pytest" override val assertionsClass: ClassId = pythonNoneClassId override val arraysAssertionsClass: ClassId = assertionsClass override val kotlinFailureAssertionsClass: ClassId = assertionsClass override val testAnnotation: String get() = TODO("Not yet implemented") override val testAnnotationId: ClassId = BuiltinClassId( canonicalName = "pytest", simpleName = "Tests" ) override val testAnnotationFqn: String = "" override val beforeMethod: String = "" override val beforeMethodId: ClassId = pythonAnyClassId override val beforeMethodFqn: String = "" override val afterMethod: String = "" override val afterMethodId: ClassId = pythonAnyClassId override val afterMethodFqn: String = "" override val parameterizedTestAnnotation: String = "" override val parameterizedTestAnnotationId: ClassId = pythonAnyClassId override val parameterizedTestAnnotationFqn: String = "" override val methodSourceAnnotation: String = "" override val methodSourceAnnotationId: ClassId = pythonAnyClassId override val methodSourceAnnotationFqn: String = "" override val nestedClassesShouldBeStatic: Boolean = false override val argListClassId: ClassId = pythonAnyClassId @OptIn(ExperimentalStdlibApi::class) override fun getRunTestsCommand( executionInvoke: String, classPath: String, classesNames: List<String>, buildDirectory: String, additionalArguments: List<String> ): List<String> = buildList { add(executionInvoke) addAll(additionalArguments) add(mainPackage) } } object Unittest : TestFramework(displayName = "Unittest", id = "Unittest") { init { isInstalled = true } override val testSuperClass: ClassId = PythonClassId("unittest.TestCase") override val mainPackage: String = "unittest" override val assertionsClass: ClassId = PythonClassId("self") override val arraysAssertionsClass: ClassId = assertionsClass override val kotlinFailureAssertionsClass: ClassId = assertionsClass override val testAnnotation: String = "" override val testAnnotationId: ClassId = BuiltinClassId( canonicalName = "Unittest", simpleName = "Tests" ) override val testAnnotationFqn: String = "unittest" override val beforeMethod: String = "" override val beforeMethodId: ClassId = pythonAnyClassId override val beforeMethodFqn: String = "" override val afterMethod: String = "" override val afterMethodId: ClassId = pythonAnyClassId override val afterMethodFqn: String = "" override val parameterizedTestAnnotation: String = "" override val parameterizedTestAnnotationId: ClassId = pythonAnyClassId override val parameterizedTestAnnotationFqn: String = "" override val methodSourceAnnotation: String = "" override val methodSourceAnnotationId: ClassId = pythonAnyClassId override val methodSourceAnnotationFqn: String = "" override val nestedClassesShouldBeStatic: Boolean = false override val argListClassId: ClassId = pythonAnyClassId override fun getRunTestsCommand( executionInvoke: String, classPath: String, classesNames: List<String>, buildDirectory: String, additionalArguments: List<String> ): List<String> { throw UnsupportedOperationException() } override val assertEquals by lazy { assertionId("assertEqual", objectClassId, objectClassId) } override fun assertionId(name: String, vararg params: ClassId): MethodId = methodId(assertionsClass, name, voidClassId, *params) }
337
Kotlin
25
70
d93fd5656645b55d3cece6eb13de8835bd0496d3
4,376
UTBotJava
Apache License 2.0
Learning English App/app/src/main/java/com/tnmd/learningenglishapp/screens/extension/ExtensionViewModel.kt
TranDatk
681,201,834
false
{"Kotlin": 316349}
package com.tnmd.learningenglishapp.screens.extension import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.viewModelScope import com.google.gson.Gson import com.tnmd.learningenglishapp.model.Edit import com.tnmd.learningenglishapp.model.EditResponse import com.tnmd.learningenglishapp.model.Schedule import com.tnmd.learningenglishapp.model.Words import com.tnmd.learningenglishapp.model.service.LogService import com.tnmd.learningenglishapp.model.service.ScheduleService import com.tnmd.learningenglishapp.model.service.WordsService import com.tnmd.learningenglishapp.screens.LearningEnglishAppViewModel import com.tnmd.learningenglishapp.screens.chatgpt.ApiService import com.tnmd.learningenglishapp.screens.chatgpt.OpenAIRequestBody import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import org.json.JSONObject import java.io.IOException import javax.inject.Inject @HiltViewModel class ExtensionViewModel @Inject constructor( private val wordsService: WordsService, logService: LogService, private val scheduleService: ScheduleService ) : LearningEnglishAppViewModel(logService) { private val _uiState = MutableStateFlow(ExtensionUiState()) val uiState: StateFlow<ExtensionUiState> = _uiState.asStateFlow() val words = mutableStateListOf<Words>() // Khai báo biến để lưu kết quả từ SAPLING API private val _editResponse = MutableStateFlow<EditResponse?>(null) val editResponse: StateFlow<EditResponse?> = _editResponse.asStateFlow() // MutableState để kiểm soát việc hiển thị hộp thoại lỗi private val _showErrorsDialog = mutableStateOf(false) val showErrorsDialog: State<Boolean> = _showErrorsDialog // Danh sách lỗi private val _errorList = mutableStateListOf<Edit>() val errorList: List<Edit> = _errorList // Biến để kiểm tra trạng thái xử lý private val _isLoading = mutableStateOf(false) val isLoading: State<Boolean> = _isLoading private val _imageAI = mutableStateOf<String?>(null) val imageAI: State<String?> = _imageAI init { launchCatching { scheduleService.schedule.collect { scheduleList -> newDayUserChoosen(scheduleList) } } loadData() } private fun newDayUserChoosen(scheduleList: List<Schedule>) { Log.d("checkScheduleScreen3", scheduleList.toString()) val updatedUiState = _uiState.value.copy(dayUserChoosen = scheduleList) _uiState.value = updatedUiState Log.d("checkScheduleScreen3", _uiState.value.dayUserChoosen.toString()) } // Hàm để đặt trạng thái xử lý private fun setIsLoading(loading: Boolean) { _isLoading.value = loading } fun showErrorsDialog(errors: List<Edit>) { // Cập nhật danh sách lỗi và hiển thị hộp thoại _errorList.clear() _errorList.addAll(errors) _showErrorsDialog.value = true } // Hàm để đóng hộp thoại lỗi fun closeErrorsDialog() { _showErrorsDialog.value = false } fun loadData() { _uiState.value = ExtensionUiState(currentPage = 0) } fun changeTab(tab: Int) { _uiState.update { currentState -> currentState.copy(currentPage = tab) } } fun updateUserCheckGrammar(string: String) { _uiState.update { currentState -> currentState.copy(userStringGues = string) } } fun submitUserStringToSapling() { val url = "https://api.sapling.ai/api/v1/edits" val key = "<KEY>" setIsLoading(true) val params = "{\"key\":\"$key\", \"text\":\" ${_uiState.value.userStringGues}\", \"session_id\":\"Test Document UUID\"}" println(params) val client = OkHttpClient() val requestBody = params.toRequestBody("application/json".toMediaTypeOrNull()) val request = Request.Builder() .url(url) .header("Content-Type", "application/json") .post(requestBody) .build() GlobalScope.launch(Dispatchers.IO) { try { val response = client.newCall(request).execute() if (!response.isSuccessful) { throw IOException("Unexpected code ${response.code}") } println("Server: ${response.header("Server")}") println("Date: ${response.header("Date")}") println("Vary: ${response.header("Vary")}") val responseBody = response.body?.string() if (!responseBody.isNullOrEmpty()) { // Chuyển đổi chuỗi JSON thành đối tượng Kotlin val gson = Gson() val editResponse = gson.fromJson(responseBody, EditResponse::class.java) // Lưu kết quả vào biến _editResponse _editResponse.value = editResponse // Đặt trạng thái xử lý là false khi hoàn thành xử lý setIsLoading(false) } else { // Xử lý trường hợp responseBody là null hoặc rỗng Log.d("responseBody", "Response body is null or empty") } } catch (e: Exception) { // Xử lý lỗi tại đây setIsLoading(false) e.printStackTrace() } } } val messages = mutableStateListOf<Message>() val isWaitingForResponse = mutableStateOf(false) fun sendMessage(text: String, isUser: Boolean = true) { messages.add(Message(text, "user")) if (isUser) { viewModelScope.launch { val response = ApiService.openAIApi.generateResponse(OpenAIRequestBody(messages = messages)) messages.add(response.choices.first().message) // Sau khi nhận được phản hồi, cập nhật isWaitingForResponse thành false isWaitingForResponse.value = false } } } fun wordsSearchChange(string: String) { _uiState.update { currentState -> currentState.copy( wordUserSearch = string, hasWordSearch = false, wordSearchResult = Words() ) } } fun searchSubmit() { Log.d("ExtensionViewModel", _uiState.value.wordUserSearch) var result = false try { setIsLoading(true) launchCatching { val foundWords = wordsService.findAWordsWithName(_uiState.value.wordUserSearch) _uiState.update { currentState -> val foundWords = wordsService.findAWordsWithName(_uiState.value.wordUserSearch) val updatedWordSearchResult = foundWords ?: Words() // Tạo một đối tượng Words mặc định nếu foundWords là null currentState.copy(wordSearchResult = updatedWordSearchResult) } } } catch (e: Exception) { // Xử lý lỗi ở đây e.printStackTrace() // Ví dụ: Hiển thị thông báo lỗi cho người dùng } finally { setIsLoading(false) } if (_uiState.value.wordSearchResult != null) { _uiState.update { currentState -> currentState.copy(hasWordSearch = true) } } Log.d("ExtensionViewModel", result.toString()) } fun updateEdit(isChecked: Boolean) { _uiState.update { currentState -> currentState.copy(isEditSchedule = isChecked) } } fun updateTempSchedule(schedule: Schedule){ _uiState.update { currentState -> currentState.copy(tempSchedule = schedule) } } fun updateDayUserChoosen(dateInput: String) { val dateExists = _uiState.value.dayUserChoosen.any { it.date == dateInput } if (dateExists == false) { Log.d("dateExists", dateExists.toString()) updateTempSchedule(Schedule(date = dateInput)) launchCatching { val id = scheduleService.newSchedule(_uiState.value.tempSchedule) // Tìm phần tử có date bằng dateInput và cập nhật id val updatedDayUserChoosen = _uiState.value.dayUserChoosen.map { if (it.date == dateInput) { it.copy(id = id) // Cập nhật id ở đây } else { it } } _uiState.update { currentState -> currentState.copy(dayUserChoosen = updatedDayUserChoosen) } } } else { updateTempSchedule(Schedule(date = dateInput)) val dateToRemove = _uiState.value.dayUserChoosen.firstOrNull { it.date.equals(dateInput) } Log.d("dateExists", dateToRemove.toString()) Log.d("dateExists", dateInput.toString() + " | check dateInput") Log.d("dateExists", _uiState.value.dayUserChoosen.toString() + " | check dateInput") if (dateToRemove != null) { Log.d("dateExists", dateToRemove.toString()) launchCatching { scheduleService.removeSchedule(dateToRemove) } } } Log.d("dateExists", dateExists.toString() + " - check") _uiState.update { currentState -> val currentList = currentState.dayUserChoosen val updatedList = if (currentList.any { it.date == dateInput }) { currentList.filterNot { it.date == dateInput } } else { currentList + Schedule(date = dateInput) } currentState.copy(dayUserChoosen = updatedList) } } fun textToImage(inputString: String) { _uiState.update { currentState -> currentState.copy(isOpenDialog = true) } _imageAI.value = null GlobalScope.launch(Dispatchers.IO) { try { val unsplashApiKey = "<KEY>" // Thay YOUR_UNSPLASH_API_KEY bằng API key của bạn val unsplashUrl = "https://api.unsplash.com/photos/random/?query=${inputString}&client_id=${unsplashApiKey}" val client = OkHttpClient() val request = Request.Builder() .url(unsplashUrl) .get() .build() val response = client.newCall(request).execute() if (response.isSuccessful) { val responseBody = response.body?.string() val json = JSONObject(responseBody) val imageUrl = json.getString("urls") val myImage = getFullImageUrl(imageUrl) withContext(Dispatchers.Main) { _imageAI.value = myImage } } else { withContext(Dispatchers.Main) {} } } catch (e: Exception) { withContext(Dispatchers.Main) {} } } } fun updateIsOpenDialog(){ _uiState.update { currentState -> currentState.copy(isOpenDialog = false) } } } data class Message(val content: String, val role: String) { val isUser: Boolean get() = role == "user" } fun getFullImageUrl(jsonString: String): String? { try { val jsonObject = JSONObject(jsonString) return jsonObject.optString("full") } catch (e: Exception) { e.printStackTrace() } return null }
0
Kotlin
0
1
f0da8a9bd2dcd7119fd4510bedf5c41c7df3bb8d
12,191
LearningEngishApplication
MIT License
feature/museum/src/main/java/com/hanbikan/nook/feature/museum/navigation/MuseumNavigation.kt
hanbikan
737,877,468
false
{"Kotlin": 237924}
package com.hanbikan.nook.feature.museum.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import com.hanbikan.nook.feature.museum.MonthlyCollectibleScreen import com.hanbikan.nook.feature.museum.MuseumScreen const val museumGraphRoute = "museum_graph_route" const val museumScreenRoute = "museum_screen_route" const val MONTHLY_COLLECTIBLE_SCREEN_ROUTE_BASE = "monthly_collectible_screen_route" const val COLLECTIBLE_INDEX_TO_SHOW = "collectibleIndexToShow" const val monthlyCollectibleScreenRoute = "$MONTHLY_COLLECTIBLE_SCREEN_ROUTE_BASE/{$COLLECTIBLE_INDEX_TO_SHOW}" fun NavGraphBuilder.museumGraph( navigateToAddUser: () -> Unit, navigateToPhone: () -> Unit, navigateToMonthlyCollectible: (Int) -> Unit, navigateUp: () -> Unit, ) { navigation( route = museumGraphRoute, startDestination = museumScreenRoute, ) { composable( route = museumScreenRoute, ) { MuseumScreen( navigateToAddUser = navigateToAddUser, navigateToPhone = navigateToPhone, navigateToMonthlyCollectible = navigateToMonthlyCollectible, ) } composable( route = monthlyCollectibleScreenRoute, arguments = listOf( navArgument(COLLECTIBLE_INDEX_TO_SHOW) { type = NavType.IntType } ) ) { MonthlyCollectibleScreen( navigateUp = navigateUp, ) } } } fun NavController.navigateToMuseum() { navigate(museumGraphRoute) } fun NavController.navigateToMonthlyCollectible(index: Int) { navigate("$MONTHLY_COLLECTIBLE_SCREEN_ROUTE_BASE/$index") }
0
Kotlin
0
0
5ba06d8fe64facf73add0956882cb6ab7cc87cc3
1,890
Nook
Apache License 2.0
app/src/main/java/com/breezefieldbluebarry/features/addAttendence/api/leavetytpeapi/LeaveTypeRepo.kt
DebashisINT
796,591,497
false
{"Kotlin": 14413602, "Java": 1021634}
package com.breezefieldbluebarry.features.addAttendence.api.leavetytpeapi import com.breezefieldbluebarry.app.Pref import com.breezefieldbluebarry.base.BaseResponse import com.breezefieldbluebarry.features.addAttendence.model.ApprovalLeaveResponseModel import com.breezefieldbluebarry.features.addAttendence.model.LeaveTypeResponseModel import com.breezefieldbluebarry.features.leaveapplynew.model.ApprovalRejectReqModel import com.breezefieldbluebarry.features.leaveapplynew.model.clearAttendanceonRejectReqModelRejectReqModel import io.reactivex.Observable /** * Created by Saikat on 22-11-2018. */ class LeaveTypeRepo(val apiService: LeaveTypeApi) { fun getLeaveTypeList(): Observable<LeaveTypeResponseModel> { return apiService.getLeaveTypeList(Pref.session_token!!, Pref.user_id!!) } fun getApprovalLeaveList(userId:String): Observable<ApprovalLeaveResponseModel> { return apiService.getApprovalLeaveList(Pref.session_token!!,userId) } fun postApprovalRejectclick(ApprovalRejectReqModel: ApprovalRejectReqModel): Observable<BaseResponse> { return apiService.postApprovalRejectclick(ApprovalRejectReqModel) } fun clearAttendanceonRejectclick(clearAttendanceonRejectReModel: clearAttendanceonRejectReqModelRejectReqModel): Observable<BaseResponse> { return apiService.clearAttendanceonRejectclick(clearAttendanceonRejectReModel) } }
0
Kotlin
0
0
b6c9ab260c1f9791fe80aaa1c70439f2fc6b2e3b
1,407
BlueBarrPaints
Apache License 2.0
app/src/main/java/ru/rznnike/eyehealthmanager/app/di/DatabaseModule.kt
RznNike
207,148,781
false
{"Kotlin": 903321}
package ru.rznnike.eyehealthmanager.app.di import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import ru.rznnike.eyehealthmanager.data.storage.dao.AcuityTestDAO import ru.rznnike.eyehealthmanager.data.storage.dao.AstigmatismTestDAO import ru.rznnike.eyehealthmanager.data.storage.dao.ColorPerceptionTestDAO import ru.rznnike.eyehealthmanager.data.storage.dao.ContrastTestDAO import ru.rznnike.eyehealthmanager.data.storage.dao.DaltonismTestDAO import ru.rznnike.eyehealthmanager.data.storage.dao.NearFarTestDAO import ru.rznnike.eyehealthmanager.data.storage.dao.TestDAO import ru.rznnike.eyehealthmanager.data.storage.entity.MyObjectBox import ru.rznnike.eyehealthmanager.domain.storage.repository.TestRepository import ru.rznnike.eyehealthmanager.data.storage.repository.TestRepositoryImpl val databaseModule = module { single { MyObjectBox.builder().androidContext(androidContext()).build() } single { TestDAO(get()) } single { AcuityTestDAO(get()) } single { AstigmatismTestDAO(get()) } single { ColorPerceptionTestDAO(get()) } single { ContrastTestDAO(get()) } single { DaltonismTestDAO(get()) } single { NearFarTestDAO(get()) } single<TestRepository> { TestRepositoryImpl(get(), get(), get(), get(), get(), get(), get(), get()) } }
0
Kotlin
1
5
95fad7c11297b63b6bc383bd66eff4b147e05b65
1,299
EyeHealthManager
MIT License
app/src/androidTest/java/dev/stenglein/connectivitycontroller/util/WaitForStateChangeUtil.kt
josteng
771,062,294
false
{"Kotlin": 55801}
package dev.stenglein.connectivitycontroller.util import kotlinx.coroutines.delay /** * Waits for a state change to occur. * @param stateProvider A function that returns the current state. * @param expectedState The state that is expected to be reached. * @param stepsToWait The number of steps to wait for the state change. * Default is 200 as managed Gradle devices tend to take a while to update * states, especially the network connectivity states. * @param timeMillisOneStep The time to wait between steps. * @return True if the expected state was reached, false otherwise. */ suspend fun waitForStateChange( stateProvider: () -> Boolean, expectedState: Boolean, stepsToWait: Int = 200, timeMillisOneStep: Long = 100 ): Boolean { for (i in 1..stepsToWait) { if (stateProvider() == expectedState) { return true } delay(timeMillisOneStep) } return false }
0
Kotlin
0
0
2e4bfa3686b7ea3fc37820a13b116241a77420c3
971
ConnectivityController
Apache License 2.0
Kotlin/Loops/sets.kt
starmut
359,206,380
true
{"C++": 23529, "JavaScript": 21234, "HTML": 20300, "Kotlin": 15781, "Python": 8762, "Java": 7972, "C#": 4659, "CSS": 4181, "Go": 1475, "PHP": 681}
fun main() { var set = setOf(3, 5, 7) for (i in set) { println("Number: $i") } for (i in set.indices) { // Gets the index println("Index $i is ${set.elementAt(i)}") // we use ${} for all /* Index 0 is 3 Index 1 is 5 Index 2 is 7 */ } }
0
C++
0
0
95a697034ae07d70850f0f7b9dd24d3eb599ee20
313
Notes
MIT License
demo/livemap/src/jsMain/kotlin/demo/livemap/demo/RasterTilesDemoJs.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package demo.livemap.demo @JsName("rasterTilesDemo") fun rasterTilesDemo() { DemoBaseJs(::RasterTilesDemoModel).show() }
102
Kotlin
50
1,164
61632186ef40d37ecb9292c56f8ae5fff1a24fd7
270
lets-plot
MIT License
app/src/main/java/com/javernaut/whatthecodec/presentation/root/ui/RootPagerAdapter.kt
YiChaoLove
326,980,408
false
null
package com.javernaut.whatthecodec.presentation.root.ui import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayoutMediator import com.javernaut.whatthecodec.R import com.javernaut.whatthecodec.presentation.audio.ui.AudioPageFragment import com.javernaut.whatthecodec.presentation.root.viewmodel.model.AvailableTab import com.javernaut.whatthecodec.presentation.stream.BasePageFragment import com.javernaut.whatthecodec.presentation.subtitle.ui.SubtitlePageFragment import com.javernaut.whatthecodec.presentation.video.ui.VideoPageFragment class RootPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) { var availableTabs: List<AvailableTab> = emptyList() set(value) { field = value notifyDataSetChanged() } override fun getItemId(position: Int): Long { return availableTabs[position].ordinal.toLong() } override fun containsItem(itemId: Long): Boolean { return availableTabs.contains( AvailableTab.values()[itemId.toInt()] ) } override fun getItemCount() = availableTabs.size override fun createFragment(position: Int): BasePageFragment { return when (availableTabs[position]) { AvailableTab.VIDEO -> VideoPageFragment() AvailableTab.AUDIO -> AudioPageFragment() AvailableTab.SUBTITLES -> SubtitlePageFragment() } } val tabConfigurationStrategy = TabLayoutMediator.TabConfigurationStrategy { tab, position -> tab.setText(when (availableTabs[position]) { AvailableTab.VIDEO -> R.string.tab_video AvailableTab.AUDIO -> R.string.tab_audio AvailableTab.SUBTITLES -> R.string.tab_subtitles }) } }
0
null
0
1
36904963fa5ddcefbe5c57d14c88ba856c91740b
1,839
WhatTheCodec
MIT License
src/main/kotlin/me/bisspector/kustom/event/CancellableEvent.kt
bisspector
430,742,578
false
{"Kotlin": 40324}
package me.bisspector.kustom.event interface CancellableEvent { var isCancelled: Boolean }
0
Kotlin
0
0
feda1834e2f310b1d710320ec18cd00157a06b68
95
kustom
MIT License
src/main/kotlin/dev/psiae/mltoolbox/composeui/AppLocals.kt
Psiae
874,299,111
false
{"Kotlin": 404098}
package dev.psiae.mltoolbox.composeui import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.window.ApplicationScope import dev.psiae.mltoolbox.app.MLToolBoxApp val LocalApplication = staticCompositionLocalOf<MLToolBoxApp> { compositionLocalNotProvidedError("LocalApplication") } val LocalComposeApplicationScope = staticCompositionLocalOf<ApplicationScope> { compositionLocalNotProvidedError("LocalComposeApplicationScope") }
0
Kotlin
0
1
3bb9280db9a1284befc091ec46a848b5780d8d6b
466
MLToolBox
Apache License 2.0
app/src/main/java/com/gmail/cities/domain/entity/ErrorState.kt
shtukar
280,606,502
false
null
package com.gmail.cities.domain.entity /** * A mapping from ErrorCode class. The set of params * supported by this class is purposefully restricted to the ones that can * be used on UI. * @property code the code of error * @property message a detailed message of the error */ class ErrorState(val code: Int, val message: String)
0
Kotlin
0
0
dcd976bba281e87f07af4934e7cc6425252e023d
338
Cities-list
Apache License 2.0
compiler/ir/backend.wasm/src/org/jetbrains/kotlin/backend/wasm/ir2wasm/WasmFunctionCodegenContext.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.wasm.ir2wasm import org.jetbrains.kotlin.backend.wasm.WasmBackendContext import org.jetbrains.kotlin.ir.IrFileEntry import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.expressions.IrLoop import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrReturnableBlockSymbol import org.jetbrains.kotlin.ir.symbols.IrValueParameterSymbol import org.jetbrains.kotlin.ir.symbols.IrValueSymbol import org.jetbrains.kotlin.ir.util.fileEntry import org.jetbrains.kotlin.wasm.ir.* import java.util.LinkedList enum class LoopLabelType { BREAK, CONTINUE } enum class SyntheticLocalType { IS_INTERFACE_PARAMETER, TABLE_SWITCH_SELECTOR } class WasmFunctionCodegenContext( val irFunction: IrFunction?, private val wasmFunction: WasmFunction.Defined, private val backendContext: WasmBackendContext, private val wasmFileCodegenContext: WasmFileCodegenContext, private val wasmModuleTypeTransformer: WasmModuleTypeTransformer, ) { val bodyGen: WasmExpressionBuilder = WasmExpressionBuilder(wasmFunction.instructions) private val wasmLocals = LinkedHashMap<IrValueSymbol, WasmLocal>() private val wasmSyntheticLocals = LinkedHashMap<SyntheticLocalType, WasmLocal>() private val loopLevels = LinkedHashMap<Pair<IrLoop, LoopLabelType>, Int>() private val nonLocalReturnLevels = LinkedHashMap<IrReturnableBlockSymbol, Int>() data class InlineContext(val inlineFunctionSymbol: IrFunctionSymbol?, val irFileEntry: IrFileEntry) private val inlineContextStack = LinkedList<InlineContext>() fun defineLocal(irValueDeclaration: IrValueSymbol) { assert(irValueDeclaration !in wasmLocals) { "Redefinition of local" } val owner = irValueDeclaration.owner val wasmLocal = WasmLocal( wasmFunction.locals.size, owner.name.asString(), if (owner is IrValueParameter) wasmModuleTypeTransformer.transformValueParameterType(owner) else wasmModuleTypeTransformer.transformType(owner.type), isParameter = irValueDeclaration is IrValueParameterSymbol ) wasmLocals[irValueDeclaration] = wasmLocal wasmFunction.locals += wasmLocal } fun defineTmpVariable(type: WasmType): Int { val wasmLocal = WasmLocal(wasmFunction.locals.size, "tmp", type, false) wasmFunction.locals += wasmLocal return wasmLocal.id } fun referenceLocal(irValueDeclaration: IrValueSymbol): WasmLocal { return wasmLocals.getValue(irValueDeclaration) } fun referenceLocal(index: Int): WasmLocal { return wasmFunction.locals[index] } private val SyntheticLocalType.wasmType get() = when (this) { SyntheticLocalType.IS_INTERFACE_PARAMETER -> WasmRefNullType(WasmHeapType.Type(wasmFileCodegenContext.referenceGcType(backendContext.irBuiltIns.anyClass))) SyntheticLocalType.TABLE_SWITCH_SELECTOR -> WasmI32 } fun referenceLocal(type: SyntheticLocalType): WasmLocal = wasmSyntheticLocals.getOrPut(type) { WasmLocal( wasmFunction.locals.size, type.name, type.wasmType, isParameter = false ).also { wasmFunction.locals += it } } fun defineNonLocalReturnLevel(block: IrReturnableBlockSymbol, level: Int) { nonLocalReturnLevels[block] = level } fun referenceNonLocalReturnLevel(block: IrReturnableBlockSymbol): Int { return nonLocalReturnLevels.getValue(block) } fun defineLoopLevel(irLoop: IrLoop, labelType: LoopLabelType, level: Int) { val loopKey = Pair(irLoop, labelType) assert(loopKey !in loopLevels) { "Redefinition of loop" } loopLevels[loopKey] = level } fun referenceLoopLevel(irLoop: IrLoop, labelType: LoopLabelType): Int { return loopLevels.getValue(Pair(irLoop, labelType)) } val currentFunctionSymbol: IrFunctionSymbol? get() = inlineContextStack.firstOrNull()?.inlineFunctionSymbol ?: irFunction?.symbol val currentFileEntry: IrFileEntry? get() = inlineContextStack.firstOrNull()?.irFileEntry ?: irFunction?.fileEntry fun stepIntoInlinedFunction(inlineFunctionSymbol: IrFunctionSymbol?, irFileEntry: IrFileEntry) { inlineContextStack.push(InlineContext(inlineFunctionSymbol, irFileEntry)) } fun stepOutLastInlinedFunction() { inlineContextStack.pop() } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
4,795
kotlin
Apache License 2.0
app/src/main/java/com/jerryhanks/farimoneytest/utils/CoroutinesDispatcherProvider.kt
meshramaravind
568,037,548
false
null
package com.arvind.picsumphotoapp.utils import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import javax.inject.Inject data class CoroutinesDispatcherProvider( val main: CoroutineDispatcher, val computation: CoroutineDispatcher, val io: CoroutineDispatcher ) { @Inject constructor() : this(Dispatchers.Main, Dispatchers.Default, Dispatchers.IO) }
0
Kotlin
0
1
7d277f6b002b464afde4c8d415870e65c6f9ed28
402
fairmoney_test
MIT License
app/src/main/java/com/jtmcn/archwiki/viewer/data/WikiPage.kt
kevinhinterlong
5,917,675
false
{"Kotlin": 28909, "CSS": 22962, "Java": 4425}
package com.jtmcn.archwiki.viewer.data /** * Wrapper for a downloaded wiki page which holds the title and html. */ data class WikiPage(val pageUrl: String, val pageTitle: String?, val htmlString: String) { var scrollPosition = 0 }
12
Kotlin
12
73
7a9a1c96ec0f33adc46231c3f95c586173361a5d
238
archwiki-viewer
Apache License 2.0
app/src/main/java/com/jetpack/compose/github/github/cruise/ui/shared/extension/SharedExt.kt
dinkar1708
799,420,610
false
{"Kotlin": 115920}
package com.jetpack.compose.github.github.cruise.ui.shared.extension import android.content.Context import android.content.Intent import android.net.Uri import timber.log.Timber /** * Created by <NAME> on 2024/05/14. */ // TODO keep for future fun Context.openUrlInBrowser(stringUrl: String) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(stringUrl)) startActivity(intent) } catch (e: Exception) { Timber.e(e) } }
0
Kotlin
0
0
e750408dfef4963368453ae5637020968c58566a
465
GithubCruise
Apache License 2.0
QuickUtil/src/main/java/com/wpf/app/quickutil/helper/ActivityUtils.kt
walgr
487,438,913
false
{"Kotlin": 831704, "Shell": 865}
package com.wpf.app.quickutil.helper import android.app.Activity import android.view.View import android.view.ViewGroup import android.view.Window import androidx.core.view.get import com.wpf.app.quickutil.helper.generic.forceTo /** * Created by 王朋飞 on 2022/6/15. */ fun Activity.contentView(): View { return findViewById(android.R.id.content) } fun Window.contentView(): View? { return this.decorView.findViewById(android.R.id.content) } fun Activity.myContentView(): View { return findViewById<ViewGroup>(android.R.id.content)[0] } fun View.activity(): Activity = context as Activity inline fun <reified T : Activity> View.activityForce(): T = context.forceTo<T>()
0
Kotlin
3
29
6b4da7f07e347ca6d4fbaa7a555ebcedde1494d6
686
Quick
MIT License
ffs-server/src/main/kotlin/Application.kt
goncalossilva
413,381,047
false
{"Kotlin": 199452, "JavaScript": 548, "Shell": 380, "HTML": 190}
package doist.ffs import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver import doist.ffs.auth.AuthorizationException import doist.ffs.auth.Permission import doist.ffs.auth.Session import doist.ffs.auth.TokenPrincipal import doist.ffs.auth.UserPrincipal import doist.ffs.auth.bearer import doist.ffs.auth.permissions import doist.ffs.db.fromToken import doist.ffs.db.roles import doist.ffs.db.tokens import doist.ffs.plugins.Database import doist.ffs.plugins.database import doist.ffs.routes.PATH_LOGIN import doist.ffs.routes.PATH_USERS import doist.ffs.routes.installFlagRoutes import doist.ffs.routes.installOrganizationRoutes import doist.ffs.routes.installProjectRoutes import doist.ffs.routes.installUserRoutes import doist.ffs.serialization.cbor import doist.ffs.serialization.json import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.serialization.kotlinx.serialization import io.ktor.server.application.Application import io.ktor.server.application.install import io.ktor.server.auth.Authentication import io.ktor.server.auth.session import io.ktor.server.cio.EngineMain import io.ktor.server.plugins.CallLogging import io.ktor.server.plugins.Compression import io.ktor.server.plugins.ContentNegotiation import io.ktor.server.plugins.DefaultHeaders import io.ktor.server.plugins.StatusPages import io.ktor.server.response.respond import io.ktor.server.sessions.Sessions import io.ktor.server.sessions.cookie import routes.installTokenRoutes fun main(args: Array<String>): Unit = EngineMain.main(args) fun Application.module() { installPlugins() installRoutes() } fun Application.installPlugins() { install(Database) { driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) } install(CallLogging) install(DefaultHeaders) install(ContentNegotiation) { serialization(ContentType.Application.Json, json) serialization(ContentType.Application.Cbor, cbor) } install(Compression) install(Sessions) { cookie<Session>("session") } install(Authentication) { session<Session>("session") { validate { (id) -> val userRoles = database.roles.selectOrganizationIdProjectIdByUser( user_id = id ).executeAsList() return@validate UserPrincipal( id = id, organizationPermissions = userRoles.associate { it.id to it.role.permissions }, projectPermissions = userRoles.filter { it.project_id != null }.associate { it.project_id!! to it.role.permissions } ) } challenge("$PATH_USERS$PATH_LOGIN") } bearer("token") { validate { credential -> val token = credential.token val id = database.tokens.selectProjectIdByToken(token).executeAsOneOrNull() if (id != null) { return@validate TokenPrincipal( projectId = id, permission = Permission.fromToken(token) ) } return@validate null } } } install(StatusPages) { exception<AuthorizationException> { call, _ -> call.respond(HttpStatusCode.Forbidden) } exception<IllegalArgumentException> { call, _ -> call.respond(HttpStatusCode.BadRequest) } } } fun Application.installRoutes() { installUserRoutes() installOrganizationRoutes() installProjectRoutes() installFlagRoutes() installTokenRoutes() }
0
Kotlin
0
0
7c97b38ae56c5b28e5f48b8ea90e2b449f909449
3,768
ffs
MIT License
openrndr-animatable/src/main/kotlin/org/openrndr/animatable/AnimationKey.kt
shi-weili
237,852,942
false
null
package org.openrndr.animatable import org.openrndr.animatable.easing.Easing /** * Animation key class * @author <NAME> */ class AnimationKey(val variable: String, val target: Double, val duration: Long, var start: Long) { var from: Double = 0.toDouble() var message: Any? = null var stage: String? = null /** * returns all completion callbacks for the animation * @return a list containing completion callbacks */ var completionCallbacks = mutableListOf<(Animatable)->Unit>() var animationState = AnimationState.Queued private set var animationMode = AnimationMode.Blend /** * returns the easing mode * @return the easing mode used */ /** * sets the easing mode for the animation * @param easer the easing mode */ var easing = Easing.None.easer enum class AnimationMode { Blend, Additive } enum class AnimationState { Queued, Playing, Stopped } /** * plays the animation * @param from the current value of the variable to animate */ fun play(from: Double) { this.from = from animationState = AnimationState.Playing } /** * stops the animation */ fun stop() { animationState = AnimationState.Stopped } /** * adds a completion callback that is called when the animation ends * @param callback the callback to be executed */ fun addCompletionCallback(callback: (Animatable)->Unit) { completionCallbacks.add(callback) } val durationSeconds get() = duration / 1E6 }
0
null
0
1
2b69f8dd818e36106bf76862fff171dc2ae73e3a
1,641
openrndr
BSD 2-Clause with views sentence
app/src/main/java/com/example/expensetrack/ui/screens/login/LoginState.kt
mar19a
765,065,136
false
{"Kotlin": 106064}
package com.example.expensetrack.ui.screens.login import com.example.expensetrack.ui.domain.MutableObservableState class LoginState { val username = MutableObservableState<String?, String?, String>( initial = null, update = { it, _ -> it }, output = { it ?: "" } ) val password = MutableObservableState<String?, String?, String>( initial = null, update = { it, _ -> it }, output = { it ?: "" } ) }
0
Kotlin
0
0
40cd01a3da2f6b741fcf5de9dc3a99ba48940b1a
465
Expensetrack
MIT License