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/bejussi/shopply/domain/use_case/item/EditItemUseCase.kt | Bejussi | 526,253,133 | false | null | package com.bejussi.shopply.domain.use_case.item
import com.bejussi.shopply.domain.model.Item
import com.bejussi.shopply.domain.repository.ItemRepository
class EditItemUseCase(private val itemRepository: ItemRepository) {
suspend operator fun invoke(item: Item) {
itemRepository.editItem(item)
}
} | 0 | Kotlin | 0 | 0 | ee684a52787ae6e695fb73f783a9d2a2ee831fce | 316 | Shopply | MIT License |
server/engine/src/main/kotlin/io/rsbox/server/engine/model/ui/old/GameInterface.kt | Blunkie | 704,702,007 | false | {"INI": 3, "Gradle Kotlin DSL": 14, "Shell": 1, "Java Properties": 1, "Git Attributes": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Kotlin": 122, "Java": 546, "XML": 5} | package io.rsbox.server.engine.model.ui.old
import io.rsbox.server.cache.GameCache
import io.rsbox.server.cache.config.EnumConfig
import io.rsbox.server.common.inject
import io.rsbox.server.engine.model.ui.DisplayMode
import io.rsbox.server.engine.model.ui.InterfaceType
enum class GameInterface(val interfaceId: Int, val resizableChildId: Int, val type: InterfaceType = InterfaceType.OVERLAY) {
CHAT_BOX(interfaceId = 162, resizableChildId = 94, type = InterfaceType.OVERLAY),
PRIVATE_CHAT(interfaceId = 163, resizableChildId = 91, type = InterfaceType.OVERLAY),
MINI_MAP(interfaceId = 160, resizableChildId = 32, type = InterfaceType.OVERLAY),
XP_TRACKER(interfaceId = 122, resizableChildId = 1, type = InterfaceType.OVERLAY),
SKILLS(interfaceId = 320, resizableChildId = 76, type = InterfaceType.OVERLAY),
QUESTS(interfaceId = 629, resizableChildId = 77, type = InterfaceType.OVERLAY),
INVENTORY(interfaceId = 149, resizableChildId = 78, type = InterfaceType.OVERLAY),
EQUIPMENT(interfaceId = 387, resizableChildId = 79, type = InterfaceType.OVERLAY),
PRAYER(interfaceId = 541, resizableChildId = 80, type = InterfaceType.OVERLAY),
SPELL_BOOK(interfaceId = 218, resizableChildId = 81, type = InterfaceType.OVERLAY),
ACCOUNT(interfaceId = 109, resizableChildId = 83, type = InterfaceType.OVERLAY),
SOCIAL(interfaceId = 429, resizableChildId = 84, type = InterfaceType.OVERLAY),
LOG_OUT(interfaceId = 182, resizableChildId = 85, type = InterfaceType.OVERLAY),
SETTINGS(interfaceId = 116, resizableChildId = 86, type = InterfaceType.OVERLAY),
EMOTES(interfaceId = 216, resizableChildId = 87, type = InterfaceType.OVERLAY),
MUSIC(interfaceId = 239, resizableChildId = 88, type = InterfaceType.OVERLAY),
CLANS(interfaceId = 707, resizableChildId = 82, type = InterfaceType.OVERLAY),
COMBAT(interfaceId = 593, resizableChildId = 75, type = InterfaceType.OVERLAY);
private val cache: GameCache by inject()
@Suppress("UNCHECKED_CAST")
fun getEnumChildId(displayMode: DisplayMode): Int {
val mappings = cache.configArchive.enums[displayMode.enumId]!!.entryMap as Map<EnumConfig.Component, EnumConfig.Component>
return mappings[EnumConfig.Component(DisplayMode.RESIZABLE.interfaceId, resizableChildId)]?.child ?: throw IllegalArgumentException("Child id not found in enum.")
}
companion object {
private val cache: GameCache by inject()
private val values = values()
@Suppress("UNCHECKED_CAST")
fun fromEnumChildId(childId: Int, displayMode: DisplayMode): GameInterface? {
val mappings = cache.configArchive.enums[displayMode.enumId]!!.entryMap
.mapValues { it.key } as Map<EnumConfig.Component, EnumConfig.Component>
val resizableChildId = mappings[EnumConfig.Component(displayMode.interfaceId, childId)]?.child ?: return null
return values.firstOrNull { it.resizableChildId == resizableChildId }
}
}
} | 1 | null | 1 | 1 | 58d6086e3318170a069c9a4985d06e068b853535 | 3,008 | rsbox | Apache License 2.0 |
src/main/java/delta/module/modules/AntiRegear.kt | Robthekilla | 468,822,114 | true | {"INI": 2, "Gradle": 2, "Shell": 1, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Java": 81, "Kotlin": 20, "JSON": 2, "HAProxy": 1, "YAML": 1} | package delta.module.modules
import delta.DeltaCore
import delta.module.Category
import delta.module.Module
import delta.setting.Setting
import delta.util.BlockUtils
import delta.util.InventoryUtils
import delta.util.PlayerUtils
import delta.util.rotation.RotationUtil
import net.minecraft.init.Items
import net.minecraft.util.math.Vec3d
class AntiRegear: Module("Anti Regear", "shulker breaking simulator", Category.COMBAT){
private val range: Setting = setting("Range", 6.0, 0.1, 6.0, false)
private val switch: Setting = setting("Switch", true)
private val silent: Setting = setting("Silent", true)
private val rotate: Setting = setting("Rotate", true)
override fun onEnable() {
if (fullNullCheck()) return;
for (pos in BlockUtils.getSphere(PlayerUtils.getPlayerPos(mc.player), range.dVal.toFloat(), range.dVal.toInt(), false, true, 0)) {
if (BlockUtils.isShulkerBox(mc.world.getBlockState(pos).block)) {
if (rotate.bVal) {
DeltaCore.rotationManager.setYaw(RotationUtil.getRotations(Vec3d(pos))[0])
DeltaCore.rotationManager.setPitch(RotationUtil.getRotations(Vec3d(pos))[1])
DeltaCore.rotationManager.setRotate(true)
}
val oldSlot = mc.player.inventory.currentItem
BlockUtils.doPacketMine(pos)
if (switch.bVal) {
InventoryUtils.switchToItem(Items.DIAMOND_PICKAXE, silent.bVal)
}
if (silent.bVal) {
InventoryUtils.switchToSlot(oldSlot, silent.bVal)
}
if (rotate.bVal) {
DeltaCore.rotationManager.restoreRotations()
}
}
}
toggle()
}
} | 0 | null | 0 | 0 | 514ba77834cfe41aaed890b72db3a9a5bbc05d00 | 1,799 | delta | MIT License |
src/main/kotlin/dev/patbeagan/ui/ComposeMenu.kt | patbeagan1 | 503,169,434 | false | null | package dev.patbeagan.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun ComposeMenu(options: List<String>, selectedIndex: Int, setSelectedIndex: (Int) -> Unit) {
val expanded = remember { mutableStateOf(false) }
Column {
Button(
modifier = Modifier.wrapContentWidth(),
border = BorderStroke(width = 1.dp, color = Color.Red),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
onClick = { expanded.value = !expanded.value },
content = { Text(options[selectedIndex]) }
)
DropdownMenu(
expanded = expanded.value,
onDismissRequest = { expanded.value = !expanded.value },
modifier = Modifier.background(Color.White)
.border(BorderStroke(width = 1.dp, color = Color.DarkGray))
.padding(2.dp)
.shadow(elevation = 2.dp)
.width(200.dp),
) {
options.forEachIndexed { index, s ->
DropdownMenuItem(onClick = {
setSelectedIndex(index)
expanded.value = false
}) {
Text(text = s)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 9f10e7e5a0480748ab5eab8f08eb470e0bd5c0ae | 2,055 | AggronRssReader | MIT License |
app/src/main/java/com/anthony/net/sample/github/data/remote/service/user_info/UserInfoService.kt | WuBingHui | 575,667,484 | false | {"Kotlin": 95419} | package com.anthony.net.sample.github.data.remote.service.user_info
import com.anthony.net.sample.github.data.remote.model.login.RepositoryDto
import retrofit2.http.GET
import retrofit2.http.Path
// 用戶資訊服務介面
interface UserInfoService {
// 使用GET方式訪問"users/{userName}/repos"路徑,獲取指定用戶的倉庫清單
@GET("users/{userName}/repos")
suspend fun getRepositories(@Path("userName") userName: String): List<RepositoryDto>
} | 0 | Kotlin | 0 | 2 | 4d49badc208291a242039cbd9dff0811b49683f1 | 418 | Android-Clean-Architecture | MIT License |
reduks-bus/src/test/kotlin/com/beyondeye/reduks/bus/BusStoreEnhancerTest.kt | bryant1410 | 88,438,925 | true | {"Kotlin": 277893, "Java": 150567} | package com.beyondeye.reduks.bus
import com.beyondeye.reduks.*
import com.beyondeye.reduks.modules.*
import com.beyondeye.reduks.pcollections.PMap
import org.junit.Test
import org.junit.Assert.*
class Action
{
class SetA(val newA:Int)
class SetB(val newB:Int)
}
val testReducer = ReducerFn<TestStateWithBusData> { state, action ->
when (action) {
is Action.SetA -> state.copy(a= action.newA)
is Action.SetB -> state.copy(b= action.newB)
else -> state
}
}
val testReducerNBD = ReducerFn<TestStateWithoutBusData> { state, action ->
when (action) {
is Action.SetA -> state.copy(a= action.newA)
is Action.SetB -> state.copy(b= action.newB)
else -> state
}
}
data class TestStateWithBusData(val a:Int, val b:Int, override val busData:PMap<String,Any> = busDataEmpty()): StateWithBusData {
override fun copyWithNewBusData(newBusData: PMap<String, Any>) = copy(busData=newBusData)
}
data class TestStateWithoutBusData(val a:Int,val b:Int)
val initialTestState= TestStateWithBusData(0,0)
val initialTestStateNBD=TestStateWithoutBusData(0,0)
val mdef1= ModuleDef(
storeCreator = SimpleStore.Creator<TestStateWithBusData>().enhancedWith(BusStoreEnhancer()),
initialState = initialTestState,
stateReducer = testReducer
)
val mdef2= ModuleDef(
storeCreator = SimpleStore.Creator<TestStateWithoutBusData>(),
initialState = initialTestStateNBD,
stateReducer = testReducerNBD
)
class BusStoreEnhancerTest {
@Test
fun testBusStore() {
//---given
val creator= SimpleStore.Creator<TestStateWithBusData>()
val store = creator.create(testReducer, initialTestState,BusStoreEnhancer())
var iDataReceivedCount:Int=0
var iHandlerCalls=0
var fDataReceivedCount:Int=0
var fHandlerCalls=0
store.addBusDataHandler { intVal:Int? ->
val receivedOnBus=intVal
++iHandlerCalls
if(receivedOnBus!=null) {
iDataReceivedCount++
assertEquals(receivedOnBus,1)
}
}
store.addBusDataHandler { floatVal:Float? ->
val receivedOnBus=floatVal
++fHandlerCalls
if(receivedOnBus!=null) {
fDataReceivedCount++
assertEquals(receivedOnBus,2.0F)
}
}
//---when
val iBusDataBeforePost:Int? =store.busData()
//---then
assertNull(iBusDataBeforePost)
//---when
val fBusDataBeforePost:Float? =store.busData()
//---then
assertNull(fBusDataBeforePost)
//---when
store.postBusData(2.0F)
//---then
assert(fDataReceivedCount==1)
assert(fHandlerCalls==1)
assert(iDataReceivedCount==0)
assert(iHandlerCalls==1) //!!!with the first post on the bus, all bus data handlers are called with null TODO: document this
//---when
iHandlerCalls=0
iDataReceivedCount=0
fHandlerCalls=0
fDataReceivedCount=0
store.postBusData(1)
//---then
assert(iHandlerCalls==1)
assert(iDataReceivedCount==1)
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
//---when
val ibusData:Int?=store.busData()
//---then
assertNotNull(ibusData)
assertEquals(ibusData ,1)
//---when
val fbusData:Float?=store.busData()
//---then
assertNotNull(fbusData)
assertEquals(fbusData ,2.0f)
//---given
fHandlerCalls=0
fDataReceivedCount=0
iHandlerCalls=0
iDataReceivedCount=0
//---when
//check that normal actions goes through as expected
store.dispatch(Action.SetA(1))
//---then
assertTrue(store.state.a==1)
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
//---when
fHandlerCalls=0
iHandlerCalls=0
store.clearBusData<Int>()
//---then
assert(iHandlerCalls==1) //data cleared message received
assert(iDataReceivedCount==0)
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
assertNull(store.busData<Int>())
//---when
fHandlerCalls=0
iHandlerCalls=0
store.clearBusData<Float>()
//---then
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
assert(fHandlerCalls==1) //data cleared message received
assert(fDataReceivedCount==0)
assertNull(store.busData<Float>())
//---when
fHandlerCalls=0
iHandlerCalls=0
store.removeAllBusDataHandlers()
store.postBusData(11)
//---then
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
//---when
fHandlerCalls=0
iHandlerCalls=0
store.postBusData(22.0f)
//---then
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
}
@Test
fun testBusStoreForMultiStore() {
//---given
val multidef=ReduksModule.MultiDef(mdef1, mdef2)
val mr = ReduksModule(multidef)
var iDataReceivedCount:Int=0
var fDataReceivedCount:Int=0
//---given
val store = mr.store as? MultiStore
assertNotNull("the created store should be a multistore",store)
store!!.addBusDataHandler { intVal:Int? ->
val receivedOnBus=intVal
if(receivedOnBus!=null) {
iDataReceivedCount++
assertEquals(receivedOnBus,1)
}
}
//test Reduks.addBusDataHandler extension function
mr.addBusDataHandlerWithTag("testtag") { floatVal:Float? ->
val receivedOnBus=floatVal
if(receivedOnBus!=null) {
fDataReceivedCount++
assertEquals(receivedOnBus,2.0F)
}
}
//---when
val iBusDataBeforePost:Int? =store.busData()
//---then
assertNull(iBusDataBeforePost)
//---when
val fBusDataBeforePost:Float? =store.busData()
//---then
assertNull(fBusDataBeforePost)
//---when
store.postBusData(2.0F)
//---then
assert(fDataReceivedCount==1)
assert(iDataReceivedCount==0)
//---when
store.postBusData(1)
//---then
assert(iDataReceivedCount==1)
assert(fDataReceivedCount==1)
//---when
val ibusData:Int?=store.busData()
//---then
assertNotNull(ibusData)
assertEquals(ibusData ,1)
//---when
val fbusData:Float?=store.busData()
//---then
assertNotNull(fbusData)
assertEquals(fbusData ,2.0f)
//---given
fDataReceivedCount=0
iDataReceivedCount=0
//---when
store.clearBusData<Int>()
//---then
assert(iDataReceivedCount==0)
assert(fDataReceivedCount==0)
assertNull(store.busData<Int>())
//---when
store.clearBusData<Float>()
//---then
assert(iDataReceivedCount==0)
assert(fDataReceivedCount==0)
assertNull(store.busData<Float>())
//---when
store.removeAllBusDataHandlers()
store.postBusData(11)
//---then
assert(fDataReceivedCount==0)
assert(iDataReceivedCount==0)
//---when
store.postBusData(22.0f)
//---then
assert(fDataReceivedCount==0)
assert(iDataReceivedCount==0)
}
class BusDataA(val payloadA:String)
class BusDataB(val payloadB:String)
@Test
fun testAddRemoveBusDataHandlers() {
//-------GIVEN
val multidef=ReduksModule.MultiDef(mdef1, mdef2)
val mr = ReduksModule(multidef)
assert(mr.busStoreSubscriptionsByTag.size==0)
//-------WHEN
val busStore=mr.subStore<TestStateWithBusData>() as? BusStore
//-------THEN
assert(busStore!=null)
//------AND WHEN
mr.addBusDataHandlerWithTag<BusDataA>("atag") {
throw NotImplementedError("Dummy handler!")
}
//------THEN
assert((mr.busStoreSubscriptionsByTag.size==1))
assert(busStore!!.nSubscriptions==1)
//------AND WHEN
mr.addBusDataHandlerWithTag<BusDataB>("btag") {
throw NotImplementedError("Dummy handler!")
}
//------THEN
assert((mr.busStoreSubscriptionsByTag.size==2))
assert(busStore.nSubscriptions==2)
var busSubscriptionsA=mr.busStoreSubscriptionsByTag["atag"]
assert(busSubscriptionsA!=null && busSubscriptionsA.size==1)
var busSubscriptionsB=mr.busStoreSubscriptionsByTag["btag"]
assert(busSubscriptionsB!=null && busSubscriptionsB.size==1)
//-----AND WHEN
mr.removeAllBusDataHandlers()
//------THEN
assert(busStore.nSubscriptions==0)
busSubscriptionsA=mr.busStoreSubscriptionsByTag["atag"]
assert(busSubscriptionsA==null || busSubscriptionsA.size==0)
busSubscriptionsB=mr.busStoreSubscriptionsByTag["btag"]
assert(busSubscriptionsB==null || busSubscriptionsB.size==0)
}
@Test
fun testRemoveBusDataHandlerWithTag() {
val multidef=ReduksModule.MultiDef(mdef1, mdef2)
val mr = ReduksModule(multidef)
//----AND GIVEN
mr.addBusDataHandlerWithTag<BusDataA>("atag") {
throw NotImplementedError("Dummy handler!")
}
mr.addBusDataHandlerWithTag<BusDataB>("btag") {
throw NotImplementedError("Dummy handler!")
}
val busSubscriptionsA=mr.busStoreSubscriptionsByTag["atag"]
val busSubscriptionsB=mr.busStoreSubscriptionsByTag["btag"]
val busStore=mr.subStore<TestStateWithBusData>() as BusStore
//----WHEN
mr.removeBusDataHandlersWithTag("atag")
//---THEN
assert(busSubscriptionsA!!.size==0)
assert(busSubscriptionsB!!.size==1)
assert(busStore.nSubscriptions==1)
//----AND WHEN
mr.removeBusDataHandlersWithTag("btag")
//---THEN
assert(busSubscriptionsA.size==0)
assert(busSubscriptionsB.size==0)
assert(busStore.nSubscriptions==0)
}
} | 0 | Kotlin | 0 | 0 | c1f2d040187cb47ce77b8a6ade5525ac37124002 | 10,518 | Reduks | Apache License 2.0 |
reduks-bus/src/test/kotlin/com/beyondeye/reduks/bus/BusStoreEnhancerTest.kt | bryant1410 | 88,438,925 | true | {"Kotlin": 277893, "Java": 150567} | package com.beyondeye.reduks.bus
import com.beyondeye.reduks.*
import com.beyondeye.reduks.modules.*
import com.beyondeye.reduks.pcollections.PMap
import org.junit.Test
import org.junit.Assert.*
class Action
{
class SetA(val newA:Int)
class SetB(val newB:Int)
}
val testReducer = ReducerFn<TestStateWithBusData> { state, action ->
when (action) {
is Action.SetA -> state.copy(a= action.newA)
is Action.SetB -> state.copy(b= action.newB)
else -> state
}
}
val testReducerNBD = ReducerFn<TestStateWithoutBusData> { state, action ->
when (action) {
is Action.SetA -> state.copy(a= action.newA)
is Action.SetB -> state.copy(b= action.newB)
else -> state
}
}
data class TestStateWithBusData(val a:Int, val b:Int, override val busData:PMap<String,Any> = busDataEmpty()): StateWithBusData {
override fun copyWithNewBusData(newBusData: PMap<String, Any>) = copy(busData=newBusData)
}
data class TestStateWithoutBusData(val a:Int,val b:Int)
val initialTestState= TestStateWithBusData(0,0)
val initialTestStateNBD=TestStateWithoutBusData(0,0)
val mdef1= ModuleDef(
storeCreator = SimpleStore.Creator<TestStateWithBusData>().enhancedWith(BusStoreEnhancer()),
initialState = initialTestState,
stateReducer = testReducer
)
val mdef2= ModuleDef(
storeCreator = SimpleStore.Creator<TestStateWithoutBusData>(),
initialState = initialTestStateNBD,
stateReducer = testReducerNBD
)
class BusStoreEnhancerTest {
@Test
fun testBusStore() {
//---given
val creator= SimpleStore.Creator<TestStateWithBusData>()
val store = creator.create(testReducer, initialTestState,BusStoreEnhancer())
var iDataReceivedCount:Int=0
var iHandlerCalls=0
var fDataReceivedCount:Int=0
var fHandlerCalls=0
store.addBusDataHandler { intVal:Int? ->
val receivedOnBus=intVal
++iHandlerCalls
if(receivedOnBus!=null) {
iDataReceivedCount++
assertEquals(receivedOnBus,1)
}
}
store.addBusDataHandler { floatVal:Float? ->
val receivedOnBus=floatVal
++fHandlerCalls
if(receivedOnBus!=null) {
fDataReceivedCount++
assertEquals(receivedOnBus,2.0F)
}
}
//---when
val iBusDataBeforePost:Int? =store.busData()
//---then
assertNull(iBusDataBeforePost)
//---when
val fBusDataBeforePost:Float? =store.busData()
//---then
assertNull(fBusDataBeforePost)
//---when
store.postBusData(2.0F)
//---then
assert(fDataReceivedCount==1)
assert(fHandlerCalls==1)
assert(iDataReceivedCount==0)
assert(iHandlerCalls==1) //!!!with the first post on the bus, all bus data handlers are called with null TODO: document this
//---when
iHandlerCalls=0
iDataReceivedCount=0
fHandlerCalls=0
fDataReceivedCount=0
store.postBusData(1)
//---then
assert(iHandlerCalls==1)
assert(iDataReceivedCount==1)
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
//---when
val ibusData:Int?=store.busData()
//---then
assertNotNull(ibusData)
assertEquals(ibusData ,1)
//---when
val fbusData:Float?=store.busData()
//---then
assertNotNull(fbusData)
assertEquals(fbusData ,2.0f)
//---given
fHandlerCalls=0
fDataReceivedCount=0
iHandlerCalls=0
iDataReceivedCount=0
//---when
//check that normal actions goes through as expected
store.dispatch(Action.SetA(1))
//---then
assertTrue(store.state.a==1)
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
//---when
fHandlerCalls=0
iHandlerCalls=0
store.clearBusData<Int>()
//---then
assert(iHandlerCalls==1) //data cleared message received
assert(iDataReceivedCount==0)
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
assertNull(store.busData<Int>())
//---when
fHandlerCalls=0
iHandlerCalls=0
store.clearBusData<Float>()
//---then
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
assert(fHandlerCalls==1) //data cleared message received
assert(fDataReceivedCount==0)
assertNull(store.busData<Float>())
//---when
fHandlerCalls=0
iHandlerCalls=0
store.removeAllBusDataHandlers()
store.postBusData(11)
//---then
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
//---when
fHandlerCalls=0
iHandlerCalls=0
store.postBusData(22.0f)
//---then
assert(fHandlerCalls==0)
assert(fDataReceivedCount==0)
assert(iHandlerCalls==0)
assert(iDataReceivedCount==0)
}
@Test
fun testBusStoreForMultiStore() {
//---given
val multidef=ReduksModule.MultiDef(mdef1, mdef2)
val mr = ReduksModule(multidef)
var iDataReceivedCount:Int=0
var fDataReceivedCount:Int=0
//---given
val store = mr.store as? MultiStore
assertNotNull("the created store should be a multistore",store)
store!!.addBusDataHandler { intVal:Int? ->
val receivedOnBus=intVal
if(receivedOnBus!=null) {
iDataReceivedCount++
assertEquals(receivedOnBus,1)
}
}
//test Reduks.addBusDataHandler extension function
mr.addBusDataHandlerWithTag("testtag") { floatVal:Float? ->
val receivedOnBus=floatVal
if(receivedOnBus!=null) {
fDataReceivedCount++
assertEquals(receivedOnBus,2.0F)
}
}
//---when
val iBusDataBeforePost:Int? =store.busData()
//---then
assertNull(iBusDataBeforePost)
//---when
val fBusDataBeforePost:Float? =store.busData()
//---then
assertNull(fBusDataBeforePost)
//---when
store.postBusData(2.0F)
//---then
assert(fDataReceivedCount==1)
assert(iDataReceivedCount==0)
//---when
store.postBusData(1)
//---then
assert(iDataReceivedCount==1)
assert(fDataReceivedCount==1)
//---when
val ibusData:Int?=store.busData()
//---then
assertNotNull(ibusData)
assertEquals(ibusData ,1)
//---when
val fbusData:Float?=store.busData()
//---then
assertNotNull(fbusData)
assertEquals(fbusData ,2.0f)
//---given
fDataReceivedCount=0
iDataReceivedCount=0
//---when
store.clearBusData<Int>()
//---then
assert(iDataReceivedCount==0)
assert(fDataReceivedCount==0)
assertNull(store.busData<Int>())
//---when
store.clearBusData<Float>()
//---then
assert(iDataReceivedCount==0)
assert(fDataReceivedCount==0)
assertNull(store.busData<Float>())
//---when
store.removeAllBusDataHandlers()
store.postBusData(11)
//---then
assert(fDataReceivedCount==0)
assert(iDataReceivedCount==0)
//---when
store.postBusData(22.0f)
//---then
assert(fDataReceivedCount==0)
assert(iDataReceivedCount==0)
}
class BusDataA(val payloadA:String)
class BusDataB(val payloadB:String)
@Test
fun testAddRemoveBusDataHandlers() {
//-------GIVEN
val multidef=ReduksModule.MultiDef(mdef1, mdef2)
val mr = ReduksModule(multidef)
assert(mr.busStoreSubscriptionsByTag.size==0)
//-------WHEN
val busStore=mr.subStore<TestStateWithBusData>() as? BusStore
//-------THEN
assert(busStore!=null)
//------AND WHEN
mr.addBusDataHandlerWithTag<BusDataA>("atag") {
throw NotImplementedError("Dummy handler!")
}
//------THEN
assert((mr.busStoreSubscriptionsByTag.size==1))
assert(busStore!!.nSubscriptions==1)
//------AND WHEN
mr.addBusDataHandlerWithTag<BusDataB>("btag") {
throw NotImplementedError("Dummy handler!")
}
//------THEN
assert((mr.busStoreSubscriptionsByTag.size==2))
assert(busStore.nSubscriptions==2)
var busSubscriptionsA=mr.busStoreSubscriptionsByTag["atag"]
assert(busSubscriptionsA!=null && busSubscriptionsA.size==1)
var busSubscriptionsB=mr.busStoreSubscriptionsByTag["btag"]
assert(busSubscriptionsB!=null && busSubscriptionsB.size==1)
//-----AND WHEN
mr.removeAllBusDataHandlers()
//------THEN
assert(busStore.nSubscriptions==0)
busSubscriptionsA=mr.busStoreSubscriptionsByTag["atag"]
assert(busSubscriptionsA==null || busSubscriptionsA.size==0)
busSubscriptionsB=mr.busStoreSubscriptionsByTag["btag"]
assert(busSubscriptionsB==null || busSubscriptionsB.size==0)
}
@Test
fun testRemoveBusDataHandlerWithTag() {
val multidef=ReduksModule.MultiDef(mdef1, mdef2)
val mr = ReduksModule(multidef)
//----AND GIVEN
mr.addBusDataHandlerWithTag<BusDataA>("atag") {
throw NotImplementedError("Dummy handler!")
}
mr.addBusDataHandlerWithTag<BusDataB>("btag") {
throw NotImplementedError("Dummy handler!")
}
val busSubscriptionsA=mr.busStoreSubscriptionsByTag["atag"]
val busSubscriptionsB=mr.busStoreSubscriptionsByTag["btag"]
val busStore=mr.subStore<TestStateWithBusData>() as BusStore
//----WHEN
mr.removeBusDataHandlersWithTag("atag")
//---THEN
assert(busSubscriptionsA!!.size==0)
assert(busSubscriptionsB!!.size==1)
assert(busStore.nSubscriptions==1)
//----AND WHEN
mr.removeBusDataHandlersWithTag("btag")
//---THEN
assert(busSubscriptionsA.size==0)
assert(busSubscriptionsB.size==0)
assert(busStore.nSubscriptions==0)
}
} | 0 | Kotlin | 0 | 0 | c1f2d040187cb47ce77b8a6ade5525ac37124002 | 10,518 | Reduks | Apache License 2.0 |
compose/src/main/java/dev/medzik/android/compose/ui/LoadingButton.kt | M3DZIK | 698,762,035 | false | {"Kotlin": 116204} | package dev.medzik.android.compose.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import dev.medzik.android.compose.rememberMutable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* Button that shows a loading animation when [loading] is true.
*
* @param onClick called when the button is clicked
* @param modifier the [Modifier] to be applied to the button
* @param loading state of the loading animation, if true, the animation will be shown
* @param enabled controls the enabled state of this button
*/
@Composable
fun LoadingButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
loading: Boolean,
enabled: Boolean = true,
content: @Composable () -> Unit
) {
Button(
onClick = onClick,
modifier = modifier,
enabled = enabled && !loading
) {
if (loading) {
LoadingIndicator(animating = true)
} else {
content()
}
}
}
/**
* Button with an loading animation.
*
* @param onClick called when the button is clicked (launched on IO thread)
* @param modifier the [Modifier] to be applied to the button
* @param enabled controls the enabled state of this button
*/
@Composable
fun LoadingButton(
onClick: suspend () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
content: @Composable () -> Unit
) {
var loading by rememberMutable { false }
val scope = rememberCoroutineScope()
LoadingButton(
onClick = {
loading = true
scope.launch(Dispatchers.IO) {
onClick()
loading = false
}
},
modifier = modifier,
loading = loading,
enabled = enabled,
content = content
)
}
@Preview(showBackground = true)
@Composable
private fun LoadingButtonPreview() {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
var loading by rememberMutable { false }
LoadingButton(
loading = loading,
onClick = { loading = !loading },
) {
Text("Click me")
}
LoadingButton(
loading = true,
onClick = {},
) {
Text("Loading")
}
LoadingButton(
onClick = {
Thread.sleep(1000)
}
) {
Text("Sleep 1s")
}
}
}
| 1 | Kotlin | 0 | 2 | 04a0762322dbd078c7332f5ac371298068de99e0 | 2,811 | android-libs | MIT License |
compose/src/main/java/dev/medzik/android/compose/ui/LoadingButton.kt | M3DZIK | 698,762,035 | false | {"Kotlin": 116204} | package dev.medzik.android.compose.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import dev.medzik.android.compose.rememberMutable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* Button that shows a loading animation when [loading] is true.
*
* @param onClick called when the button is clicked
* @param modifier the [Modifier] to be applied to the button
* @param loading state of the loading animation, if true, the animation will be shown
* @param enabled controls the enabled state of this button
*/
@Composable
fun LoadingButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
loading: Boolean,
enabled: Boolean = true,
content: @Composable () -> Unit
) {
Button(
onClick = onClick,
modifier = modifier,
enabled = enabled && !loading
) {
if (loading) {
LoadingIndicator(animating = true)
} else {
content()
}
}
}
/**
* Button with an loading animation.
*
* @param onClick called when the button is clicked (launched on IO thread)
* @param modifier the [Modifier] to be applied to the button
* @param enabled controls the enabled state of this button
*/
@Composable
fun LoadingButton(
onClick: suspend () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
content: @Composable () -> Unit
) {
var loading by rememberMutable { false }
val scope = rememberCoroutineScope()
LoadingButton(
onClick = {
loading = true
scope.launch(Dispatchers.IO) {
onClick()
loading = false
}
},
modifier = modifier,
loading = loading,
enabled = enabled,
content = content
)
}
@Preview(showBackground = true)
@Composable
private fun LoadingButtonPreview() {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
var loading by rememberMutable { false }
LoadingButton(
loading = loading,
onClick = { loading = !loading },
) {
Text("Click me")
}
LoadingButton(
loading = true,
onClick = {},
) {
Text("Loading")
}
LoadingButton(
onClick = {
Thread.sleep(1000)
}
) {
Text("Sleep 1s")
}
}
}
| 1 | Kotlin | 0 | 2 | 04a0762322dbd078c7332f5ac371298068de99e0 | 2,811 | android-libs | MIT License |
lib-kostra-common/src/commonTest/kotlin/test/StringMemoryDatabase.kt | jbruchanov | 670,094,402 | false | {"Kotlin": 358070, "Batchfile": 277} | package test
import com.jibru.kostra.KLocale
import com.jibru.kostra.StringResourceKey
import com.jibru.kostra.internal.StringDatabase
class StringMemoryDatabase(internal val data: Map<KLocale, Map<StringResourceKey, String>>) : StringDatabase(emptyMap()) {
override fun getValue(key: StringResourceKey, locale: KLocale): String? {
return data[locale]?.get(key).also {
println("StringMemoryDatabase.getValue key:$key, locale:$locale, result:$it")
}
}
}
| 0 | Kotlin | 0 | 0 | 9d01eba1a354674a1f48f4d073f4201fcc974d73 | 491 | kostra | Apache License 2.0 |
app/src/main/java/com/lvp/autodownloader/ui/settings/components/SwitchSettingItem.kt | LuongPV | 770,756,923 | false | {"Kotlin": 398406} | package com.lvp.autodownloader.ui.settings.components
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.lvp.autodownloader.ui.theme.AppTheme
import com.lvp.autodownloader.ui.theme.GreenColor
import com.lvp.autodownloader.utils.SingleDataCallback
@Composable
fun SwitchSettingItem(
icon: Int,
title: String,
isChecked: Boolean,
onCheckedChange: SingleDataCallback<Boolean>,
modifier: Modifier = Modifier
) {
SettingItem(modifier = modifier, icon = icon, title = title) {
Switch(
checked = isChecked, onCheckedChange = onCheckedChange, colors = SwitchDefaults.colors(
checkedTrackColor = GreenColor,
uncheckedBorderColor = Color(0xFF535353),
uncheckedThumbColor = Color(0xFF535353),
uncheckedTrackColor = AppTheme.getCustomizedThemeColors(
lightColor = Color(0xFFDADADA),
darkColor = Color(0xFF9E9E9E),
),
)
)
}
} | 0 | Kotlin | 0 | 0 | d61756b69755b0df324f7fd13c50aced46402c59 | 1,173 | AutoDownloader | Apache License 1.1 |
src/main/kotlin/com/madrapps/dagger/validation/InjectProblem.kt | Madrapps | 245,758,107 | false | null | package com.madrapps.dagger.validation
import com.intellij.psi.PsiElement
import com.madrapps.dagger.utils.*
import org.jetbrains.uast.*
object InjectProblem : Problem {
override fun isError(element: PsiElement): List<Problem.Error> {
val annotation = element.toUElement()
if (annotation is UAnnotation && annotation.isInject) {
val declaration = annotation.getContainingDeclaration() ?: return emptyList()
val range = annotation.psiIdentifier
return when (declaration) {
is UMethod -> validateMethod(declaration, range)
is UVariable -> validateField(declaration, range)
else -> emptyList()
}
}
return emptyList()
}
private fun validateField(field: UVariable, range: PsiElement): List<Problem.Error> {
return mutableListOf<Problem.Error>().apply {
this += validateFinalField(field, range)
this += validatePrivateField(field, range)
this += validateStaticField(field, range)
this += validatePrivateClass(field, range)
}
}
private fun validateMethod(method: UMethod, range: PsiElement): List<Problem.Error> {
return if (method.isConstructor) {
validateConstructor(method, range)
} else {
mutableListOf<Problem.Error>().apply {
this += method.validatePrivateMethod(range, "Dagger does not support injection into private methods")
this += method.validateAbstractMethod(range, "Methods with @Inject may not be abstract")
this += validateStaticMethod(method, range)
this += method.validateTypeParameter(range, "Methods with @Inject may not declare type parameters")
this += method.validateCheckedExceptionMethod(range, "Methods with @Inject may not throw checked exceptions %s. " +
"Please wrap your exceptions in a RuntimeException instead.")
this += validatePrivateClass(method, range)
}
}
}
private fun validateConstructor(method: UMethod, range: PsiElement): List<Problem.Error> {
return mutableListOf<Problem.Error>().apply {
this += validatePrivateConstructor(method, range)
this += validateScopeOnConstructor(method, range)
this += validateQualifierOnConstructor(method, range)
this += validateAbstractClass(method, range)
this += validateIfSingleAnnotation(method, range)
this += validateMultipleScope(method, range)
this += method.validateCheckedExceptionMethod(range, "Dagger does not support checked exceptions %s on @Inject constructors")
this += validateInnerClass(method, range)
this += validatePrivateClass(method, range)
}
}
private fun validatePrivateClass(declaration: UDeclaration, range: PsiElement): List<Problem.Error> {
val uClass = declaration.getContainingUClass() ?: return emptyList()
return if (uClass.isPrivateOrParameterInPrivateMethod()) {
range.errors("Dagger does not support injection into private classes")
} else emptyList()
}
private fun validateInnerClass(method: UMethod, range: PsiElement): List<Problem.Error> {
val uClass = method.getContainingUClass() ?: return emptyList()
return if (uClass.isInner) {
range.errors("@Inject constructors are invalid on inner classes. Did you mean to make the class static?")
} else emptyList()
}
private fun validateMultipleScope(method: UMethod, range: PsiElement): List<Problem.Error> {
val uClass = method.getContainingUClass() ?: return emptyList()
val scopes = uClass.scopes()
return if (scopes.size > 1) {
range.errors("A single binding may not declare more than one @Scope ${scopes.presentable}")
} else emptyList()
}
private fun validateIfSingleAnnotation(method: UMethod, range: PsiElement): List<Problem.Error> {
val uClass = method.getContainingUClass() ?: return emptyList()
val constructorsWithInject = uClass.methods.filter { it.isConstructor && it.isInject }.count()
return if (constructorsWithInject > 1) {
range.errors("Types may only contain one @Inject constructor")
} else emptyList()
}
private fun validateAbstractClass(method: UMethod, range: PsiElement): List<Problem.Error> {
return if (method.getContainingUClass()?.isAbstract == true) {
range.errors("@Inject is nonsense on the constructor of an abstract class")
} else emptyList()
}
private fun validateScopeOnConstructor(method: UMethod, range: PsiElement): List<Problem.Error> {
val scopes = method.scopes()
return if (scopes.isNotEmpty()) {
range.errors("@Scope annotations ${scopes.presentable} are not allowed on @Inject constructors; annotate the class instead")
} else emptyList()
}
private fun validateQualifierOnConstructor(method: UMethod, range: PsiElement): List<Problem.Error> {
val qualifiers = method.qualifiers()
return if (qualifiers.isNotEmpty()) {
range.errors("@Qualifier annotations ${qualifiers.presentable} are not allowed on @Inject constructors")
} else emptyList()
}
private fun validatePrivateConstructor(method: UMethod, range: PsiElement): List<Problem.Error> {
return if (method.isPrivateOrParameterInPrivateMethod()) {
range.errors("Dagger does not support injection into private constructors")
} else emptyList()
}
private fun validatePrivateField(field: UVariable, range: PsiElement): List<Problem.Error> {
return if (field.isPrivateOrParameterInPrivateMethod()) {
range.errors("Dagger does not support injection into private fields")
} else emptyList()
}
private fun validateStaticField(field: UVariable, range: PsiElement): List<Problem.Error> {
return if (field.isStatic || field.getContainingUClass()?.isKotlinObject == true) {
range.errors("Dagger does not support injection into static fields")
} else emptyList()
}
private fun validateFinalField(field: UVariable, range: PsiElement): List<Problem.Error> {
return if (field.isFinal) {
range.errors("@Inject fields may not be final")
} else emptyList()
}
private fun validateStaticMethod(method: UMethod, range: PsiElement): List<Problem.Error> {
return if (method.isStatic || method.getContainingUClass()?.isKotlinObject == true) {
range.errors("Dagger does not support injection into static methods")
} else emptyList()
}
}
| 13 | Kotlin | 7 | 27 | e75ebab16eb85139d55b4d31f04021938671a384 | 6,804 | dagger-plugin | Apache License 2.0 |
src/main/kotlin/edu/antevortadb/dbInteraction/dbSelector/hollywood/MLGenomeTagsSelector.kt | spg63 | 115,169,375 | false | null | /*
* Copyright (c) 2018 Sean Grimes. All Rights Reserved.
* License: MIT
*/
package edu.antevortadb.dbInteraction.dbSelector.hollywood
import edu.antevortadb.configs.DBLocator
import edu.antevortadb.configs.Finals
import edu.antevortadb.dbInteraction.columnsAndKeys.MovielensGenomeTags
import edu.antevortadb.dbInteraction.dbSelector.DBSelector
import edu.antevortadb.dbInteraction.dbSelector.RSMapper
import edu.antevortadb.dbInteraction.dbSelector.SelectionWorker
import edu.antevortadb.dbInteraction.dbSelector.Selector
import java.util.concurrent.ConcurrentHashMap
val tagMemoMap = ConcurrentHashMap<String, Int>()
class MLGenomeTagsSelector: Selector() {
private val tagcol = "tag"
private val tagidcol = "tagid"
init {
this.tableName = Finals.ML_GENOME_TAGS_TABLE
this.listOfColumns = MovielensGenomeTags.columnNames()
}
override fun generalSelection(SQLStatement: String): List<RSMapper> {
val dbs = DBLocator.hollywoodAbsolutePaths()
verifyDBsExist(dbs)
val workers = ArrayList<SelectionWorker>()
for(i in 0 until dbs.size)
workers.add(SelectionWorker(dbs[i], SQLStatement, MLGenomeTagsSetMapper()))
return genericSelect(workers, SQLStatement)
}
/**
* @return the tagID if it's found from the tagText, else -1
*/
fun getTagIDFromTagText(tagText: String): Int {
val memoResult = tagMemoMap[tagText]
if(memoResult != null)
return memoResult
// Need to clean up the string
val tag = tagText.toLowerCase().replace("'", "").replace("\"", "")
val dbsql = DBSelector()
.column(tagidcol)
.from(this.tableName)
.where("$tagcol = '$tag'")
val res = this.generalSelection(dbsql.sql())
// Oh, how disappointing.
if(res.isEmpty()){
return -1
}
// Instead of returning -1 here, just return the first result. Let the code
// continue
if(res.size > 1)
logger.err("${res.size} results for '$tagText'. " +
"Returning the last added result.")
// Get the tagid value from the RSMapper object
val tagid = res[0].getInt(tagidcol)
// Add the result to the map for future look-ups
if(!tagMemoMap.contains(tagText)) tagMemoMap[tagText] = tagid
return tagid
}
}
| 0 | Kotlin | 0 | 0 | dd2626b93ece7ffddf6e9776e20882b1cfd63dca | 2,417 | antevorta-db | MIT License |
mobile/app/src/main/java/at/sunilson/tahomaraffstorecontroller/mobile/features/authentication/domain/LogoutUseCase.kt | sunilson | 524,687,319 | false | null | package at.sunilson.tahomaraffstorecontroller.mobile.features.authentication.domain
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import at.sunilson.tahomaraffstorecontroller.mobile.features.authentication.data.GATEWAY_PIN_KEY
import at.sunilson.tahomaraffstorecontroller.mobile.features.authentication.data.PASSWORD_KEY
import at.sunilson.tahomaraffstorecontroller.mobile.features.authentication.data.USERNAME_KEY
import at.sunilson.tahomaraffstorecontroller.mobile.features.authentication.data.USER_TOKEN_KEY
import at.sunilson.tahomaraffstorecontroller.mobile.shared.domain.UseCase
class LogoutUseCase(private val encryptedSharedPreferences: EncryptedSharedPreferences) : UseCase<Unit, Unit>() {
override suspend fun doWork(params: Unit) {
encryptedSharedPreferences.edit {
remove(USERNAME_KEY)
remove(PASSWORD_KEY)
remove(GATEWAY_PIN_KEY)
remove(USER_TOKEN_KEY)
}
}
} | 0 | Kotlin | 0 | 0 | 8dedb163d4ba1353508020fe7bfa148d65b02a0a | 993 | somfy-tahoma-raffstore-app | MIT License |
src/main/kotlin/indi/midreamsheep/app/tre/context/TREAction.kt | Simple-Markdown | 744,897,915 | false | {"Kotlin": 148610, "Java": 49446} | package indi.midreamsheep.app.tre.context
abstract class TREAction<T>(val context: T) | 0 | Kotlin | 0 | 3 | d5fb0506f8273d7cc2dd6cec28b3fae47e80ade7 | 86 | SMarkdown | Apache License 2.0 |
network/src/main/java/muoipt/nyt/network/di/ApiServiceModule.kt | muoipt | 822,659,454 | false | {"Kotlin": 93219} | package muoipt.nyt.network.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import muoipt.nyt.network.api.ArticleApiService
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class ApiServiceModule {
@Provides
@Singleton
fun provideArticleApiService(retrofit: Retrofit): ArticleApiService {
return retrofit.create(ArticleApiService::class.java)
}
} | 0 | Kotlin | 0 | 0 | 9d7b69b5cc982881329ffefa47e57a262b4ad7ba | 501 | NYTimesTopStoriesCompose | Apache License 2.0 |
kotpass/src/main/kotlin/app/keemobile/kotpass/cryptography/padding/PKCS7Padding.kt | keemobile | 384,214,968 | false | {"Kotlin": 452076} | /**
* The Bouncy Castle License
*
* Copyright (c) 2000-2021 The Legion Of The Bouncy Castle Inc. (https://www.bouncycastle.org)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package app.keemobile.kotpass.cryptography.padding
import app.keemobile.kotpass.errors.CryptoError.InvalidCipherText
/**
* PKCS#7 is described in RFC 5652.
*
* Padding is in whole bytes. The value of each added byte is the number of
* bytes that are added, i.e. N bytes, each of value N are added. The number
* of bytes added will depend on the block boundary to which the message
* needs to be extended.
*
* **See Also:** [RFC 5652](https://tools.ietf.org/html/rfc5652#section-6.3)
*/
internal data object PKCS7Padding : BlockCipherPadding {
override fun addPadding(input: ByteArray, offset: Int): Int {
val code = (input.size - offset).toByte()
input.fill(code, offset)
return code.toInt()
}
override fun padCount(input: ByteArray): Int {
val countAsByte = input[input.size - 1]
val count = countAsByte.toInt() and 0xFF
val position = input.size - count
var failed = (position or (count - 1)) shr 31
for (i in input.indices) {
failed = failed or (
(input[i].toInt() xor countAsByte.toInt())
and ((i - position) shr 31).inv()
)
}
if (failed != 0) {
throw InvalidCipherText("Pad block is corrupted")
}
return count
}
}
| 4 | Kotlin | 0 | 14 | 4b6455872fb882b74787c9ba18dd7024a9dde69d | 2,533 | kotpass | MIT License |
src/test/kotlin/kio/util/CollectionUtilsTest.kt | kotcrab | 153,176,744 | false | null | /*
* 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 kio.util
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class CollectionUtilsTest {
@Test
fun `should pad array`() {
assertThat(padArray(ByteArray(0), 4)).hasSize(0)
assertThat(padArray(ByteArray(1), 4)).hasSize(4)
assertThat(padArray(ByteArray(2), 4)).hasSize(4)
assertThat(padArray(ByteArray(3), 4)).hasSize(4)
assertThat(padArray(ByteArray(4), 4)).hasSize(4)
assertThat(padArray(ByteArray(5), 4)).hasSize(8)
assertThat(padArray(ByteArray(0), 16)).hasSize(0)
assertThat(padArray(ByteArray(10), 16)).hasSize(16)
assertThat(padArray(ByteArray(16), 16)).hasSize(16)
}
@Test
fun `should copy array`() {
val arr1 = ByteArray(5) { 0xCD.toByte() }
val arr2 = ByteArray(5)
arrayCopy(src = arr1, dest = arr2)
assertThat(arr1).containsExactly(*arr2)
}
@Test
fun `should copy part of array`() {
val arr1 = ByteArray(5) { 0xCD.toByte() }
val arr2 = ByteArray(5)
arrayCopy(src = arr1, dest = arr2, destPos = 2, length = 1)
assertThat(arr2).containsExactly(0, 0, 0xCD, 0, 0)
}
@Test
fun `should swap 2 elements using indexes`() {
val arr = mutableListOf(true, false)
arr.swap(0, 1)
assertThat(arr).containsExactly(false, true)
}
@Test
fun `should swap 2 elements using objects`() {
val arr = mutableListOf(true, false)
arr.swap(arr[0], arr[1])
assertThat(arr).containsExactly(false, true)
}
@Test
fun `should append line`() {
val sb = StringBuilder()
sb.appendLine("foo")
assertThat(sb.toString()).isEqualTo("foo\n")
}
@Test
fun `should append line with custom new line`() {
val sb = StringBuilder()
sb.appendLine("foo", newLine = "\r\n")
assertThat(sb.toString()).isEqualTo("foo\r\n")
}
@Test
fun `should return sub array pos`() {
val arr = byteArrayOf(0, 0, 0, 1, 2, 3, 0, 0, 3, 2)
assertThat(getSubArrayPos(arr, byteArrayOf(1, 2, 3))).isEqualTo(3)
}
}
| 0 | Kotlin | 0 | 1 | 9111dcc149039e72987b9e83bb8a148e1fddc634 | 2,528 | kio | Apache License 2.0 |
app/src/main/java/com/deonolarewaju/product_catalogue/BrowseProductsApplication.kt | deonwaju | 729,797,385 | false | {"Kotlin": 48833} | package com.deonolarewaju.product_catalogue
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class BrowseProductsApplication: Application() {
} | 0 | Kotlin | 0 | 1 | fead009cfd7e36c09d4c8965c768c6b6f12d75d8 | 185 | Product-catalogue | MIT License |
app/src/main/java/com/example/byowsigner/AppContainer.kt | bitcoin-education | 607,962,286 | false | null | package com.example.byowsigner
import android.content.Context
import com.example.byowsigner.api.ExtendedPubkeyService
import com.example.byowsigner.api.MnemonicSeedService
import com.example.byowsigner.api.TransactionParserService
import com.example.byowsigner.api.TransactionSignerService
import com.example.byowsigner.database.AppDatabase
import com.example.byowsigner.database.WalletRepository
class AppContainer(applicationContext: Context) {
var db = AppDatabase(applicationContext)
val mnemonicSeedService: MnemonicSeedService = MnemonicSeedService()
var walletRepository = WalletRepository(db.walletDao())
val transactionParserService: TransactionParserService = TransactionParserService()
val transactionSignerService: TransactionSignerService = TransactionSignerService()
val extendedPubkeyService: ExtendedPubkeyService = ExtendedPubkeyService()
} | 0 | Kotlin | 0 | 0 | 3caa4a0c42d1c7c92f788f746693117b426767bb | 884 | byow-signer | MIT License |
core/base/src/commonMain/kotlin/com/thomaskioko/tvmaniac/core/base/model/AppCoroutineScope.kt | thomaskioko | 361,393,353 | false | {"Kotlin": 668650, "Swift": 206696, "Ruby": 1770, "Shell": 1120} | package com.thomaskioko.tvmaniac.core.base.model
import kotlinx.coroutines.CoroutineScope
data class AppCoroutineScope(
val default: CoroutineScope,
val io: CoroutineScope,
val main: CoroutineScope,
)
| 15 | Kotlin | 28 | 282 | 8c83a0461c03a1975afdf709e9d9307a141c0ec3 | 209 | tv-maniac | Apache License 2.0 |
app/src/main/kotlin/org/jdc/template/util/log/CrashLogException.kt | jeffdcamp | 12,853,600 | false | {"Kotlin": 391400, "HTML": 58007} | package org.jdc.template.util.log
/**
* Non-fatal exception for use with Logger and Crashlytics
*/
class CrashLogException(message: String = "") : RuntimeException(message) | 0 | Kotlin | 40 | 99 | a50a83a046765c6ba8d0c60a5241e7aba7fe8c59 | 175 | android-template | Apache License 2.0 |
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/ScreenshotOutlined.kt | karakum-team | 387,062,541 | false | {"Kotlin": 3059969, "TypeScript": 2249, "HTML": 724, "CSS": 86} | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ScreenshotOutlined")
package mui.icons.material
@JsName("default")
external val ScreenshotOutlined: SvgIconComponent
| 0 | Kotlin | 5 | 35 | 45ca2eabf1d75a64ab7454fa62a641221ec0aa25 | 200 | mui-kotlin | Apache License 2.0 |
core/src/commonTest/kotlin/dev/kryptonreborn/blockfrost/unittest/network/model/NetworkInformationTest.kt | KryptonReborn | 803,884,694 | false | {"Kotlin": 608773, "Swift": 594, "HTML": 323} | package dev.kryptonreborn.blockfrost.unittest.network.model
import dev.kryptonreborn.blockfrost.TestKtorClient.resourceToExpectedData
import dev.kryptonreborn.blockfrost.network.model.NetworkInformation
import kotlin.test.Test
import kotlin.test.assertEquals
class NetworkInformationTest {
@Test
fun testDeserialization() {
val content =
"src/commonTest/resources/model/network_information.json".resourceToExpectedData<NetworkInformation>()
// Supply details
val supply = content.supply
assertEquals("45000000000000000", supply.max)
assertEquals("32890715183299160", supply.total)
assertEquals("32412601976210393", supply.circulating)
assertEquals("125006953355", supply.locked)
assertEquals("98635632000000", supply.treasury)
assertEquals("46635632000000", supply.reserves)
// Stake details
val stake = content.stake
assertEquals("23204950463991654", stake.live)
assertEquals("22210233523456321", stake.active)
}
}
| 0 | Kotlin | 1 | 1 | 8eeb0f0a6776bcfba4051c8c88cb8c406a49b28b | 1,048 | blockfrost-kotlin-sdk | Apache License 2.0 |
core/src/commonTest/kotlin/dev/kryptonreborn/blockfrost/unittest/network/model/NetworkInformationTest.kt | KryptonReborn | 803,884,694 | false | {"Kotlin": 608773, "Swift": 594, "HTML": 323} | package dev.kryptonreborn.blockfrost.unittest.network.model
import dev.kryptonreborn.blockfrost.TestKtorClient.resourceToExpectedData
import dev.kryptonreborn.blockfrost.network.model.NetworkInformation
import kotlin.test.Test
import kotlin.test.assertEquals
class NetworkInformationTest {
@Test
fun testDeserialization() {
val content =
"src/commonTest/resources/model/network_information.json".resourceToExpectedData<NetworkInformation>()
// Supply details
val supply = content.supply
assertEquals("45000000000000000", supply.max)
assertEquals("32890715183299160", supply.total)
assertEquals("32412601976210393", supply.circulating)
assertEquals("125006953355", supply.locked)
assertEquals("98635632000000", supply.treasury)
assertEquals("46635632000000", supply.reserves)
// Stake details
val stake = content.stake
assertEquals("23204950463991654", stake.live)
assertEquals("22210233523456321", stake.active)
}
}
| 0 | Kotlin | 1 | 1 | 8eeb0f0a6776bcfba4051c8c88cb8c406a49b28b | 1,048 | blockfrost-kotlin-sdk | Apache License 2.0 |
opta-router-core/src/main/kotlin/io/github/pintowar/opta/router/core/domain/models/matrix/VrpCachedMatrix.kt | pintowar | 120,393,481 | false | {"Kotlin": 156826, "Vue": 72961, "TypeScript": 5560, "JavaScript": 463, "HTML": 388, "CSS": 58} | package io.github.pintowar.opta.router.core.domain.models.matrix
import java.util.concurrent.ConcurrentHashMap
class VrpCachedMatrix(private val matrix: Matrix) : Matrix by matrix {
private val distanceCache = ConcurrentHashMap<Pair<Long, Long>, Double>()
private val timeCache = ConcurrentHashMap<Pair<Long, Long>, Long>()
override fun distance(originId: Long, targetId: Long): Double {
return distanceCache.computeIfAbsent(originId to targetId) { (i, j) -> matrix.distance(i, j) }
}
override fun time(originId: Long, targetId: Long): Long {
return timeCache.computeIfAbsent(originId to targetId) { (i, j) -> matrix.time(i, j) }
}
} | 1 | Kotlin | 2 | 28 | 4c49f6c5bbb16ad8a68eb15fae87c6ddc59aede0 | 678 | opta-router | Apache License 2.0 |
misk/src/main/kotlin/misk/web/shutdown/GracefulShutdownModule.kt | cashapp | 113,107,217 | false | {"Kotlin": 3916547, "TypeScript": 285736, "Java": 83564, "JavaScript": 6613, "Shell": 5536, "HTML": 2323, "CSS": 58, "HCL": 20} | package misk.web.shutdown
import misk.MiskDefault
import misk.ServiceModule
import misk.annotation.ExperimentalMiskApi
import misk.inject.KAbstractModule
import misk.web.NetworkInterceptor
import misk.web.WebConfig
import misk.web.jetty.JettyHealthService.Companion.jettyHealthServiceEnabled
import misk.web.jetty.JettyService
internal class GracefulShutdownModule (private val config: WebConfig): KAbstractModule() {
@OptIn(ExperimentalMiskApi::class)
override fun configure() {
if (!config.jettyHealthServiceEnabled() || config.graceful_shutdown_config?.disabled != false) {
return
}
install(
ServiceModule<GracefulShutdownService>()
.dependsOn<JettyService>()
)
multibind<NetworkInterceptor.Factory>(MiskDefault::class)
.to<GracefulShutdownInterceptorFactory>()
}
}
| 168 | Kotlin | 169 | 399 | 76aa8e38a05c913d86cffc581363f82fd132e5c4 | 825 | misk | Apache License 2.0 |
app/src/main/java/myid/shizuka/rpl/models/Quiz.kt | Shizu-ka | 698,383,498 | false | {"Kotlin": 61439} | package myid.shizuka.rpl.models
class Quiz {
var id: String = ""
get() = field
set(value) {
field = value
}
var title: String = ""
get() = field
set(value) {
field = value
}
var questions: MutableMap<String, Question> = mutableMapOf()
get() = field
set(value) {
field = value
}
} | 0 | Kotlin | 3 | 2 | f3e793215fefee8b6f3b8e344a0b7d12b12b0cbc | 402 | Quiz-App | MIT License |
app/src/test/java/com/adwi/pexwallpapers/repository/FakeSettingsRepository.kt | adimanwit | 388,852,382 | false | null | package com.adwi.pexwallpapers.data.repository
import com.adwi.pexwallpapers.data.local.entity.Settings
import com.adwi.pexwallpapers.data.local.entity.defaultSettings
import com.adwi.pexwallpapers.data.repository.interfaces.SettingsRepositoryInterface
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
class FakeSettingsRepository : SettingsRepositoryInterface {
private var settingsItem = Settings()
private val settingsFlow = MutableStateFlow(settingsItem)
override suspend fun getSettings(): Settings {
return settingsFlow.first()
}
override suspend fun insertSettings(settings: Settings) {
settingsItem = settings
refreshFlow()
}
override suspend fun updateLastQuery(query: String) {
settingsItem.lastQuery = query
refreshFlow()
}
override suspend fun updatePushNotification(enabled: Boolean) {
settingsItem.pushNotification = enabled
refreshFlow()
}
override suspend fun updateNewWallpaperSet(enabled: Boolean) {
settingsItem.newWallpaperSet = enabled
refreshFlow()
}
override suspend fun updateWallpaperRecommendations(enabled: Boolean) {
settingsItem.wallpaperRecommendations = enabled
refreshFlow()
}
override suspend fun updateAutoChangeWallpaper(enabled: Boolean) {
settingsItem.autoChangeWallpaper = enabled
refreshFlow()
}
override suspend fun updateDownloadOverWiFi(enabled: Boolean) {
settingsItem.downloadOverWiFi = enabled
refreshFlow()
}
override suspend fun updateChangePeriodType(radioButton: Int) {
settingsItem.selectedButton = radioButton
refreshFlow()
}
override suspend fun updateChangePeriodMinutes(periodValue: Float) {
settingsItem.timeRangeMinutes = periodValue
refreshFlow()
}
override suspend fun resetAllSettings() {
settingsItem = defaultSettings
refreshFlow()
}
private fun refreshFlow() {
settingsFlow.value = settingsItem
}
} | 0 | Kotlin | 1 | 2 | 0a0cefec5b890262ea6c62ca7f62cbaa0a956ac5 | 2,091 | PexWallpapers | Apache License 2.0 |
app/src/main/java/com/utn/frba/cinemapp/data/api/mappers/DetailsMovieDataEntityMapper.kt | UTN-FRBA-Mobile | 299,745,853 | false | null | package com.utn.frba.cinemapp.data.api.mappers
import com.utn.frba.cinemapp.data.api.entity.movies.MovieDetailsData
import com.utn.frba.cinemapp.domain.common.Mapper
import com.utn.frba.cinemapp.domain.entities.movies.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DetailsMovieDataEntityMapper @Inject constructor() : Mapper<MovieDetailsData, MovieEntity>() {
override fun mapFrom(from: MovieDetailsData): MovieEntity {
val details = MovieDetailsEntity(
overview = from.overview,
budget = from.budget,
homepage = from.homepage,
imdbId = from.imdbId,
revenue = from.revenue,
runtime = from.runtime,
tagline = from.tagline,
genres = from.genres?.map { genreData ->
GenreEntity(id = genreData.id, name = genreData.name)
},
videos = from.videos?.results?.map { videoData ->
VideoEntity(
id = videoData.id,
name = videoData.name,
youtubeKey = videoData.key
)
},
reviews = from.reviews?.results?.map { reviewData ->
ReviewEntity(
id = reviewData.id,
author = reviewData.author,
content = reviewData.content
)
}
)
return MovieEntity(
id = from.id,
voteCount = from.voteCount,
video = from.video,
voteAverage = from.voteAverage,
popularity = from.popularity,
adult = from.adult,
title = from.title,
posterPath = from.posterPath,
originalTitle = from.originalTitle,
backdropPath = from.backdropPath,
originalLanguage = from.originalLanguage,
releaseDate = from.releaseDate,
overview = from.overview,
details = details
)
}
} | 0 | Kotlin | 0 | 0 | 68b858ab93c113f80477c26355a3937aaabeae3d | 2,013 | Cinemapp | MIT License |
queue/src/main/java/com/github/xpwu/queue/queue.kt | xpwu | 847,632,466 | false | {"Kotlin": 1554} | package com.github.xpwu.queue
import kotlinx.coroutines.CoroutineName
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.AbstractCoroutineContextElement
private class queueCtx<T>(
val underlying: T
) : AbstractCoroutineContextElement(queueCtx) {
companion object Key : CoroutineContext.Key<queueCtx<*>>
}
class Queue<T>(name: String = "xpwu.queue", init: suspend ()->T){
private val scope = CoroutineScope(CoroutineName(name))
internal val queue: Channel<suspend (T) -> Unit> = Channel(UNLIMITED)
init {
// consumer
scope.launch {
val underlying = init()
withContext(queueCtx(underlying)) {
while (isActive) {
val exe = queue.receive()
exe(underlying)
}
}
}
}
fun close() {
scope.cancel()
}
}
suspend operator fun <R, T> Queue<T>.invoke(block: suspend (T)->R): R {
// process nest
val ctx = currentCoroutineContext()[queueCtx.Key]
if (ctx != null) {
@Suppress("UNCHECKED_CAST")
return block(ctx.underlying as T)
}
val ch = Channel<R>(1)
queue.send {
ch.send(block(it))
}
return ch.receive()
}
suspend fun <R, T> Queue<T>.en(block: suspend (T)->R): R {
return this(block)
}
| 0 | Kotlin | 0 | 0 | 76da350cbe46dc987d2506213defdd183ebbf33a | 1,554 | kt-queue | MIT License |
tangem-sdk-android/src/main/java/com/tangem/sdk/nfc/SlixTagReader.kt | tangem | 218,994,149 | false | {"Kotlin": 1222315, "Java": 13485, "Ruby": 911} | package com.tangem.sdk.nfc
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.tech.NfcV
import com.tangem.common.apdu.StatusWord
import com.tangem.common.extensions.toByteArray
import com.tangem.common.extensions.toHexString
import com.tangem.common.tlv.Tlv
import com.tangem.common.tlv.TlvDecoder
import com.tangem.common.tlv.TlvTag
import java.io.ByteArrayOutputStream
import java.io.IOException
class SlixTagReader {
private lateinit var nfcV: NfcV
fun transceive(nfcV: NfcV): SlixReadResult {
this.nfcV = nfcV
if (!nfcV.isConnected) {
try {
nfcV.connect()
} catch (e: Exception) {
return SlixReadResult.Failure(e)
}
}
return try {
runRead()
} catch (e: Exception) {
nfcV.close()
SlixReadResult.Failure(e)
}
}
private fun runRead(): SlixReadResult {
val ndefMessage = runReadNDEF()
val records: Array<NdefRecord> = ndefMessage.records
for (record in records) {
if (record.toUri() != null && record.toUri().toString() == "vnd.android.nfc://ext/tangem.com:wallet") {
val payload = record.payload
val status = StatusWord.ProcessCompleted.code.toByteArray()
val data = payload.copyOfRange(2, payload.size) + status
nfcV.close()
return SlixReadResult.Success(data)
}
}
return SlixReadResult.Failure(Exception("No relevant data was found."))
}
@Suppress("MagicNumber")
private fun runReadNDEF(): NdefMessage {
val answerCC = readSingleBlock(0x00)
val condition = answerCC.size != 4 || answerCC[0].toInt() != 0xE1 ||
answerCC[1].toInt().and(other = 0xF0) != 0x40
if (!condition) error("Failed! Invalid CC read " + answerCC.toHexString())
if (answerCC[3].toInt().and(other = 0x01) != 0x01) error("Multiple block read unsupported!")
val areaSize = 8 * answerCC[2]
val blocksCount = areaSize / 4
val areaBuf = readMultipleBlocks(startBlock = 1, blocksCount = blocksCount)
val tlvNdef = TlvDecoder(Tlv.deserialize(areaBuf, true) ?: listOf())
return NdefMessage(tlvNdef.decode<ByteArray>(TlvTag.CardPublicKey))
}
private fun readSingleBlock(blockNo: Int): ByteArray {
return performRead(cmd = 0x20, p1 = blockNo)!!
}
private fun readMultipleBlocks(startBlock: Int, blocksCount: Int): ByteArray {
val resultBuf = ByteArrayOutputStream()
var blocksRemaining = blocksCount
var firstBlockToRead = startBlock
while (blocksRemaining > 0) {
val blocksToRead = if (blocksRemaining > MAX_BLOCKS_AT_ONCE) MAX_BLOCKS_AT_ONCE else blocksRemaining
val blocks = performRead(0x23.toByte(), firstBlockToRead, blocksToRead - 1)
blocksRemaining -= blocksToRead
firstBlockToRead += blocksToRead
resultBuf.write(blocks!!)
}
return resultBuf.toByteArray()
}
@Suppress("ImplicitDefaultLocale")
private fun performRead(cmd: Byte, p1: Int?, p2: Int? = null, params: ByteArray? = null): ByteArray? {
val command: ByteArray
val os = ByteArrayOutputStream()
os.write(REQ_FLAG.toInt())
os.write(cmd.toInt())
p1?.let { os.write(p1) }
p2?.let { os.write(it) }
params?.let { os.write(params, 0, params.size) }
command = os.toByteArray()
if (!nfcV.isConnected) throw IOException("Connection lost")
val res = nfcV.transceive(command)
val errorCode = res[0].toInt()
if (errorCode != 0) {
throw IOException("Error! Code: " + String.format("0x%02x", errorCode))
}
return res.copyOfRange(1, res.size)
}
private companion object {
// iso15693 flags
const val REQ_FLAG: Byte = 0x02
const val MAX_BLOCKS_AT_ONCE = 32
}
}
sealed class SlixReadResult {
data class Success(val data: ByteArray) : SlixReadResult()
data class Failure(val exception: Exception) : SlixReadResult()
}
| 4 | Kotlin | 38 | 64 | 2ea3795fd521f23ecc6414913ab5d207c256fe84 | 4,194 | tangem-sdk-android | MIT License |
app/src/main/java/com/teampym/onlineclothingshopapplication/data/repository/LikeRepository.kt | riley0521 | 417,400,188 | false | {"Kotlin": 750594} | package com.teampym.onlineclothingshopapplication.data.repository
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.ktx.toObject
import com.teampym.onlineclothingshopapplication.data.di.IoDispatcher
import com.teampym.onlineclothingshopapplication.data.models.Like
import com.teampym.onlineclothingshopapplication.data.models.Post
import com.teampym.onlineclothingshopapplication.data.util.LIKES_SUB_COLLECTION
import com.teampym.onlineclothingshopapplication.data.util.POSTS_COLLECTION
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LikeRepository @Inject constructor(
db: FirebaseFirestore,
@IoDispatcher val dispatcher: CoroutineDispatcher
) {
private val postCollectionRef = db.collection(POSTS_COLLECTION)
suspend fun getAll(postId: String): List<Like> {
return withContext(dispatcher) {
val likeList = mutableListOf<Like>()
val likeDocuments = postCollectionRef
.document(postId)
.collection(LIKES_SUB_COLLECTION)
.get()
.await()
likeDocuments?.let { querySnapshot ->
for (doc in querySnapshot.documents) {
val like = doc.toObject<Like>()!!.copy(id = doc.id, postId = postId)
likeList.add(like)
}
}
likeList
}
}
suspend fun add(post: Post, like: Like): Boolean {
return withContext(dispatcher) {
try {
postCollectionRef
.document(post.id)
.collection(LIKES_SUB_COLLECTION)
.document(like.userId)
.set(like, SetOptions.merge())
.await()
return@withContext true
} catch (ex: java.lang.Exception) {
return@withContext false
}
}
}
suspend fun remove(postId: String, userId: String): Boolean {
return withContext(dispatcher) {
try {
postCollectionRef
.document(postId)
.collection(LIKES_SUB_COLLECTION)
.document(userId)
.delete()
.await()
return@withContext true
} catch (ex: Exception) {
return@withContext false
}
}
}
suspend fun isLikedByCurrentUser(postId: String, userId: String): Boolean {
return withContext(dispatcher) {
val result = postCollectionRef
.document(postId)
.collection(LIKES_SUB_COLLECTION)
.whereEqualTo("userId", userId)
.limit(1)
.get()
.await()
result.documents.size == 1
}
}
}
| 0 | Kotlin | 0 | 1 | 25cd6e4228fbe22e3d357d6f3ded7ca81c42202b | 3,048 | Android-Online-Ordering-for-Clothing-Shop-With-Sales-And-Inventory-Report | Apache License 2.0 |
features/library/src/main/java/com/zigis/paleontologas/features/library/stories/lifeform/LifeFormScreenState.kt | edgar-zigis | 240,962,785 | false | {"Kotlin": 268894} | package com.zigis.paleontologas.features.library.stories.lifeform
import com.zigis.paleontologas.core.architecture.interfaces.IState
data class LifeFormScreenState(
val title: String = "",
val artwork: String = "",
val artworkAuthor: String = "",
val timeScale: String = "",
val description: String = "",
val additionalArtworkAuthor: String = "",
val additionalArtwork: String = ""
) : IState | 0 | Kotlin | 16 | 123 | 1809316c012d6d0cd5a276104c4979af21ef5e7a | 422 | Paleontologas | Apache License 2.0 |
library/src/main/java/com/farmanlab/coroutinedialogfragment/CoroutineBottomSheetDialogFragment.kt | farmanlab | 183,270,610 | false | null | package com.farmanlab.coroutinedialogfragment
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
abstract class CoroutineBottomSheetDialogFragment<T> : BottomSheetDialogFragment() {
private val onAttachEventChannel = Channel<Unit>()
private val channelViewModel: ChannelDialogViewModel<T> by lazy { provideViewModel() }
/**
* You can override this property if want to use fragment scope, your factory and so on...
*/
protected open val viewModelProvider by lazy { ViewModelProvider(requireActivity()) }
@Suppress("UNCHECKED_CAST")
private fun provideViewModel(): ChannelDialogViewModel<T> =
viewModelProvider.let {
val viewModelKey = tag ?: this::class.java.simpleName
it.get(viewModelKey, ChannelDialogViewModel::class.java) as ChannelDialogViewModel<T>
}
@androidx.annotation.CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycleScope.launch { onAttachEventChannel.send(Unit) }
}
@androidx.annotation.CallSuper
override fun onCancel(dialog: DialogInterface) {
channelViewModel.channel.offer(DialogResult.Cancel)
super.onCancel(dialog)
}
suspend fun showAndResult(
fragmentManager: FragmentManager,
tag: String? = null
): DialogResult<T> {
val ft: FragmentTransaction = fragmentManager.beginTransaction()
ft.add(this, tag)
ft.commitAllowingStateLoss()
onAttachEventChannel.receive()
return channelViewModel.channel.receive()
}
suspend fun result(): DialogResult<T> = channelViewModel.channel.receive()
class ChannelDialogViewModel<T> : ViewModel() {
val channel: Channel<DialogResult<T>> = Channel()
}
}
| 0 | Kotlin | 1 | 2 | 0eba79bacae92b9cbb5e5d6a636ca85526315062 | 2,216 | coroutine-dialog-fragment | Apache License 2.0 |
app/src/main/java/com/ajce/hostelmate/FirebaseQueryLiveData.kt | Jithin-Jude | 256,905,231 | false | null | package com.ajce.hostelmate
import android.util.Log
import androidx.lifecycle.LiveData
import com.google.firebase.database.*
/**
* Created by JithinJude on 26,April,2020
*/
class FirebaseQueryLiveData : LiveData<DataSnapshot?> {
private val query: Query
private val listener = MyValueEventListener()
constructor(query: Query) {
this.query = query
}
constructor(ref: DatabaseReference) {
query = ref
}
override fun onActive() {
Log.d(LOG_TAG, "onActive")
query.addValueEventListener(listener)
}
override fun onInactive() {
Log.d(LOG_TAG, "onInactive")
query.removeEventListener(listener)
}
private inner class MyValueEventListener : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
value = dataSnapshot
}
override fun onCancelled(databaseError: DatabaseError) {
Log.e(LOG_TAG, "Can't listen to query $query", databaseError.toException())
}
}
companion object {
private const val LOG_TAG = "FirebaseQueryLiveData"
}
} | 4 | null | 1 | 1 | da95b289d6767dceec57e07718f0ad283ad1dfc4 | 1,124 | HostelMate_AJCE | MIT License |
TabStripRunner/src/jvmMain/kotlin/io/nacular/doodle/examples/main.kt | nacular | 312,752,321 | false | {"Kotlin": 282412, "MDX": 105130, "JavaScript": 9616, "CSS": 7582, "HTML": 3519} | package io.nacular.doodle.examples
import io.nacular.doodle.animation.Animator
import io.nacular.doodle.animation.AnimatorImpl
import io.nacular.doodle.application.Modules.Companion.PointerModule
import io.nacular.doodle.application.application
import io.nacular.doodle.geometry.PathMetrics
import io.nacular.doodle.geometry.impl.PathMetricsImpl
import org.kodein.di.DI
import org.kodein.di.bindSingleton
import org.kodein.di.instance
/**
* Creates a [TabStripApp]
*/
fun main() {
application(modules = listOf(PointerModule, DI.Module(name = "AppModule") {
bindSingleton<Animator> { AnimatorImpl(instance(), instance()) }
bindSingleton<PathMetrics> { PathMetricsImpl(instance()) }
})) {
// load app
TabStripApp(instance(), instance(), instance())
}
} | 0 | Kotlin | 10 | 14 | 01dff82b8ff528dcd298dba9bd9741e1a68c4ef0 | 798 | doodle-tutorials | MIT License |
app/src/main/java/com/example/android/dagger/viewModel/BookMarkFragmentViewModel.kt | anuragsingh6436 | 502,997,723 | false | null | package com.example.android.dagger.viewModel
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.android.dagger.adapter.BookMarkFragmentAdapter
import com.example.android.dagger.base.BaseRecyclerItem
import com.example.android.dagger.dataBase.DataBaseRepository
import com.example.android.dagger.event.ActivityEvent
import com.example.android.dagger.model.Event
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class BookMarkFragmentViewModel : ViewModel() {
val eventStream = MutableLiveData<Event>()
val adapter = BookMarkFragmentAdapter()
val itemsList = ObservableArrayList<BaseRecyclerItem>()
val errorText = ObservableField("")
init {
getItemsFromDb()
}
private fun getItemsFromDb() {
CoroutineScope(Dispatchers.IO).launch {
val data = DataBaseRepository.getAllBookMarkItems()
data?.forEach {
itemsList.add(BookMarkFragmentItemViewModel(it,eventStream))
} ?: kotlin.run{
errorText.set("NO BOOKMARK MOVIES")
}
}
}
fun clickOnEmptyArea() {
eventStream.postValue(Event(ActivityEvent.CLOSE_BOOK_MARK_FRAGMENT))
}
} | 0 | Kotlin | 0 | 0 | 6a015bdb5c2e0667a5365a5b8541c20c9c8af1f1 | 1,377 | androidmovie | Apache License 2.0 |
app/src/main/java/jp/juggler/subwaytooter/action/ActionUtils.kt | dengzhicheng092 | 273,178,424 | true | {"Kotlin": 2598700, "Java": 1605147, "Perl": 61230} | package jp.juggler.subwaytooter.action
import android.content.Context
import jp.juggler.subwaytooter.api.*
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.table.UserRelation
import jp.juggler.util.JsonObject
import jp.juggler.util.LogCategory
import jp.juggler.util.jsonObject
import jp.juggler.util.showToast
import java.util.*
// 疑似アカウントを作成する
// 既に存在する場合は再利用する
// 実アカウントを返すことはない
internal fun addPseudoAccount(
context : Context,
host : Host,
instanceInfo : TootInstance? = null,
callback : (SavedAccount) -> Unit
) {
try {
val acct = Acct.parse("?",host)
var account = SavedAccount.loadAccountByAcct(context, acct.ascii)
if(account != null) {
callback(account)
return
}
if(instanceInfo == null) {
TootTaskRunner(context).run(host, object : TootTask {
var targetInstance : TootInstance? = null
override fun background(client : TootApiClient) : TootApiResult? {
val (instance, instanceResult) = TootInstance.get(client)
targetInstance = instance
return instanceResult
}
override fun handleResult(result : TootApiResult?) = when {
result == null -> {
}
targetInstance == null -> showToast(context, false, result.error)
else -> addPseudoAccount(context, host, targetInstance, callback)
}
})
return
}
val account_info = jsonObject {
put("username", acct.username)
put("acct", acct.username) // ローカルから参照した場合なのでshort acct
}
val row_id = SavedAccount.insert(
host.ascii,
acct.ascii,
account_info,
JsonObject(),
misskeyVersion = instanceInfo.misskeyVersion
)
account = SavedAccount.loadAccount(context, row_id)
if(account == null) {
throw RuntimeException("loadAccount returns null.")
}
account.notification_follow = false
account.notification_follow_request = false
account.notification_favourite = false
account.notification_boost = false
account.notification_mention = false
account.notification_reaction = false
account.notification_vote = false
account.saveSetting()
callback(account)
return
} catch(ex : Throwable) {
val log = LogCategory("addPseudoAccount")
log.trace(ex)
log.e(ex, "failed.")
showToast(context, ex, "addPseudoAccount failed.")
}
return
}
// 疑似アカ以外のアカウントのリスト
fun makeAccountListNonPseudo(
context : Context, pickup_host : Host?
) : ArrayList<SavedAccount> {
val list_same_host = ArrayList<SavedAccount>()
val list_other_host = ArrayList<SavedAccount>()
for(a in SavedAccount.loadAccountList(context)) {
if(a.isPseudo) continue
when(pickup_host) {
null, a.host -> list_same_host
else -> list_other_host
}.add(a)
}
SavedAccount.sort(list_same_host)
SavedAccount.sort(list_other_host)
list_same_host.addAll(list_other_host)
return list_same_host
}
internal fun saveUserRelation(access_info : SavedAccount, src : TootRelationShip?) : UserRelation? {
src ?: return null
val now = System.currentTimeMillis()
return UserRelation.save1Mastodon(now, access_info.db_id, src)
}
internal fun saveUserRelationMisskey(
access_info : SavedAccount,
whoId : EntityId,
parser : TootParser
) : UserRelation? {
val now = System.currentTimeMillis()
val relation = parser.getMisskeyUserRelation(whoId)
UserRelation.save1Misskey(now, access_info.db_id, whoId.toString(), relation)
return relation
}
//// relationshipを取得
//internal fun loadRelation1Mastodon(
// client : TootApiClient,
// access_info : SavedAccount,
// who : TootAccount
//) : RelationResult {
// val rr = RelationResult()
// rr.result = client.request("/api/v1/accounts/relationships?id=${who.id}")
// val r2 = rr.result
// val jsonArray = r2?.jsonArray
// if(jsonArray != null) {
// val list = parseList(::TootRelationShip, TootParser(client.context, access_info), jsonArray)
// if(list.isNotEmpty()) {
// rr.relation = saveUserRelation(access_info, list[0])
// }
// }
// return rr
//}
// 別アカ操作と別タンスの関係
const val NOT_CROSS_ACCOUNT = 1
const val CROSS_ACCOUNT_SAME_INSTANCE = 2
const val CROSS_ACCOUNT_REMOTE_INSTANCE = 3
internal fun calcCrossAccountMode(
timeline_account : SavedAccount,
action_account : SavedAccount
) : Int = when {
timeline_account == action_account -> NOT_CROSS_ACCOUNT
timeline_account.matchHost(action_account.host) -> CROSS_ACCOUNT_SAME_INSTANCE
else -> CROSS_ACCOUNT_REMOTE_INSTANCE
}
| 0 | null | 0 | 0 | c03a5ff731b6056e7fafec4b07e00733eeda02da | 4,392 | SubwayTooter | Apache License 2.0 |
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/FrontendBackendHost.kt | JetBrains | 42,181,594 | false | {"C#": 5052738, "Kotlin": 759241, "ShaderLab": 89447, "Lex": 36667, "GLSL": 15101, "Batchfile": 8565, "PowerShell": 1523, "Shell": 163} | package com.jetbrains.rider.plugins.unity
import com.intellij.execution.ProgramRunnerUtil
import com.intellij.execution.RunManager
import com.intellij.execution.executors.DefaultDebugExecutor
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.wm.WindowManager
import com.intellij.util.BitUtil
import com.intellij.xdebugger.XDebuggerManager
import com.jetbrains.rd.framework.impl.RdTask
import com.jetbrains.rd.platform.util.idea.ProtocolSubscribedProjectComponent
import com.jetbrains.rd.util.reactive.AddRemove
import com.jetbrains.rd.util.reactive.Signal
import com.jetbrains.rd.util.reactive.adviseNotNull
import com.jetbrains.rd.util.reactive.valueOrDefault
import com.jetbrains.rider.debugger.DebuggerInitializingState
import com.jetbrains.rider.debugger.RiderDebugActiveDotNetSessionsTracker
import com.jetbrains.rider.plugins.unity.actions.StartUnityAction
import com.jetbrains.rider.plugins.unity.model.LogEvent
import com.jetbrains.rider.plugins.unity.model.frontendBackend.frontendBackendModel
import com.jetbrains.rider.plugins.unity.run.DefaultRunConfigurationGenerator
import com.jetbrains.rider.plugins.unity.run.UnityRemoteConnectionDetails
import com.jetbrains.rider.plugins.unity.run.configurations.UnityAttachToEditorRunConfiguration
import com.jetbrains.rider.plugins.unity.run.configurations.UnityDebugConfigurationType
import com.jetbrains.rider.plugins.unity.run.configurations.UnityProcessRunProfile
import com.jetbrains.rider.plugins.unity.run.configurations.unityExe.UnityExeConfiguration
import com.jetbrains.rider.plugins.unity.util.UnityInstallationFinder
import com.jetbrains.rider.plugins.unity.util.Utils.Companion.AllowUnitySetForegroundWindow
import com.jetbrains.rider.plugins.unity.util.toProgramParameters
import com.jetbrains.rider.plugins.unity.util.withProjectPath
import com.jetbrains.rider.projectView.solution
import java.awt.Frame
import java.io.File
import kotlin.math.max
class FrontendBackendHost(project: Project) : ProtocolSubscribedProjectComponent(project) {
val model = project.solution.frontendBackendModel
val logSignal = Signal<LogEvent>()
init {
model.activateRider.advise(projectComponentLifetime) {
activateRider()
}
model.consoleLogging.onConsoleLogEvent.adviseNotNull(projectComponentLifetime) {
logSignal.fire(it)
}
model.startUnity.advise(projectComponentLifetime) {
StartUnityAction.startUnity(project)
}
model.attachDebuggerToUnityEditor.set { lt, _ ->
val sessions = XDebuggerManager.getInstance(project).debugSessions
val task = RdTask<Boolean>()
val configuration =
RunManager.getInstance(project).findConfigurationByTypeAndName(UnityDebugConfigurationType.id, DefaultRunConfigurationGenerator.ATTACH_CONFIGURATION_NAME)
if (configuration == null)
{
task.set(false)
return@set task
}
val unityAttachConfiguration = configuration.configuration as UnityAttachToEditorRunConfiguration
unityAttachConfiguration.updatePidAndPort()
val isAttached = sessions.any {
if (it.runProfile == null) return@any false
if (it.runProfile is UnityAttachToEditorRunConfiguration) {
return@any (it.runProfile as UnityAttachToEditorRunConfiguration).pid == unityAttachConfiguration.pid
}
if (it.runProfile is UnityProcessRunProfile) {
return@any ((it.runProfile as UnityProcessRunProfile).process as UnityRemoteConnectionDetails).port == unityAttachConfiguration.port
}
if (it.runProfile is UnityExeConfiguration) {
val params = (it.runProfile as UnityExeConfiguration).parameters
val unityPath = UnityInstallationFinder.getInstance(project).getApplicationExecutablePath()
return@any File(params.exePath) == unityPath?.toFile() && params.programParameters.contains(
mutableListOf<String>().withProjectPath(project).toProgramParameters()
)
}
return@any false
}
if (!isAttached) {
val processTracker: RiderDebugActiveDotNetSessionsTracker = RiderDebugActiveDotNetSessionsTracker.getInstance(project)
processTracker.dotNetDebugProcesses.change.advise(projectComponentLifetime) { (event, debugProcess) ->
if (event == AddRemove.Add) {
debugProcess.initializeDebuggerTask.debuggerInitializingState.advise(lt) {
if (it == DebuggerInitializingState.Initialized)
task.set(true)
if (it == DebuggerInitializingState.Canceled)
task.set(false)
}
}
}
ProgramRunnerUtil.executeConfiguration(configuration, DefaultDebugExecutor.getDebugExecutorInstance())
} else task.set(true)
task
}
model.allowSetForegroundWindow.set { _, _ ->
val task = RdTask<Boolean>()
val id = model.unityApplicationData.valueOrNull?.unityProcessId
if (id == null)
task.set(false)
else
task.set(AllowUnitySetForegroundWindow(id))
task
}
model.openFileLineCol.set { _, arg ->
val manager = FileEditorManager.getInstance(project)
val file = VfsUtil.findFileByIoFile(File(arg.path), true) ?: return@set RdTask.fromResult(false)
manager.openEditor(OpenFileDescriptor(project, file, max(0, arg.line - 1), max(0, arg.col - 1)), true)
activateRider()
RdTask.fromResult(true)
}
}
companion object {
fun getInstance(project: Project): FrontendBackendHost = project.getComponent(FrontendBackendHost::class.java)
}
private fun activateRider() {
ProjectUtil.focusProjectWindow(project, true)
val frame = WindowManager.getInstance().getFrame(project)
if (frame != null) {
if (BitUtil.isSet(frame.extendedState, Frame.ICONIFIED))
frame.extendedState = BitUtil.set(frame.extendedState, Frame.ICONIFIED, false)
}
}
}
fun Project?.isConnectedToEditor() = this != null && this.solution.frontendBackendModel.unityEditorConnected.valueOrDefault(false) | 271 | C# | 139 | 1,179 | 3f57a1b9ce1894573605e7af96cac09d24f44ef6 | 6,802 | resharper-unity | Apache License 2.0 |
BindingDemo/app/src/main/java/com/example/bindingdemo/MainActivity.kt | Android-SrB-2020 | 232,621,348 | false | null | package com.example.bindingdemo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import androidx.databinding.DataBindingUtil
import com.example.bindingdemo.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
var name = "Dave"
var salutation: Int = R.string.sal_1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
salutation = savedInstanceState?.getInt("SAL", 0)?: salutation
// setContentView(R.layout.activity_main)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
binding.mainActivity = this
binding.doitButton.setOnClickListener{
salutation = when (salutation){
R.string.sal_1 -> R.string.sal_2
R.string.sal_2 -> R.string.sal_3
else -> R.string.sal_1
}
//refresh the binding
binding.invalidateAll()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("SAL", salutation)
}
}
| 0 | Kotlin | 0 | 0 | 319447a2d858842379bc9c70ead875a9e4cf64f9 | 1,229 | homework-BenJokela | MIT License |
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsVirusBlock.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.boxicons.boxicons.solid
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup
public val SolidGroup.BxsVirusBlock: ImageVector
get() {
if (_bxsVirusBlock != null) {
return _bxsVirusBlock!!
}
_bxsVirusBlock = Builder(name = "BxsVirusBlock", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.952f, 17.538f)
curveToRelative(-0.749f, -0.749f, -0.908f, -1.869f, -0.5f, -2.846f)
lineToRelative(0.021f, -0.049f)
curveToRelative(0.399f, -0.974f, 1.309f, -1.643f, 2.362f, -1.643f)
horizontalLineToRelative(0.08f)
curveToRelative(0.638f, 0.0f, 1.085f, -0.447f, 1.085f, -1.0f)
reflectiveCurveToRelative(-0.447f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-0.17f)
curveToRelative(-1.053f, 0.0f, -1.958f, -0.669f, -2.357f, -1.644f)
lineToRelative(-0.021f, -0.049f)
curveToRelative(-0.408f, -0.977f, -0.249f, -2.097f, 0.5f, -2.846f)
lineToRelative(0.119f, -0.119f)
arcToRelative(0.999f, 0.999f, 0.0f, true, false, -1.414f, -1.414f)
lineToRelative(-0.119f, 0.119f)
curveToRelative(-0.749f, 0.749f, -1.869f, 0.908f, -2.846f, 0.5f)
lineToRelative(-0.049f, -0.021f)
curveTo(13.669f, 5.128f, 13.0f, 4.218f, 13.0f, 3.165f)
verticalLineToRelative(-0.081f)
curveTo(13.0f, 2.447f, 12.553f, 2.0f, 12.0f, 2.0f)
reflectiveCurveToRelative(-1.0f, 0.447f, -1.0f, 1.0f)
verticalLineToRelative(0.036f)
curveToRelative(0.0f, 1.096f, -0.66f, 2.084f, -1.673f, 2.503f)
lineToRelative(-0.006f, 0.003f)
arcToRelative(2.71f, 2.71f, 0.0f, false, true, -2.953f, -0.588f)
lineToRelative(-0.025f, -0.025f)
lineToRelative(-2.636f, -2.636f)
lineToRelative(-1.414f, 1.414f)
lineToRelative(18.0f, 18.0f)
lineToRelative(1.414f, -1.414f)
lineToRelative(-2.636f, -2.636f)
lineToRelative(-0.119f, -0.119f)
close()
moveTo(12.0f, 10.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, true, 2.0f, 2.0f)
curveToRelative(-0.257f, 0.0f, -0.501f, -0.053f, -0.728f, -0.142f)
lineToRelative(-1.131f, -1.131f)
arcTo(1.998f, 1.998f, 0.0f, false, true, 12.0f, 10.0f)
close()
moveTo(8.0f, 13.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
arcToRelative(0.99f, 0.99f, 0.0f, false, true, 0.244f, -0.635f)
lineTo(5.431f, 9.552f)
arcTo(2.634f, 2.634f, 0.0f, false, true, 3.085f, 11.0f)
horizontalLineToRelative(-0.001f)
curveTo(2.447f, 11.0f, 2.0f, 11.447f, 2.0f, 12.0f)
reflectiveCurveToRelative(0.447f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(0.068f)
arcToRelative(2.66f, 2.66f, 0.0f, false, true, 2.459f, 1.644f)
lineToRelative(0.021f, 0.049f)
arcToRelative(2.69f, 2.69f, 0.0f, false, true, -0.583f, 2.929f)
lineToRelative(-0.036f, 0.036f)
arcToRelative(0.999f, 0.999f, 0.0f, true, false, 1.414f, 1.414f)
lineToRelative(0.036f, -0.036f)
arcToRelative(2.689f, 2.689f, 0.0f, false, true, 2.929f, -0.583f)
lineToRelative(0.143f, 0.06f)
arcTo(2.505f, 2.505f, 0.0f, false, true, 11.0f, 20.83f)
verticalLineToRelative(0.085f)
curveToRelative(0.0f, 0.638f, 0.447f, 1.085f, 1.0f, 1.085f)
reflectiveCurveToRelative(1.0f, -0.448f, 1.0f, -1.0f)
verticalLineToRelative(-0.17f)
curveToRelative(0.0f, -0.976f, 0.568f, -1.853f, 1.443f, -2.266f)
lineToRelative(-5.809f, -5.809f)
arcTo(0.98f, 0.98f, 0.0f, false, true, 8.0f, 13.0f)
close()
}
}
.build()
return _bxsVirusBlock!!
}
private var _bxsVirusBlock: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 5,119 | compose-icon-collections | MIT License |
feature/search/src/main/kotlin/com/seosh817/moviehub/feature/search/SearchUiEvent.kt | seosh817 | 722,390,551 | false | {"Kotlin": 471373} | /*
* Copyright 2024 seosh817 (<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
*
* 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.seosh817.moviehub.feature.search
import com.seosh817.moviehub.core.model.UserMovie
sealed interface SearchUiEvent {
data class OnQueryChanged(val query: String) : SearchUiEvent
data object ClearSearchQuery : SearchUiEvent
data class OnBookmarkClick(val userMovie: UserMovie, val isBookmark: Boolean) : SearchUiEvent
data class ShowBookmarkedMessage(val isBookmarked: Boolean, val id: Long) : SearchUiEvent
}
| 12 | Kotlin | 0 | 3 | fde7db89417954c4fc4a776222f6c23da3d4bc98 | 1,044 | MovieHub | Apache License 2.0 |
libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/join/DefaultJoinRoom.kt | element-hq | 546,522,002 | false | {"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44} | /*
* Copyright (c) 2024 New Vector 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 io.element.android.libraries.matrix.impl.room.join
import com.squareup.anvil.annotations.ContributesBinding
import im.vector.app.features.analytics.plan.JoinedRoom
import io.element.android.libraries.di.SessionScope
import io.element.android.libraries.matrix.api.MatrixClient
import io.element.android.libraries.matrix.api.core.RoomIdOrAlias
import io.element.android.libraries.matrix.api.room.join.JoinRoom
import io.element.android.libraries.matrix.api.roomlist.RoomSummary
import io.element.android.libraries.matrix.impl.analytics.toAnalyticsJoinedRoom
import io.element.android.services.analytics.api.AnalyticsService
import javax.inject.Inject
@ContributesBinding(SessionScope::class)
class DefaultJoinRoom @Inject constructor(
private val client: MatrixClient,
private val analyticsService: AnalyticsService,
) : JoinRoom {
override suspend fun invoke(
roomIdOrAlias: RoomIdOrAlias,
serverNames: List<String>,
trigger: JoinedRoom.Trigger
): Result<Unit> {
return when (roomIdOrAlias) {
is RoomIdOrAlias.Id -> {
if (serverNames.isEmpty()) {
client.joinRoom(roomIdOrAlias.roomId)
} else {
client.joinRoomByIdOrAlias(roomIdOrAlias, serverNames)
}
}
is RoomIdOrAlias.Alias -> {
client.joinRoomByIdOrAlias(roomIdOrAlias, serverNames = emptyList())
}
}.onSuccess { roomSummary ->
client.captureJoinedRoomAnalytics(roomSummary, trigger)
}.map { }
}
private suspend fun MatrixClient.captureJoinedRoomAnalytics(roomSummary: RoomSummary?, trigger: JoinedRoom.Trigger) {
if (roomSummary == null) return
getRoom(roomSummary.roomId)?.use { room ->
analyticsService.capture(room.toAnalyticsJoinedRoom(trigger))
}
}
}
| 263 | Kotlin | 129 | 955 | 31d0621fa15fe153bfd36104e560c9703eabe917 | 2,499 | element-x-android | Apache License 2.0 |
ledger/src/main/kotlin/org/knowledger/ledger/service/pools/transaction/SUTransactionPoolStorageAdapter.kt | fakecoinbase | 282,563,487 | false | null | package org.knowledger.ledger.service.pools.transaction
import org.knowledger.ledger.adapters.AdapterManager
import org.knowledger.ledger.config.adapters.ChainIdStorageAdapter
import org.knowledger.ledger.crypto.Hash
import org.knowledger.ledger.database.ManagedSession
import org.knowledger.ledger.database.StorageElement
import org.knowledger.ledger.database.StorageType
import org.knowledger.ledger.results.Outcome
import org.knowledger.ledger.results.allValues
import org.knowledger.ledger.results.tryOrLedgerUnknownFailure
import org.knowledger.ledger.results.zip
import org.knowledger.ledger.service.adapters.PoolTransactionStorageAdapter
import org.knowledger.ledger.service.adapters.ServiceStorageAdapter
import org.knowledger.ledger.service.results.LedgerFailure
internal class SUTransactionPoolStorageAdapter(
private val adapterManager: AdapterManager,
private val poolTransactionStorageAdapter: PoolTransactionStorageAdapter
) : ServiceStorageAdapter<TransactionPoolImpl> {
override val id: String
get() = "TransactionPool"
override val properties: Map<String, StorageType>
get() = mapOf(
"chainId" to StorageType.LINK,
"transactions" to StorageType.SET
)
override fun store(
toStore: TransactionPoolImpl,
session: ManagedSession
): StorageElement =
session
.newInstance(id)
.setLinked(
"chainId",
ChainIdStorageAdapter.persist(
toStore.chainId, session
)
).setElementSet(
"transactions",
toStore.transactions.map {
poolTransactionStorageAdapter.persist(
it, session
)
}.toSet()
)
@Suppress("NAME_SHADOWING")
override fun load(
ledgerHash: Hash,
element: StorageElement
): Outcome<TransactionPoolImpl, LedgerFailure> =
tryOrLedgerUnknownFailure {
val chainId = element.getLinked("chainId")
val transactions = element.getElementSet("transactions")
zip(
ChainIdStorageAdapter.load(
ledgerHash, chainId
),
transactions.map {
poolTransactionStorageAdapter.load(
ledgerHash,
it
)
}.allValues()
) { chainId, transactions ->
TransactionPoolImpl(
adapterManager,
chainId,
transactions.toMutableSet()
)
}
}
} | 0 | Kotlin | 0 | 0 | 8bc64987e1ab4d26663064da06393de6befc30ae | 2,709 | SeriyinslashKnowLedger | MIT License |
rest/src/main/kotlin/builder/channel/ChannelPermissionModifyBuilder.kt | jombidev | 507,000,315 | false | {"Kotlin": 2022642, "Java": 87103} | package dev.jombi.kordsb.rest.builder.channel
import dev.jombi.kordsb.common.annotation.KordDsl
import dev.jombi.kordsb.common.entity.OverwriteType
import dev.jombi.kordsb.common.entity.Permissions
import dev.jombi.kordsb.rest.builder.AuditRequestBuilder
import dev.jombi.kordsb.rest.json.request.ChannelPermissionEditRequest
@KordDsl
public class ChannelPermissionModifyBuilder(private var type: OverwriteType) :
AuditRequestBuilder<ChannelPermissionEditRequest> {
override var reason: String? = null
/**
* The permissions that are explicitly allowed for this channel.
*/
public var allowed: Permissions = Permissions()
/**
* The permissions that are explicitly denied for this channel.
*/
public var denied: Permissions = Permissions()
override fun toRequest(): ChannelPermissionEditRequest = ChannelPermissionEditRequest(allowed, denied, type)
}
| 0 | Kotlin | 0 | 4 | 7e4eba1e65e5454e5c9400da83bd2de883acf96d | 904 | kord-selfbot | MIT License |
app/src/main/java/com/example/android/unscramble/ui/game/GameViewModel.kt | joelimyx | 471,431,387 | false | {"Kotlin": 11553} | package com.example.android.unscramble.ui.game
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class GameViewModel : ViewModel() {
private val _score = MutableLiveData(0)
val score: LiveData<Int>
get() = _score
private val _currentWordCount = MutableLiveData(0)
val currentWordCount: LiveData<Int>
get() = _currentWordCount
private val _currentScrambledWord = MutableLiveData<String>()
val currentScrambledWord: LiveData<String>
get() = _currentScrambledWord
private var wordList: MutableList<String> = mutableListOf()
private lateinit var currentWord: String
init {
Log.i("GameViewModel", "ViewModel Created")
getNextWord()
}
private fun getNextWord() {
currentWord = allWordsList.random()
val tempChar = currentWord.toCharArray()
while (String(tempChar).equals(currentWord, false))
tempChar.shuffle()
if(wordList.contains(currentWord)) {
getNextWord()
}
else{
_currentScrambledWord.value = String(tempChar)
_currentWordCount.value = (_currentWordCount.value)?.inc()
wordList.add(currentWord)
Log.d("getNextWord", "Value: $currentWordCount")
}
}
fun nextWord(): Boolean {
return if (_currentWordCount.value!! < MAX_NO_OF_WORDS) {
getNextWord()
true
}else false
}
fun isUserWordCorrect(playerWord: String): Boolean {
if (playerWord.equals(currentWord,true)){
increaseScore()
return true
}
return false
}
private fun increaseScore() {
_score.value = (_score.value)?.plus(SCORE_INCREASE)
}
fun reinitializeData() {
_score.value = 0
_currentWordCount.value = 0
wordList.clear()
getNextWord()
}
} | 0 | Kotlin | 0 | 0 | 02f50aeb61d69667a9ca580502250b92275a2b00 | 1,967 | abk-unscramble | Apache License 2.0 |
app/src/androidTest/java/com/fanstaticapps/randomticker/ui/main/RunningTickerAndroidTest.kt | carvaq | 300,246,718 | false | null | package com.fanstaticapps.randomticker.ui.main
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.rules.activityScenarioRule
import com.fanstaticapps.randomticker.R
import com.fanstaticapps.randomticker.TickerPreferences
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import javax.inject.Inject
@HiltAndroidTest
class RunningTickerAndroidTest {
private val hiltRule = HiltAndroidRule(this)
@get:Rule
val rule: RuleChain = RuleChain.outerRule(hiltRule)
.around(activityScenarioRule<MainActivity>())
@Inject
lateinit var tickerPreferences: TickerPreferences
@Before
fun setUp() {
hiltRule.inject()
tickerPreferences.setTickerInterval(40000)
}
@Test
fun testThatIfTickerIsRunningGoToKlaxon() {
onView(withId(R.id.btnDismiss)).perform(scrollTo(), click())
}
}
| 0 | Kotlin | 0 | 1 | 5641fcca92e5bf4fc04b2b872cb115c1933cf0ca | 1,192 | random-ticker | Apache License 2.0 |
common/src/main/kotlin/studio/forface/ktmdb/utils/string.kt | 4face-studi0 | 154,903,789 | false | null | package studio.forface.ktmdb.utils
/* Author: <NAME> */
/** En empty [String] "" */
internal const val EMPTY_STRING = "" | 0 | Kotlin | 0 | 3 | bfcba0cc37a22aef54ecb3f65334dcceb84dbc4f | 122 | KTmdb | Apache License 2.0 |
app/src/main/java/com/example/todoapp/ui/todolist/recyclerview/TodoItemsAdapter.kt | Mobile-Developement-School-23 | 652,254,012 | false | null | package com.example.todoapp.ui.todolist.recyclerview
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.example.todoapp.data.model.TodoItem
import com.example.todoapp.databinding.TodoItemBinding
/**
* Adapter class for displaying a list of todoItems in a RecyclerView.
*
*/
class TodoItemsAdapter(
private val callbacks: TodoItemChangeCallbacks
) : ListAdapter<TodoItem, TodoItemViewHolder>(DiffUtilCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = TodoItemBinding.inflate(inflater, parent, false)
return TodoItemViewHolder(binding, callbacks)
}
override fun onBindViewHolder(holder: TodoItemViewHolder, position: Int) {
val todoItem = getItem(position)
holder.onBind(todoItem, position)
}
override fun getItemId(position: Int): Long {
return getItem(position).id.toLong()
}
}
| 0 | Kotlin | 0 | 0 | 27bbeb03445d18f0026b1b56bbba87118d14b488 | 1,051 | android-todo-app-rakhmukova | Apache License 2.0 |
src/test/kotlin/Day04Test.kt | robert-iits | 573,124,643 | false | {"Kotlin": 21047} | import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
internal class Day04Test {
private val sut = Day04()
@ParameterizedTest
@MethodSource("fullOverlapInput")
fun countFullOverlap(range1: IntRange, range2: IntRange, expected: Int) {
sut.countFullOverlap(range1, range2) shouldBe expected
}
@ParameterizedTest
@MethodSource("overlapInput")
fun isOverlap(range1: IntRange, range2: IntRange, expected: Int) {
sut.countOverlap(range1, range2) shouldBe expected
}
private val testInput = listOf(
"2-4,6-8",
"2-3,4-5",
"5-7,7-9",
"2-8,3-7",
"6-6,4-6",
"2-6,4-8",
)
@Test
fun part1() {
sut.part1(testInput) shouldBe 2
}
@Test
fun part2() {
sut.part2(testInput) shouldBe 4
}
companion object {
@JvmStatic
private fun fullOverlapInput(): Stream<Arguments> {
return Stream.of(
Arguments.of(1..3, 1..5, 1),
Arguments.of(3..5, 4..6, 0),
Arguments.of(1..3, 4..6, 0),
Arguments.of(5..6, 4..7, 1),
Arguments.of(4..6, 4..7, 1),
)
}
@JvmStatic
private fun overlapInput(): Stream<Arguments> {
return Stream.of(
Arguments.of(1..3, 1..5, 1),
Arguments.of(3..5, 4..6, 1),
Arguments.of(1..3, 4..6, 0),
Arguments.of(5..6, 4..7, 1),
Arguments.of(4..6, 4..7, 1),
Arguments.of(4..6, 1..2, 0),
)
}
}
} | 0 | Kotlin | 0 | 0 | 223017895e483a762d8aa2cdde6d597ab9256b2d | 1,855 | aoc2022 | Apache License 2.0 |
app/src/main/java/com/madurasoftware/vmble/Receiver.kt | RogerParkinson | 286,349,900 | false | null | package com.madurasoftware.vmble
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.util.Log
class Receiver : BroadcastReceiver() {
private var handler: Handler? = null
private val TAG = "Receiver"
fun setHandler(handler: Handler) {
this.handler = handler
}
private fun getHandler():Handler {
return handler!!
}
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive ${intent.extras}")
val status = intent.extras!!.getInt(BLEService.CONNECTION_STATUS,-100)
val info = intent.extras!!.getString(CONNECTION_INFO,"")
Log.d(TAG, "onReceive $status $info")
getHandler().obtainMessage(CONNECTING_STATUS, status, -1, info)
.sendToTarget()
}
} | 0 | Kotlin | 0 | 0 | 636e912cce01bebff2f1f36461b6384c6eae3041 | 859 | VMBLE | Apache License 2.0 |
src/test/kotlin/com/akagiyui/common/delegate/LoggerDelegateTests.kt | AkagiYui | 647,653,830 | false | {"Kotlin": 211788, "HTML": 1003, "Dockerfile": 654} | package com.akagiyui.common.delegate
import org.junit.jupiter.api.Test
/**
* Logger 委托测试
*
* @author AkagiYui
*/
class LoggerDelegateTests {
private val logger by LoggerDelegate()
@Test
fun testLoggerDelegate() {
logger.info("test logger delegate")
}
}
| 3 | Kotlin | 1 | 8 | c36962a4242649b6aa3bfe25db47b03e6b36bd8e | 284 | KenkoDrive | MIT License |
app/src/main/java/eu/caraus/home24/application/ui/main/selection/SelectionInteractor.kt | alexandrucaraus | 143,283,559 | false | null | package eu.caraus.home24.application.ui.main.selection
import eu.caraus.dynamo.application.common.retrofit.Outcome
import eu.caraus.home24.application.common.extensions.*
import eu.caraus.home24.application.common.schedulers.SchedulerProvider
import eu.caraus.home24.application.data.domain.home24.ArticlesItem
import eu.caraus.home24.application.data.remote.home24.Home24Api
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
/**
* SelectionInteractor - this class queries the Home24Api service,
* and the publishes requested data down the pipe
*
*/
class SelectionInteractor( private val home24Api : Home24Api ,
private val scheduler : SchedulerProvider,
private val compositeDisposable: CompositeDisposable) : SelectionContract.Interactor {
private val dataFetchResult = PublishSubject.create<Outcome<List<ArticlesItem?>>>()
private var offset = 0
private var limit = 10
override fun getArticles() {
dataFetchResult.loading(true )
home24Api.getArticles( offset , limit ).subOnIoObsOnUi( scheduler ).subscribe(
{
it.embedded?.articles?.let {
offset = limit ; limit += limit
dataFetchResult.success( it )
}
},
{
dataFetchResult.failed( it )
}
).addTo( compositeDisposable )
}
override fun getArticles( numberOfArticles: Int ) {
dataFetchResult.loading(true )
home24Api.getArticles( 0 , numberOfArticles ).subOnIoObsOnUi( scheduler).subscribe(
{
it.embedded?.articles?.let {
dataFetchResult.success( it )
}
},
{
dataFetchResult.failed( it )
}
).addTo( compositeDisposable )
}
override fun getArticlesOutcome() : PublishSubject<Outcome<List<ArticlesItem?>>>{
return dataFetchResult
}
} | 0 | Kotlin | 0 | 0 | 51ca5bd6ea34fa2dcceb79653824263e94ba626c | 2,119 | Home24LikeMvp | MIT License |
core/src/main/kotlin/ru/mobileup/template/core/utils/BackPressedUtils.kt | MobileUpLLC | 485,284,340 | false | null | package ru.mobileup.template.core.utils
import android.content.Context
import android.content.ContextWrapper
import androidx.activity.ComponentActivity
/**
* Should be used to handle clicks on toolbar back button.
*
* Usage:
* val context = LocalContext.current
* ...
* onClick = {
* dispatchOnBackPressed(context)
* }
*/
fun dispatchOnBackPressed(context: Context) {
val activity = context.getActivity() ?: return
activity.onBackPressedDispatcher.onBackPressed()
}
private fun Context.getActivity(): ComponentActivity? = when (this) {
is ComponentActivity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
} | 0 | Kotlin | 0 | 8 | 75c3350979d4d2a92d8b685194b80ef3747201e9 | 662 | MobileUp-Android-Template | MIT License |
app/src/main/java/dev/thiaago/finn/core/ui/components/DatePickerInput.kt | thiaagodev | 683,539,394 | false | {"Kotlin": 97147} | package dev.thiaago.finn.core.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import dev.thiaago.finn.core.extensions.toBrazilianDateFormat
import java.util.Date
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DatePickerInput(onDateSelected: (date: Date) -> Unit) {
var openDateDialog by remember {
mutableStateOf(false)
}
val showClearIcon by remember {
mutableStateOf(false)
}
var date by remember {
mutableStateOf(Date().time.toBrazilianDateFormat())
}
BasicTextField(
modifier = Modifier
.wrapContentWidth()
.defaultMinSize(minWidth = 250.dp)
.clickable { openDateDialog = true },
value = date,
onValueChange = {},
maxLines = 1,
singleLine = true,
enabled = false
) {
OutlinedTextFieldDefaults.DecorationBox(
value = date,
innerTextField = it,
enabled = true,
singleLine = true,
placeholder = {
Text(
text = "Data",
style = TextStyle(
fontSize = 14.sp,
color = Color.Gray
),
)
},
contentPadding = PaddingValues(12.dp),
visualTransformation = VisualTransformation.None,
trailingIcon = {
if (showClearIcon && date.isNotEmpty()) {
Icon(
modifier = Modifier.clickable {
date = ""
},
imageVector = Icons.Default.Close,
contentDescription = "Limpar"
)
}
},
interactionSource = remember {
MutableInteractionSource()
}
)
}
val dateState = rememberDatePickerState()
if (openDateDialog) {
DatePickerDialog(
onDismissRequest = {
openDateDialog = false
},
confirmButton = {
TextButton(
onClick = {
dateState.selectedDateMillis?.let {
date = it.toBrazilianDateFormat()
onDateSelected(Date(it))
}
openDateDialog = false
}
) {
Text("OK")
}
}
) {
DatePicker(state = dateState)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
private fun DatePickerInputPreview() {
DatePickerInput(onDateSelected = {})
} | 0 | Kotlin | 0 | 2 | 73c5db63d337a8bc6ba2c1733ea44cfa6e68f48d | 4,052 | Finn | Creative Commons Attribution 4.0 International |
client/src/main/kotlin/io/github/matrixkt/utils/resource/ResourceFormat.kt | Dominaezzz | 205,671,029 | false | null | package io.github.matrixkt.utils.resource
import io.ktor.http.*
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.StructureKind
import kotlinx.serialization.descriptors.elementDescriptors
import kotlinx.serialization.descriptors.elementNames
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
@OptIn(ExperimentalSerializationApi::class)
public object ResourcesFormat : SerialFormat {
override val serializersModule: SerializersModule get() = EmptySerializersModule
public data class Parameter(
val name: String,
val isOptional: Boolean
)
public fun <T> encodeToPathPattern(serializer: SerializationStrategy<T>): String {
val pathBuilder = StringBuilder()
var current: SerialDescriptor? = serializer.descriptor
while (current != null) {
val path = current.annotations.filterIsInstance<Resource>().first().path
val addSlash = pathBuilder.isNotEmpty() && !pathBuilder.startsWith('/') && !path.endsWith('/')
if (addSlash) {
pathBuilder.insert(0, '/')
}
pathBuilder.insert(0, path)
val membersWithAnnotations = current.elementDescriptors.filter { it.annotations.any { it is Resource } }
check(membersWithAnnotations.size <= 1) {
"There are multiple parents for resource ${current!!.serialName}"
}
current = membersWithAnnotations.firstOrNull()
}
if (pathBuilder.startsWith('/')) {
pathBuilder.deleteAt(0)
}
return pathBuilder.toString()
}
public fun <T> encodeToQueryParameters(serializer: SerializationStrategy<T>): Set<Parameter> {
val path = encodeToPathPattern(serializer)
val allParameters = mutableSetOf<Parameter>()
collectAllParameters(serializer.descriptor, allParameters)
return allParameters
.filterNot { (name, _) ->
path.contains("{$name}") || path.contains("{$name?}") || path.contains("{$name...}")
}
.toSet()
}
private fun collectAllParameters(descriptor: SerialDescriptor, result: MutableSet<Parameter>) {
descriptor.elementNames.forEach { name ->
val index = descriptor.getElementIndex(name)
val elementDescriptor = descriptor.getElementDescriptor(index)
if (elementDescriptor.kind is StructureKind.CLASS) {
collectAllParameters(elementDescriptor, result)
} else {
result.add(Parameter(name, descriptor.isElementOptional(index)))
}
}
}
public fun <T> encodeToParameters(serializer: SerializationStrategy<T>, value: T): Parameters {
val encoder = ParametersEncoder(serializersModule)
encoder.encodeSerializableValue(serializer, value)
return encoder.parameters
}
public fun <T> decodeFromParameters(deserializer: DeserializationStrategy<T>, parameters: Parameters): T {
val input = ParametersDecoder(serializersModule, parameters, emptyList())
return input.decodeSerializableValue(deserializer)
}
}
| 1 | Kotlin | 6 | 25 | fa3d95f1d4bcdbc38fead6a662bbe9bd6de27a0c | 3,276 | matrix-kt | Apache License 2.0 |
urbanairship-automation/src/test/java/com/urbanairship/automation/remotedata/AutomationRemoteDataAccessTest.kt | urbanairship | 58,972,818 | false | {"Kotlin": 3266979, "Java": 2582150, "Python": 10137, "Shell": 589} | package com.urbanairship.automation.remotedata
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.urbanairship.TestClock
import com.urbanairship.automation.AutomationSchedule
import com.urbanairship.json.JsonValue
import com.urbanairship.json.jsonMapOf
import com.urbanairship.remotedata.RemoteData
import com.urbanairship.remotedata.RemoteDataInfo
import com.urbanairship.remotedata.RemoteDataSource
import com.urbanairship.util.Network
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertNull
import junit.framework.TestCase.assertTrue
import junit.framework.TestCase.fail
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
public class AutomationRemoteDataAccessTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val network: Network = mockk()
private val remoteData: RemoteData = mockk()
private val clock = TestClock()
private lateinit var subject: AutomationRemoteDataAccess
@Before
public fun setup() {
every { remoteData.payloadFlow(eq(listOf("in_app_messages"))) } returns flowOf()
subject = AutomationRemoteDataAccess(context, remoteData, network)
}
@Test
public fun testIsCurrentTrue(): TestResult = runTest {
val info = makeRemoteDataInfo()
every { remoteData.isCurrent(any()) } returns true
val isCurrent = subject.isCurrent(makeSchedule(info))
assertTrue(isCurrent)
verify { remoteData.isCurrent(eq(info)) }
}
@Test
public fun testIsCurrentFalse(): TestResult = runTest {
val info = makeRemoteDataInfo()
every { remoteData.isCurrent(any()) } returns false
val isCurrent = subject.isCurrent(makeSchedule(info))
assertFalse(isCurrent)
verify { remoteData.isCurrent(eq(info)) }
}
@Test
public fun testIsCurrentNilRemoteDataInfo(): TestResult = runTest {
every { remoteData.isCurrent(any()) } returns true
val isCurrent = subject.isCurrent(makeSchedule())
assertFalse(isCurrent)
}
@Test
public fun testRequiresUpdateUpToDate(): TestResult = runTest {
val info = makeRemoteDataInfo()
val schedule = makeSchedule(info)
every { remoteData.isCurrent(any()) } returns true
every { remoteData.status(any()) } answers {
if (RemoteDataSource.APP == firstArg()) {
RemoteData.Status.UP_TO_DATE
} else {
RemoteData.Status.STALE
}
}
assertFalse(subject.requiredUpdate(schedule))
verify { remoteData.isCurrent(eq(info)) }
verify { remoteData.status(eq(RemoteDataSource.APP)) }
}
@Test
public fun testRequiresUpdateStale(): TestResult = runTest {
val info = makeRemoteDataInfo()
val schedule = makeSchedule(info)
every { remoteData.isCurrent(any()) } returns true
every { remoteData.status(any()) } answers {
if (RemoteDataSource.APP == firstArg()) {
RemoteData.Status.STALE
} else {
RemoteData.Status.UP_TO_DATE
}
}
assertFalse(subject.requiredUpdate(schedule))
verify { remoteData.isCurrent(eq(info)) }
verify { remoteData.status(eq(RemoteDataSource.APP)) }
}
@Test
public fun testRequiresUpdateOutOfDate(): TestResult = runTest {
val info = makeRemoteDataInfo()
val schedule = makeSchedule(info)
every { remoteData.isCurrent(any()) } returns true
every { remoteData.status(any()) } answers {
if (RemoteDataSource.APP == firstArg()) {
RemoteData.Status.OUT_OF_DATE
} else {
RemoteData.Status.UP_TO_DATE
}
}
assertTrue(subject.requiredUpdate(schedule))
verify { remoteData.isCurrent(eq(info)) }
verify { remoteData.status(eq(RemoteDataSource.APP)) }
}
@Test
public fun testRequiresUpdateNotCurrent(): TestResult = runTest {
val info = makeRemoteDataInfo()
val schedule = makeSchedule(info)
every { remoteData.isCurrent(any()) } returns false
every { remoteData.status(any()) } answers {
if (RemoteDataSource.APP == firstArg()) {
RemoteData.Status.UP_TO_DATE
} else {
RemoteData.Status.OUT_OF_DATE
}
}
assertTrue(subject.requiredUpdate(schedule))
verify { remoteData.isCurrent(eq(info)) }
verify(exactly = 0) { remoteData.status(eq(RemoteDataSource.APP)) }
}
@Test
public fun testRequiresUpdateNilRemoteDataInfo(): TestResult = runTest {
val schedule = makeSchedule(null)
every { remoteData.isCurrent(any()) } returns false
every { remoteData.status(any()) } answers {
if (RemoteDataSource.APP == firstArg()) {
RemoteData.Status.UP_TO_DATE
} else {
RemoteData.Status.OUT_OF_DATE
}
}
assertTrue(subject.requiredUpdate(schedule))
verify(exactly = 0) { remoteData.status(eq(RemoteDataSource.APP)) }
}
@Test
public fun testRequiresUpdateRightSource(): TestResult = runTest {
every { remoteData.isCurrent(any()) } returns true
every { remoteData.status(any()) } answers {
val source: RemoteDataSource = firstArg()
when(source) {
RemoteDataSource.APP -> RemoteData.Status.OUT_OF_DATE
RemoteDataSource.CONTACT -> RemoteData.Status.UP_TO_DATE
}
}
assertFalse(subject.requiredUpdate(makeSchedule(makeRemoteDataInfo(RemoteDataSource.CONTACT))))
assertTrue(subject.requiredUpdate(makeSchedule(makeRemoteDataInfo(RemoteDataSource.APP))))
verify { remoteData.status(eq(RemoteDataSource.CONTACT)) }
verify { remoteData.status(eq(RemoteDataSource.APP)) }
}
@Test
public fun testWaitForFullRefresh(): TestResult = runTest {
val schedule = makeSchedule(makeRemoteDataInfo(RemoteDataSource.CONTACT))
coEvery { remoteData.waitForRefresh(any(), any()) } answers {
assertEquals(RemoteDataSource.CONTACT, firstArg())
assertNull(secondArg())
}
subject.waitForFullRefresh(schedule)
coVerify { remoteData.waitForRefresh(any(), any()) }
}
@Test
public fun testWaitForFullRefreshNilInfo(): TestResult = runTest {
coEvery { remoteData.waitForRefresh(any(), any()) } answers {
assertEquals(RemoteDataSource.APP, firstArg())
assertNull(secondArg())
}
subject.waitForFullRefresh(makeSchedule())
coVerify { remoteData.waitForRefresh(any(), any()) }
}
@Test
public fun testBestEffortRefresh(): TestResult = runTest {
coEvery { network.isConnected(any()) } returns true
every { remoteData.isCurrent(any()) } returns true
every { remoteData.status(any()) } answers {
val source: RemoteDataSource = firstArg()
when(source) {
RemoteDataSource.APP -> RemoteData.Status.UP_TO_DATE
RemoteDataSource.CONTACT -> RemoteData.Status.STALE
}
}
coEvery { remoteData.waitForRefreshAttempt(any(), any()) } answers {
assertEquals(RemoteDataSource.CONTACT, firstArg())
assertNull(secondArg())
}
assertTrue(subject.bestEffortRefresh(makeSchedule(makeRemoteDataInfo(RemoteDataSource.CONTACT))))
coVerify { remoteData.waitForRefreshAttempt(any(), any()) }
}
@Test
public fun testBestEffortRefreshNotCurrentAfterAttempt(): TestResult = runTest {
var isCurrentRemoteData = true
coEvery { network.isConnected(any()) } returns true
every { remoteData.isCurrent(any()) } answers { isCurrentRemoteData }
every { remoteData.status(any()) } answers {
val source: RemoteDataSource = firstArg()
when(source) {
RemoteDataSource.APP -> RemoteData.Status.UP_TO_DATE
RemoteDataSource.CONTACT -> RemoteData.Status.STALE
}
}
coEvery { remoteData.waitForRefreshAttempt(any(), any()) } answers {
assertEquals(RemoteDataSource.CONTACT, firstArg())
assertNull(secondArg())
isCurrentRemoteData = false
}
assertFalse(subject.bestEffortRefresh(makeSchedule(makeRemoteDataInfo(RemoteDataSource.CONTACT))))
coVerify { remoteData.waitForRefreshAttempt(any(), any()) }
}
@Test
public fun testBestEffortRefreshNotCurrentReturnsNil(): TestResult = runTest {
coEvery { network.isConnected(any()) } returns true
every { remoteData.isCurrent(any()) } answers { false }
every { remoteData.status(any()) } answers {
val source: RemoteDataSource = firstArg()
when(source) {
RemoteDataSource.APP -> RemoteData.Status.UP_TO_DATE
RemoteDataSource.CONTACT -> RemoteData.Status.STALE
}
}
coEvery { remoteData.waitForRefreshAttempt(any(), any()) } answers {
fail()
}
assertFalse(subject.bestEffortRefresh(makeSchedule(makeRemoteDataInfo(RemoteDataSource.CONTACT))))
}
@Test
public fun testBestEffortRefreshNotConnected(): TestResult = runTest {
coEvery { network.isConnected(any()) } returns false
every { remoteData.isCurrent(any()) } answers { true }
every { remoteData.status(any()) } answers {
val source: RemoteDataSource = firstArg()
when(source) {
RemoteDataSource.APP -> RemoteData.Status.UP_TO_DATE
RemoteDataSource.CONTACT -> RemoteData.Status.STALE
}
}
coEvery { remoteData.waitForRefreshAttempt(any(), any()) } answers {
fail()
}
assertTrue(subject.bestEffortRefresh(makeSchedule(makeRemoteDataInfo(RemoteDataSource.CONTACT))))
}
private fun makeRemoteDataInfo(source: RemoteDataSource = RemoteDataSource.APP): RemoteDataInfo {
return RemoteDataInfo(
url = "https://airship.test",
lastModified = null,
source = source
)
}
private fun makeSchedule(remoteDataInfo: RemoteDataInfo? = null): AutomationSchedule {
return AutomationSchedule(
identifier = "schedule id",
data = AutomationSchedule.ScheduleData.Actions(JsonValue.NULL),
triggers = listOf(),
created = clock.currentTimeMillis.toULong(),
metadata = jsonMapOf("com.urbanairship.iaa.REMOTE_DATA_INFO" to (remoteDataInfo ?: "")).toJsonValue()
)
}
}
| 2 | Kotlin | 122 | 111 | 21d49c3ffd373e3ba6b51a706a4839ab3713db11 | 11,230 | android-library | Apache License 2.0 |
trustagent/src/com/google/android/libraries/car/trustagent/util/Log.kt | google | 415,118,653 | false | {"Kotlin": 865761, "Java": 244253} | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent.util
import android.util.Log
/** Methods that log to android system log buffer and app log buffer. */
fun logwtf(tag: String, message: String) {
Log.wtf(tag, message)
Logger.logwtf(tag, message)
}
fun loge(tag: String, message: String, e: Throwable? = null) {
Log.e(tag, message, e)
Logger.loge(tag, message, e)
}
fun logw(tag: String, message: String) {
Log.w(tag, message)
Logger.logw(tag, message)
}
fun logi(tag: String, message: String) {
Log.i(tag, message)
Logger.logi(tag, message)
}
fun logd(tag: String, message: String) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message)
Logger.logd(tag, message)
}
}
fun logv(tag: String, message: String) {
if (Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message)
Logger.logv(tag, message)
}
}
| 1 | Kotlin | 5 | 18 | 912fd5cff1f08577d679bfaff9fc0666b8093367 | 1,440 | android-auto-companion-android | Apache License 2.0 |
store-rx2/src/test/kotlin/com/dropbox/store/rx2/test/RxFlowableStoreTest.kt | warting | 240,340,296 | true | {"Kotlin": 109713, "Shell": 1015} | package com.dropbox.store.rx2.test
import com.dropbox.android.external.store4.ResponseOrigin
import com.dropbox.android.external.store4.StoreBuilder
import com.dropbox.android.external.store4.StoreRequest
import com.dropbox.android.external.store4.StoreResponse
import com.dropbox.store.rx2.observe
import com.dropbox.store.rx2.fromFlowable
import com.dropbox.store.rx2.withFlowablePersister
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Single
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.concurrent.atomic.AtomicInteger
@RunWith(JUnit4::class)
class RxFlowableStoreTest {
val atomicInteger = AtomicInteger(0)
val fakeDisk = mutableMapOf<Int, String>()
val store =
StoreBuilder.fromFlowable<Int, String> {
Flowable.create({ emitter ->
emitter.onNext("$it ${atomicInteger.incrementAndGet()} occurrence")
emitter.onNext("$it ${atomicInteger.incrementAndGet()} occurrence")
emitter.onComplete()
}, BackpressureStrategy.LATEST)
}
.withFlowablePersister(
reader = {
if (fakeDisk[it] != null)
Flowable.fromCallable { fakeDisk[it]!! }
else
Flowable.empty()
},
writer = { key, value ->
Single.fromCallable { fakeDisk[key] = value }
}
)
.build()
@Test
fun simpleTest() {
val values = store.observe(StoreRequest.fresh(3))
.test()
.awaitCount(3)
.assertValues(
StoreResponse.Loading<String>(ResponseOrigin.Fetcher),
StoreResponse.Data("3 1 occurrence", ResponseOrigin.Fetcher),
StoreResponse.Data("3 2 occurrence", ResponseOrigin.Fetcher)
)
val values2 = store.observe(StoreRequest.cached(3, false))
.test()
.awaitCount(2)
.assertValues(
StoreResponse.Data("3 2 occurrence", ResponseOrigin.Cache),
StoreResponse.Data("3 2 occurrence", ResponseOrigin.Persister)
)
val values3 = store.observe(StoreRequest.fresh(3))
.test()
.awaitCount(3)
.assertValues(
StoreResponse.Loading<String>(ResponseOrigin.Fetcher),
StoreResponse.Data("3 3 occurrence", ResponseOrigin.Fetcher),
StoreResponse.Data("3 4 occurrence", ResponseOrigin.Fetcher)
)
val values4 = store.observe(StoreRequest.cached(3, false))
.test()
.awaitCount(2)
.assertValues(
StoreResponse.Data("3 4 occurrence", ResponseOrigin.Cache),
StoreResponse.Data("3 4 occurrence", ResponseOrigin.Persister)
)
}
}
| 0 | null | 0 | 0 | 7b7f01a439fb4d013d3129c3c2df2143ec78a507 | 2,960 | Store | Apache License 2.0 |
src/main/kotlin/ui/sections/packages/PackageCommands.kt | Pulimet | 678,269,308 | false | {"Kotlin": 295687} | package ui.sections.packages
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import compose.icons.TablerIcons
import compose.icons.tablericons.SettingsAutomation
import net.alexandroid.adbugger.adbugger.generated.resources.Res
import net.alexandroid.adbugger.adbugger.generated.resources.apk_path
import net.alexandroid.adbugger.adbugger.generated.resources.clear_ata
import net.alexandroid.adbugger.adbugger.generated.resources.clear_restart
import net.alexandroid.adbugger.adbugger.generated.resources.close
import net.alexandroid.adbugger.adbugger.generated.resources.install
import net.alexandroid.adbugger.adbugger.generated.resources.open
import net.alexandroid.adbugger.adbugger.generated.resources.restart
import net.alexandroid.adbugger.adbugger.generated.resources.uninstall
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.koinInject
import store.AppStore
import ui.theme.Dimensions
import ui.widgets.buttons.BtnWithText
@Composable
fun PackageCommands(
modifier: Modifier = Modifier,
model: AppStore = koinInject()
) {
val state = model.state
val isPackageSelected = state.selectedPackage != AppStore.PACKAGE_NONE
val isDeviceSelected = state.selectedTargetsList.isNotEmpty()
Column(
modifier = modifier.fillMaxHeight().padding(vertical = 6.dp),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally
) {
BtnWithText(
enabled = isPackageSelected,
onClick = { model.onOpenClick() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.open),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
enabled = isPackageSelected,
onClick = { model.onCloseClick() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.close),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
enabled = isPackageSelected,
onClick = { model.onRestartClick() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.restart),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
enabled = isPackageSelected,
onClick = { model.onClearDataClick() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.clear_ata),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
enabled = isPackageSelected,
onClick = { model.onClearAndRestartClick() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.clear_restart),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
enabled = isPackageSelected,
onClick = { model.onUninstallClick() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.uninstall),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
enabled = isPackageSelected && isDeviceSelected,
onClick = { model.onApkPath() },
icon = Icons.Rounded.CheckCircle,
description = stringResource(Res.string.apk_path),
width = Dimensions.packageCommandsBtnWidth,
)
BtnWithText(
icon = TablerIcons.SettingsAutomation,
onClick = { model.openFilePicker() },
description = stringResource(Res.string.install),
width = Dimensions.packageCommandsBtnWidth,
)
}
}
| 12 | Kotlin | 2 | 25 | 62a201e9b3cd9cfd4eca32b77da2d27e8b1483b1 | 4,149 | ADBugger | MIT License |
firebase-auth/src/jsMain/kotlin/FirebaseAuth.kt | cotrin8672 | 775,878,116 | false | {"Kotlin": 17472} | @file:JsModule("firebase/auth")
@file:JsNonModule
@file:Suppress("unused")
import kotlin.js.Promise
external interface Error {
var name: String
var message: String
var stack: String?
}
external interface Observer<T> {
var next: NextFn<T>
var error: ErrorFn
var complete: CompleteFn
}
external interface Persistence {
var type: PersistenceType
}
external val browserLocalPersistence: Persistence
external val browserSessionPersistence: Persistence
external val inMemoryPersistence: Persistence
external interface Auth {
var app: FirebaseApp
var currentUser: User?
fun onAuthStateChanged(
nextOrObserver: NextFn<User?>,
error: ErrorFn? = definedExternally,
completed: CompleteFn? = definedExternally,
): Unsubscribe
fun onAuthStateChanged(
nextOrObserver: Observer<User?>,
error: ErrorFn? = definedExternally,
completed: CompleteFn? = definedExternally,
): Unsubscribe
fun setPersistence(persistence: Persistence): Promise<Unit>
fun signOut(): Promise<Unit>
}
external fun getAuth(app: FirebaseApp): Auth
external interface UserCredential {
var providerId: String?
var user: User
}
external interface UserInfo {
var displayName: String?
var email: String?
var phoneNumber: String?
var photoURL: String?
var providerId: String
var uid: String
}
external interface IdTokenResult {
var claims: dynamic
}
external interface User : UserInfo {
val emailVerified: Boolean
var isAnonymous: Boolean
var metadata: dynamic
var providerData: dynamic
var refreshToken: String
var tenantId: String?
fun delete(): Promise<Unit>
fun getIdToken(forceRefresh: Boolean): Promise<String>
fun getIdTokenResult(forceRefresh: Boolean): Promise<IdTokenResult>
fun reload(): Promise<Unit>
}
external interface UpdateUserInfo {
var displayName: String
var photoURL: String
}
external interface ActionCodeSettings {
var handleCodeInApp: Boolean?
var url: String?
}
external fun createUserWithEmailAndPassword(auth: Auth, email: String, password: String): Promise<UserCredential>
external fun signInWithEmailAndPassword(auth: Auth, email: String, password: String): Promise<UserCredential>
external fun updateProfile(user: User, updateUserInfo: UpdateUserInfo): Promise<Unit>
external fun sendEmailVerification(user: User): Promise<Unit>
| 0 | Kotlin | 0 | 1 | b70d7f4079ab8235933c7948eec18839153619ef | 2,429 | kotlin-firebase-js | MIT License |
Android/app/src/main/java/com/example/pro_diction/SttActivity.kt | GDSC-SWU | 738,141,316 | false | {"Kotlin": 373175, "Java": 92597, "Python": 59149, "Jupyter Notebook": 47255, "Dockerfile": 342} | package com.example.pro_diction
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.speech.tts.TextToSpeech
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.core.content.ContentProviderCompat.requireContext
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.normal.TedPermission
import java.util.Locale
class SttActivity : AppCompatActivity() {
lateinit var speechRecognizer: SpeechRecognizer
lateinit var recodeStr: String
private lateinit var tts: TextToSpeech
var isFirst = true
// permissions
private val REQUIRED_PERMISSIONS = mutableListOf(
android.Manifest.permission.RECORD_AUDIO).toTypedArray()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_stt)
// permission
val permissionListener = object : PermissionListener {
override fun onPermissionGranted() {
//setupStreamingModePipeline()
//glSurfaceView.post { startCamera() }
//glSurfaceView.visibility = View.VISIBLE
//initView()
}
override fun onPermissionDenied(deniedPermissions: MutableList<String>?) {
Toast.makeText(this@SttActivity, "권한을 다시 설정해주세요!", Toast.LENGTH_SHORT).show()
}
}
TedPermission.create()
.setPermissionListener(permissionListener)
.setPermissions(*REQUIRED_PERMISSIONS)
.check()
// sst 버튼
var btn_sst = findViewById<Button>(R.id.btn_sst)
btn_sst.setOnClickListener {
startVoiceRecording()
}
initTTS()
// tts 버튼 & edit text
var btn_tts = findViewById<Button>(R.id.btn_tts)
var edit_tts = findViewById<EditText>(R.id.edit_tts)
btn_tts.setOnClickListener {
speakOut(edit_tts.text.toString())
}
}
// sst
private fun startVoiceRecording() {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, packageName)
putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR")
}
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this@SttActivity)
speechRecognizer.setRecognitionListener(recognitionListener)
speechRecognizer.startListening(intent)
}
private val recognitionListener: RecognitionListener = object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {
Toast.makeText(applicationContext, "음성인식 시작", Toast.LENGTH_SHORT).show()
}
override fun onBeginningOfSpeech() {
}
override fun onRmsChanged(rmsdB: Float) {
}
override fun onBufferReceived(buffer: ByteArray?) {
}
override fun onEndOfSpeech() {
}
override fun onError(error: Int) {
val message = when (error) {
SpeechRecognizer.ERROR_AUDIO -> "오디오 에러"
SpeechRecognizer.ERROR_CLIENT -> "클라이언트 에러"
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "퍼미션 없음"
SpeechRecognizer.ERROR_NETWORK -> "네트워크 에러"
SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "네트웍 타임아웃"
SpeechRecognizer.ERROR_NO_MATCH -> "찾을 수 없음"
SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "RECOGNIZER 가 바쁨"
SpeechRecognizer.ERROR_SERVER -> "서버가 이상함"
SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "말하는 시간초과"
else -> "알 수 없는 오류임"
}
Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}
override fun onResults(results: Bundle?) {
val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
recodeStr = "" // 음성인식을 두번 연속 할 때 기존 인식된 텍스트를 초기화 하는 코드
for (i in matches!!.indices) recodeStr += matches[i]
Log.d("TEXT", "$recodeStr")
}
override fun onPartialResults(partialResults: Bundle?) {
}
override fun onEvent(eventType: Int, params: Bundle?) {
}
}
// tts
private fun initTTS() {
tts = TextToSpeech(this, textToSpeechListener)
}
private val textToSpeechListener: TextToSpeech.OnInitListener = TextToSpeech.OnInitListener {
if(isFirst) {
isFirst = false
return@OnInitListener
}
if (it == TextToSpeech.SUCCESS) {
val result = tts.setLanguage(Locale.KOREA)
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
// 지원하지 않는 언어거나, 없는 언어일때
} else {
// 정상 인식 되었을 때 실행
}
}
}
private fun speakOut(text: String) {
tts.setPitch(1F)
tts.setSpeechRate(1F)
tts.speak(text, TextToSpeech.QUEUE_ADD, null, "id1")
Toast.makeText(applicationContext, "재생 중..", Toast.LENGTH_SHORT).show()
}
} | 0 | Kotlin | 0 | 1 | 51ced1607b5336ce33becce66f408d53c7e3358e | 5,470 | 2024-ProDiction-SolutionChallenge | MIT License |
app/src/main/java/com/example/recomposememoryleak/MainActivity.kt | maksym-nosov-ecobee | 612,421,652 | false | null | package com.example.recomposememoryleak
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.sp
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.savedstate.findViewTreeSavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import kotlinx.coroutines.flow.MutableStateFlow
class MainActivity : AppCompatActivity() {
private var textMutableState = MutableStateFlow("Default mutable message")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(
ComposeView(this).apply {
setViewTreeLifecycleOwner(this.findViewTreeLifecycleOwner())
setViewTreeSavedStateRegistryOwner(this.findViewTreeSavedStateRegistryOwner())
setContent {
ScreenContent(textMutableState.collectAsState(initial = "").value)
}
}
)
}
override fun onStop() {
super.onStop()
textMutableState.value = "Updated mutable message"
println("-------------------- MainActivity.onStop() --------------------")
}
@Composable
fun ScreenContent(text: String) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column {
Text(
modifier = Modifier.align(CenterHorizontally),
text = "MainActivity",
fontSize = 24.sp
)
Button(modifier = Modifier.align(CenterHorizontally), onClick = {
startActivity(
Intent(
this@MainActivity,
IntermediateActivity::class.java
)
)
}) { Text(text = text) }
}
}
}
} | 0 | Kotlin | 0 | 0 | a5be0130ef9f2190fcf74928392e8759da922064 | 2,384 | recompose-memory-leak | Apache License 2.0 |
src/main/kotlin/com/robotutor/authService/services/TokenService.kt | IOT-echo-system | 732,106,776 | false | {"Kotlin": 72609, "Shell": 600, "Dockerfile": 121} | package com.robotutor.authService.services
import com.robotutor.authService.controllers.view.ResetPasswordRequest
import com.robotutor.authService.controllers.view.UpdateTokenRequest
import com.robotutor.authService.controllers.view.UserLoginRequest
import com.robotutor.authService.controllers.view.ValidateTokenResponse
import com.robotutor.authService.exceptions.IOTError
import com.robotutor.authService.gateway.AccountServiceGateway
import com.robotutor.authService.models.*
import com.robotutor.authService.repositories.TokenRepository
import com.robotutor.iot.auditOnError
import com.robotutor.iot.auditOnSuccess
import com.robotutor.iot.exceptions.UnAuthorizedException
import com.robotutor.iot.models.AuditEvent
import com.robotutor.iot.service.IdGeneratorService
import com.robotutor.iot.utils.createMonoError
import com.robotutor.iot.utils.models.UserAuthenticationData
import com.robotutor.loggingstarter.logOnError
import com.robotutor.loggingstarter.logOnSuccess
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.switchIfEmpty
import java.time.LocalDateTime
@Service
class TokenService(
private val tokenRepository: TokenRepository,
private val idGeneratorService: IdGeneratorService,
private val userService: UserService,
private val accountServiceGateway: AccountServiceGateway
) {
fun login(userLoginRequest: UserLoginRequest): Mono<Token> {
return userService.verifyCredentials(userLoginRequest)
.flatMap { generateToken(userId = it.userId, expiredAt = LocalDateTime.now().plusDays(7)) }
}
fun validate(token: String): Mono<ValidateTokenResponse> {
return tokenRepository.findByValueAndExpiredAtAfter(token)
.map {
ValidateTokenResponse(
userId = it.userId,
projectId = it.accountId ?: "",
roleId = it.roleId ?: "",
boardId = it.boardId
)
}
.switchIfEmpty {
createMonoError(UnAuthorizedException(IOTError.IOT0103))
}
.logOnSuccess(message = "Successfully validated token")
.logOnError(errorCode = IOTError.IOT0103.errorCode, errorMessage = "Failed to validate token")
}
fun generateToken(
userId: UserId,
expiredAt: LocalDateTime,
otpId: OtpId? = null,
accountId: String? = null,
roleId: String? = null,
boardId: String? = null
): Mono<Token> {
return idGeneratorService.generateId(IdType.TOKEN_ID)
.flatMap { tokenId ->
tokenRepository.save(
Token.generate(
tokenId = tokenId,
userId = userId,
expiredAt = expiredAt,
otpId = otpId,
accountId = accountId,
roleId = roleId,
boardId = boardId
)
)
.auditOnSuccess(
event = AuditEvent.GENERATE_TOKEN,
metadata = mapOf("tokenId" to tokenId),
userId = userId
)
}
.auditOnError(event = AuditEvent.GENERATE_TOKEN, userId = userId)
.logOnSuccess(message = "Successfully generated token")
.logOnError(errorMessage = "Failed to generate token")
}
fun resetPassword(resetPasswordRequest: ResetPasswordRequest, tokenValue: String): Mono<UserDetails> {
return tokenRepository.findByValueAndExpiredAtAfter(tokenValue)
.flatMap { token ->
resetPassword(token, resetPasswordRequest)
.logOnSuccess(message = "Successfully reset user password")
.logOnError(errorMessage = "Failed to reset user password")
.flatMap { userDetails ->
tokenRepository.save(token.setExpired())
.map { userDetails }
}
.logOnSuccess(message = "set current token as expired")
.logOnError(errorMessage = "Failed to set current token as expired")
}
}
private fun resetPassword(token: Token, resetPasswordRequest: ResetPasswordRequest): Mono<UserDetails> {
return if (token.otpId != null) {
userService.resetPassword(token.userId, resetPasswordRequest.password)
} else {
userService.resetPassword(
token.userId,
resetPasswordRequest.currentPassword ?: "",
resetPasswordRequest.password
)
}
}
fun updateToken(updateTokenRequest: UpdateTokenRequest, tokenString: String): Mono<Token> {
return tokenRepository.findByValueAndExpiredAtAfter(tokenString)
.flatMap { token ->
accountServiceGateway.isValidAccountAndRole(
userId = token.userId,
accountId = updateTokenRequest.projectId,
roleId = updateTokenRequest.roleId
)
.flatMap {
generateToken(
userId = token.userId,
expiredAt = token.expiredAt,
otpId = null,
accountId = updateTokenRequest.projectId,
roleId = updateTokenRequest.roleId
)
}
}
}
fun logout(token: String, userAuthenticationData: UserAuthenticationData): Mono<Token> {
return tokenRepository.findByValue(token)
.flatMap {
tokenRepository.save(it.setExpired())
}
.auditOnSuccess(event = AuditEvent.LOG_OUT)
.auditOnError(event = AuditEvent.LOG_OUT)
.logOnSuccess(message = "Successfully logged out user")
.logOnError(errorMessage = "Failed to log out user")
}
fun generateTokenForBoard(boardId: String, authenticationData: UserAuthenticationData): Mono<Token> {
return tokenRepository.findByBoardIdAndExpiredAtAfter(boardId)
.switchIfEmpty {
accountServiceGateway.isValidBoard(boardId, authenticationData)
.flatMap {
generateToken(
expiredAt = LocalDateTime.now().plusYears(100),
accountId = authenticationData.accountId,
roleId = "00004",
boardId = boardId,
userId = "Board_$boardId"
)
}
}
}
fun updateTokenForBoard(boardId: String, authenticationData: UserAuthenticationData): Mono<Token> {
return tokenRepository.deleteByBoardId(boardId)
.flatMap {
generateTokenForBoard(boardId, authenticationData)
}
}
}
| 0 | Kotlin | 0 | 0 | ec234618e3b0ec1f58a1e7661f4ceff21fe0e78e | 7,111 | auth-service | MIT License |
presentation/src/main/java/com/jota/sunshine/view/fragment/BaseFragment.kt | DavidPizarro | 459,618,953 | true | {"Kotlin": 56310, "Java": 2222} | package com.jota.sunshine.view.fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jota.sunshine.internal.di.HasComponent
abstract class BaseFragment : Fragment() {
abstract fun getLayoutResource(): Int
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val fragmentView: View = (inflater?.inflate(getLayoutResource(), container, false) as View)
return fragmentView
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
this.initialize()
}
protected abstract fun initialize()
protected fun <C> getComponent(componentType: Class<C>): C {
return componentType.cast((activity as HasComponent<C>).getComponent())
}
}
| 0 | null | 0 | 0 | 6c1565f8549a34340e700e06eefc9ac5cb984a1d | 1,068 | Android-Kotlin-CleanArchitecture | Apache License 2.0 |
Focus/app/src/main/java/com/fyp/focus/fragment/DefaultTimersFragment.kt | hillcormac | 453,995,952 | false | {"Kotlin": 82321} | package com.fyp.focus.fragment
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import com.fyp.focus.R
import com.fyp.focus.activity.TimerActivity
import com.fyp.focus.adapter.TimerListAdapter
import com.fyp.focus.customclass.DBHelper
import com.fyp.focus.customclass.Timer
import com.fyp.focus.global.GlobalFunctions.logMessage
import com.fyp.focus.global.UserPreferences
private const val TAG = "DefaultTimersFragment"
class DefaultTimersFragment : Fragment() {
private lateinit var preferences: UserPreferences
private lateinit var dbHelper: DBHelper
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_default_timers, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dbHelper = DBHelper(this.requireContext(), "focus", "default_timers")
preferences = UserPreferences(requireContext())
// check if the default_timers table exists, create it if not
if (!preferences.defaultTimerDbCreated) {
logMessage(TAG, "table not created, creating now")
dbHelper.createTimerTable(dbHelper.writableDatabase)
preferences.defaultTimerDbCreated = true
}
// get all default timers in the database
val timerArray = ArrayList<Timer>()
val cursor = dbHelper.readAllData(dbHelper.readableDatabase)
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
val timer = Timer(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(4))
timerArray.add(timer)
logMessage(TAG, "timer: $timer")
cursor.moveToNext()
}
}
// attach adapter to ListView
val adapter = TimerListAdapter(this, timerArray)
val listView = requireView().findViewById<ListView>(R.id.lvDefaultTimers)
listView.adapter = adapter
// start timer activity with the given timer when it is clicked
listView.setOnItemClickListener { adapterView, view, i, l ->
val intent = Intent(context, TimerActivity::class.java)
logMessage(TAG, "intent extras: ${adapter.timers[i].name}, ${adapter.timers[i].timeWork}. ${adapter.timers[i].timeShortBreak}, ${adapter.timers[i].timeLongBreak}, ${adapter.timers[i].intervals}")
intent.putExtra("timerName", adapter.timers[i].name)
intent.putExtra("timeWork", adapter.timers[i].timeWork)
intent.putExtra("timeShortBreak", adapter.timers[i].timeShortBreak.toString())
intent.putExtra("timeLongBreak", adapter.timers[i].timeLongBreak.toString())
intent.putExtra("intervals", adapter.timers[i].intervals.toString())
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | 542f9a4bff73abad97381e0748d072d1754ae6dc | 3,185 | focus-app | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ecs/CfnTaskDefinitionRuntimePlatformPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.ecs
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.ecs.CfnTaskDefinition
/**
* Information about the platform for the Amazon ECS service or task.
*
* For more information about `RuntimePlatform` , see
* [RuntimePlatform](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#runtime-platform)
* in the *Amazon Elastic Container Service Developer Guide* .
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.ecs.*;
* RuntimePlatformProperty runtimePlatformProperty = RuntimePlatformProperty.builder()
* .cpuArchitecture("cpuArchitecture")
* .operatingSystemFamily("operatingSystemFamily")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-runtimeplatform.html)
*/
@CdkDslMarker
public class CfnTaskDefinitionRuntimePlatformPropertyDsl {
private val cdkBuilder: CfnTaskDefinition.RuntimePlatformProperty.Builder =
CfnTaskDefinition.RuntimePlatformProperty.builder()
/**
* @param cpuArchitecture The CPU architecture. You can run your Linux tasks on an ARM-based
* platform by setting the value to `ARM64` . This option is available for tasks that run on
* Linux Amazon EC2 instance or Linux containers on Fargate.
*/
public fun cpuArchitecture(cpuArchitecture: String) {
cdkBuilder.cpuArchitecture(cpuArchitecture)
}
/** @param operatingSystemFamily The operating system. */
public fun operatingSystemFamily(operatingSystemFamily: String) {
cdkBuilder.operatingSystemFamily(operatingSystemFamily)
}
public fun build(): CfnTaskDefinition.RuntimePlatformProperty = cdkBuilder.build()
}
| 3 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,167 | awscdk-dsl-kotlin | Apache License 2.0 |
src/main/kotlin/my/chaster/extension/fitness/stepstounlock/workaround/config/StepsToUnlockConfig.kt | Encelus | 384,208,614 | false | null | package my.chaster.extension.fitness.stepstounlock.workaround.config
import my.chaster.chaster.ChasterLockId
import my.chaster.chaster.WithChasterLockId
import my.chaster.jpa.AbstractEntity
import my.chaster.jpa.AbstractEntityId
import java.util.UUID
import javax.persistence.Column
import javax.persistence.Embeddable
import javax.persistence.Entity
import javax.persistence.Table
@Entity
@Table(name = "steps_to_unlock_config")
class StepsToUnlockConfig(
@Column(name = "chaster_lock_id", nullable = false, updatable = false, unique = true)
override val chasterLockId: ChasterLockId,
@Column(name = "required_steps", nullable = false, updatable = false)
val requiredSteps: Int,
) : AbstractEntity<StepsToUnlockConfigId>(StepsToUnlockConfigId()), WithChasterLockId {
@Column(name = "is_frozen", nullable = false)
var isFrozen = true
}
@Embeddable
class StepsToUnlockConfigId(id: UUID = randomId()) : AbstractEntityId(id) | 3 | Kotlin | 0 | 1 | 8a486fab94c5d038f64770d4db99859b8ffd2ef0 | 931 | MyChaster | The Unlicense |
app/src/main/java/com/pandulapeter/beagle/appDemo/feature/main/examples/valueWrappers/ValueWrappersViewModel.kt | pandulapeter | 209,092,048 | false | {"Kotlin": 849080, "Ruby": 497} | package com.pandulapeter.beagle.appDemo.feature.main.examples.valueWrappers
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.pandulapeter.beagle.Beagle
import com.pandulapeter.beagle.appDemo.R
import com.pandulapeter.beagle.appDemo.data.model.BeagleListItemContractImplementation
import com.pandulapeter.beagle.appDemo.feature.main.examples.valueWrappers.list.BulkApplySwitchViewHolder
import com.pandulapeter.beagle.appDemo.feature.main.examples.valueWrappers.list.CurrentStateViewHolder
import com.pandulapeter.beagle.appDemo.feature.main.examples.valueWrappers.list.EnableAllModulesSwitchViewHolder
import com.pandulapeter.beagle.appDemo.feature.main.examples.valueWrappers.list.ResetButtonViewHolder
import com.pandulapeter.beagle.appDemo.feature.main.examples.valueWrappers.list.ValueWrappersListItem
import com.pandulapeter.beagle.appDemo.feature.shared.ListViewModel
import com.pandulapeter.beagle.appDemo.feature.shared.list.CodeSnippetViewHolder
import com.pandulapeter.beagle.appDemo.feature.shared.list.SectionHeaderViewHolder
import com.pandulapeter.beagle.appDemo.feature.shared.list.SpaceViewHolder
import com.pandulapeter.beagle.appDemo.feature.shared.list.TextViewHolder
import com.pandulapeter.beagle.modules.CheckBoxModule
import com.pandulapeter.beagle.modules.MultipleSelectionListModule
import com.pandulapeter.beagle.modules.SingleSelectionListModule
import com.pandulapeter.beagle.modules.SliderModule
import com.pandulapeter.beagle.modules.SwitchModule
import com.pandulapeter.beagle.modules.TextInputModule
import kotlin.properties.Delegates
class ValueWrappersViewModel : ListViewModel<ValueWrappersListItem>() {
private val _items = MutableLiveData<List<ValueWrappersListItem>>()
override val items: LiveData<List<ValueWrappersListItem>> = _items
val toggle1 get() = Beagle.find<SwitchModule>(ValueWrappersFragment.TOGGLE_1_ID)
val toggle2 get() = Beagle.find<SwitchModule>(ValueWrappersFragment.TOGGLE_2_ID)
val toggle3 get() = Beagle.find<CheckBoxModule>(ValueWrappersFragment.TOGGLE_3_ID)
val toggle4 get() = Beagle.find<CheckBoxModule>(ValueWrappersFragment.TOGGLE_4_ID)
val multipleSelectionOptions get() = Beagle.find<MultipleSelectionListModule<BeagleListItemContractImplementation>>(ValueWrappersFragment.CHECK_BOX_GROUP_ID)
val singleSelectionOption get() = Beagle.find<SingleSelectionListModule<BeagleListItemContractImplementation>>(ValueWrappersFragment.RADIO_BUTTON_GROUP_ID)
val slider get() = Beagle.find<SliderModule>(ValueWrappersFragment.SLIDER)
val textInput get() = Beagle.find<TextInputModule>(ValueWrappersFragment.TEXT_INPUT)
private var selectedSection by Delegates.observable<Section?>(null) { _, _, _ -> refreshItems() }
var areModulesEnabled = true
set(value) {
field = value
refreshItems()
}
var isBulkApplyEnabled = false
set(value) {
field = value
toggle1?.resetPendingChanges(Beagle)
toggle2?.resetPendingChanges(Beagle)
toggle3?.resetPendingChanges(Beagle)
toggle4?.resetPendingChanges(Beagle)
multipleSelectionOptions?.resetPendingChanges(Beagle)
singleSelectionOption?.resetPendingChanges(Beagle)
slider?.resetPendingChanges(Beagle)
textInput?.resetPendingChanges(Beagle)
refreshItems()
}
init {
refreshItems()
}
fun onSectionHeaderSelected(uiModel: SectionHeaderViewHolder.UiModel) {
Section.fromResourceId(uiModel.titleResourceId).let {
selectedSection = if (it == selectedSection) null else it
}
}
fun refreshItems() {
_items.postValue(mutableListOf<ValueWrappersListItem>().apply {
addTopSection()
addSwitchSection()
addCheckBoxSection()
addMultipleSelectionListSection()
addSingleSelectionListSection()
addSliderSection()
addTextInputSection()
addQueryingAndChangingTheCurrentValueSection()
addPersistingStateSection()
addDisablingInteractionsSection()
addBulkApplySection()
})
}
private fun MutableList<ValueWrappersListItem>.addTopSection() {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_text_1))
add(
CurrentStateViewHolder.UiModel(
toggle1 = toggle1?.getCurrentValue(Beagle) == true,
toggle2 = toggle2?.getCurrentValue(Beagle) == true,
toggle3 = toggle3?.getCurrentValue(Beagle) == true,
toggle4 = toggle4?.getCurrentValue(Beagle) == true,
multipleSelectionOptions = multipleSelectionOptions?.getCurrentValue(Beagle)?.toList().orEmpty(),
singleSelectionOption = singleSelectionOption?.getCurrentValue(Beagle),
slider = slider?.getCurrentValue(Beagle) ?: 0,
text = textInput?.getCurrentValue(Beagle).orEmpty()
)
)
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_text_2))
add(SpaceViewHolder.UiModel())
}
private fun MutableList<ValueWrappersListItem>.addSwitchSection() = addSection(Section.SWITCH) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_switch_description_1))
add(
CodeSnippetViewHolder.UiModel(
"SwitchModule(\n" +
" text = \"Text on the switch\", \n" +
" onValueChanged = { isChecked -> TODO() }\n" +
")"
)
)
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_switch_description_2))
}
private fun MutableList<ValueWrappersListItem>.addCheckBoxSection() = addSection(Section.CHECK_BOX) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_check_box_description))
add(
CodeSnippetViewHolder.UiModel(
"CheckBoxModule(\n" +
" text = \"Text on the check box\", \n" +
" onValueChanged = { isChecked -> TODO() }\n" +
")"
)
)
}
private fun MutableList<ValueWrappersListItem>.addMultipleSelectionListSection() = addSection(Section.MULTIPLE_SELECTION_LIST) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_multiple_selection_list_description_1))
add(
CodeSnippetViewHolder.UiModel(
"data class Option(\n" +
" override val id: String,\n" +
" override val title: Text \n" +
") : BeagleListItemContract"
)
)
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_multiple_selection_list_description_2))
add(
CodeSnippetViewHolder.UiModel(
"MultipleSelectionListModule(\n" +
" title = \"Text in the header\",\n" +
" items = listOf(\n" +
" Option(id = \"option1\", title = \"Option 1\".toText()),\n" +
" Option(id = \"option2\", title = \"Option 2\".toText()),\n" +
" Option(id = \"option3\", title = \"Option 3\".toText())\n" +
" ),\n" +
" initiallySelectedItemIds = emptySet(),\n" +
" onSelectionChanged = { selectedItems -> TODO() }\n" +
")"
)
)
}
private fun MutableList<ValueWrappersListItem>.addSingleSelectionListSection() = addSection(Section.SINGLE_SELECTION_LIST) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_single_selection_list_description_1))
add(
CodeSnippetViewHolder.UiModel(
"SingleSelectionListModule(\n" +
" title = \"Text in the header\",\n" +
" items = listOf(\n" +
" Option(id = \"option1\", title = \"Option 1\".toText()),\n" +
" Option(id = \"option2\", title = \"Option 2\".toText()),\n" +
" Option(id = \"option3\", title = \"Option 3\".toText())\n" +
" ),\n" +
" initiallySelectedItemId = \"option1\",\n" +
" onSelectionChanged = { selectedItem -> TODO() }\n" +
")"
)
)
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_single_selection_list_description_2))
}
private fun MutableList<ValueWrappersListItem>.addSliderSection() = addSection(Section.SLIDER) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_slider_description_1))
add(
CodeSnippetViewHolder.UiModel(
"SliderModule(\n" +
" text = { currentValue -> \"Current value: \$currentValue\".toText() },\n" +
" onValueChanged = { newValue -> TODO() }\n" +
"),"
)
)
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_slider_description_2))
}
private fun MutableList<ValueWrappersListItem>.addTextInputSection() = addSection(Section.TEXT_INPUT) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_text_input_description_1))
add(
CodeSnippetViewHolder.UiModel(
"TextInputModule(\n" +
" text = { currentValue -> \"Current value: \$currentValue\".toText() },\n" +
" onValueChanged = { newValue -> TODO() }\n" +
")"
)
)
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_text_input_description_2))
}
private fun MutableList<ValueWrappersListItem>.addQueryingAndChangingTheCurrentValueSection() = addSection(Section.QUERYING_AND_CHANGING_THE_CURRENT_VALUE) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_querying_and_changing_the_current_value_description_1))
add(CodeSnippetViewHolder.UiModel("module.getCurrentValue(Beagle)"))
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_querying_and_changing_the_current_value_description_2))
add(CodeSnippetViewHolder.UiModel("module.setCurrentValue(Beagle, newValue)"))
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_querying_and_changing_the_current_value_description_3))
add(ResetButtonViewHolder.UiModel())
add(SpaceViewHolder.UiModel())
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_querying_and_changing_the_current_value_description_4))
add(CodeSnippetViewHolder.UiModel("Beagle.find<ModuleType>(moduleId)"))
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_querying_and_changing_the_current_value_description_5))
}
private fun MutableList<ValueWrappersListItem>.addPersistingStateSection() = addSection(Section.PERSISTING_STATE) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_persisting_state_description))
}
private fun MutableList<ValueWrappersListItem>.addDisablingInteractionsSection() = addSection(Section.DISABLING_INTERACTIONS) {
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_disabling_interactions_description_1))
add(EnableAllModulesSwitchViewHolder.UiModel(areModulesEnabled))
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_disabling_interactions_description_2))
}
private fun MutableList<ValueWrappersListItem>.addBulkApplySection() = addSection(Section.BULK_APPLY) {
add(TextViewHolder.UiModel(if (isBulkApplyEnabled) R.string.case_study_value_wrappers_bulk_apply_description_1_on else R.string.case_study_value_wrappers_bulk_apply_description_1_off))
add(BulkApplySwitchViewHolder.UiModel(isBulkApplyEnabled))
add(TextViewHolder.UiModel(R.string.case_study_value_wrappers_bulk_apply_description_2))
}
private fun MutableList<ValueWrappersListItem>.addSection(section: Section, action: MutableList<ValueWrappersListItem>.() -> Unit) = (selectedSection == section).also { isExpanded ->
add(SectionHeaderViewHolder.UiModel(section.titleResourceId, isExpanded))
if (isExpanded) {
action()
add(SpaceViewHolder.UiModel())
}
}
private enum class Section(@StringRes val titleResourceId: Int) {
SWITCH(R.string.case_study_value_wrappers_switch),
CHECK_BOX(R.string.case_study_value_wrappers_check_box),
MULTIPLE_SELECTION_LIST(R.string.case_study_value_wrappers_multiple_selection_list),
SINGLE_SELECTION_LIST(R.string.case_study_value_wrappers_single_selection_list),
SLIDER(R.string.case_study_value_wrappers_slider),
TEXT_INPUT(R.string.case_study_value_wrappers_text_input),
QUERYING_AND_CHANGING_THE_CURRENT_VALUE(R.string.case_study_value_wrappers_querying_and_changing_the_current_value),
PERSISTING_STATE(R.string.case_study_value_wrappers_persisting_state),
DISABLING_INTERACTIONS(R.string.case_study_value_wrappers_disabling_interactions),
BULK_APPLY(R.string.case_study_value_wrappers_bulk_apply);
companion object {
fun fromResourceId(@StringRes titleResourceId: Int?) = entries.firstOrNull { it.titleResourceId == titleResourceId }
}
}
} | 15 | Kotlin | 27 | 491 | edc654e4bd75bf9519c476c67a9b77d600e3ce9e | 13,730 | beagle | Apache License 2.0 |
app/src/main/java/io/pascucci/repos/route/RouteRepository.kt | CatInt | 762,218,426 | false | {"Kotlin": 55179} | /*
* *******************************************************************************
* ** Copyright (C), 2014-2021, OnePlus Mobile Comm Corp., Ltd
* ** All rights reserved.
* *******************************************************************************
*/
package io.pascucci.repos.route
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.tomtom.sdk.location.GeoPoint
import com.tomtom.sdk.routing.route.Route
import io.pascucci.AppCoroutineDispatchers
import io.pascucci.data.Location
import io.pascucci.repos.AsyncResult
import kotlinx.coroutines.runBlocking
import timber.log.Timber
class RouteRepository(
private val planner: IRoutePlanner,
private val dispatchers: AppCoroutineDispatchers
) : IRouteRepository {
private val _destinationObservable = MutableLiveData<Location>()
override val destinationObservable get() = _destinationObservable
private val _routesObservable = MutableLiveData<List<Route>>()
override val routesObservable: LiveData<List<Route>> = _routesObservable
override fun plan(from: GeoPoint, to: GeoPoint) {
Timber.d("onRouteRepo plan ${Thread.currentThread()}")
runBlocking(dispatchers.io) {
Timber.d("onRouteRepo ${Thread.currentThread()}")
val result = planner.plan(from, to)
when (result) {
is AsyncResult.Success<List<Route>> -> result.data
else -> emptyList()
}.let { list ->
_routesObservable.postValue(list)
}
}
}
} | 0 | Kotlin | 0 | 0 | b2b9f3d84a333b76586b443dc6dc16b8f54d967e | 1,566 | Pascucci | Apache License 2.0 |
app/src/main/java/com/teobaranga/monica/data/sync/Synchronizer.kt | teobaranga | 686,113,276 | false | {"Kotlin": 269714} | package com.teobaranga.monica.data.sync
import kotlinx.coroutines.flow.Flow
interface Synchronizer {
val syncState: Flow<State>
suspend fun sync()
enum class State {
IDLE,
REFRESHING,
}
}
| 1 | Kotlin | 1 | 8 | 370462ffeaa6982e2475a416ef0ec6c2d435da14 | 225 | monica | Apache License 2.0 |
runtime/runtime-core/native/src/aws/smithy/kotlin/runtime/io/CloseableNative.kt | smithy-lang | 294,823,838 | false | {"Kotlin": 4171610, "Smithy": 122979, "Python": 1215} | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package aws.smithy.kotlin.runtime.io
public actual interface Closeable {
@Throws(IOException::class)
public actual fun close()
}
| 36 | Kotlin | 26 | 82 | ad18e2fb043f665df9add82083c17877a23f8610 | 254 | smithy-kotlin | Apache License 2.0 |
app/src/main/java/com/example/Wandroid/weidget/CustomViewpager.kt | xuell0601 | 324,354,223 | false | null | /**
* Copyright (C), 2015-2020, XXX有限公司
* FileName: CustomViewpager
* Author: Administrator
* Date: 2020/11/18 0018 22:08
* Description:
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
</desc></version></time></author> */
package com.example.Wandroid.weidget
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
/**
* @ClassName: CustomViewpager
* @Description: java类作用描述
* @Author: Administrator
* @Date: 2020/11/18 0018 22:08
*/
/**
* Created by vipui on 16/8/25.
*/
class CustomViewpager : ViewPager {
private var current = 0
var heights:Int = 0
var isScrollble = true
constructor(context: Context?) : super(context!!) {}
constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {}
protected override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var heightMeasureSpec = heightMeasureSpec
if (childCount > current) {
val child: View = getChildAt(current)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
heights = h
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
fun voidresetHeight(current: Int) {
this.current = current
if (childCount > current) {
var layoutParams = layoutParams as LinearLayout.LayoutParams?
if (layoutParams == null) {
layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height)
} else {
layoutParams.height = heights
}
setLayoutParams(layoutParams)
}
}
override fun onTouchEvent(ev: MotionEvent?): Boolean {
return if (!isScrollble) {
true
} else super.onTouchEvent(ev)
}
} | 0 | Kotlin | 0 | 0 | 5c2fae49669c3144529ab6768cc9929c35cd3d35 | 2,086 | Wandroid | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BathOff.kt | walter-juan | 868,046,028 | false | {"Kotlin": 20416825} | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.BathOff: ImageVector
get() {
if (_bathOff != null) {
return _bathOff!!
}
_bathOff = Builder(name = "BathOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.0f, 12.0f)
horizontalLineToRelative(4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(3.0f)
curveToRelative(0.0f, 0.311f, -0.036f, 0.614f, -0.103f, 0.904f)
moveToRelative(-1.61f, 2.378f)
arcToRelative(3.982f, 3.982f, 0.0f, false, true, -2.287f, 0.718f)
horizontalLineToRelative(-10.0f)
arcToRelative(4.0f, 4.0f, 0.0f, false, true, -4.0f, -4.0f)
verticalLineToRelative(-3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
horizontalLineToRelative(8.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 12.0f)
verticalLineToRelative(-6.0f)
moveToRelative(1.178f, -2.824f)
curveToRelative(0.252f, -0.113f, 0.53f, -0.176f, 0.822f, -0.176f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(2.25f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 21.0f)
lineToRelative(1.0f, -1.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 21.0f)
lineToRelative(-1.0f, -1.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.0f, 3.0f)
lineToRelative(18.0f, 18.0f)
}
}
.build()
return _bathOff!!
}
private var _bathOff: ImageVector? = null
| 0 | Kotlin | 0 | 1 | b037895588c2f62d069c724abe624b67c0889bf9 | 3,747 | compose-icon-collections | MIT License |
shared/src/commonMain/kotlin/com/devscion/classy/presentation/menu/components/MenuItem.kt | zeeshanali-k | 679,622,499 | false | {"Kotlin": 100741, "Swift": 708, "HTML": 513, "Shell": 228, "Ruby": 101} | package com.devscion.classy.presentation.menu.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.devscion.classy.ui.LARGE_SPACING
import com.devscion.classy.ui.STANDARD_SPACING
import com.devscion.classy.utils.Vertical
import com.devscion.typistcmp.Typist
import com.devscion.typistcmp.TypistSpeed
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
@OptIn(ExperimentalResourceApi::class)
@Composable
fun MenuItem(title: String, icon: String, onClicked: () -> Unit) {
Card(
shape = RoundedCornerShape(20.dp),
elevation = CardDefaults.elevatedCardElevation(),
colors = CardDefaults.cardColors(
containerColor = Color.White
)
) {
Column(
Modifier.padding(10.dp)
.clickable { onClicked() },
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(
painterResource(icon),
contentDescription = "App Logo",
modifier = Modifier.size(170.dp)
)
LARGE_SPACING.Vertical()
Typist(
title,
typistSpeed = TypistSpeed.FAST,
isInfiniteCursor = false,
textStyle = TextStyle(
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold
)
)
}
}
} | 0 | Kotlin | 1 | 24 | 92772ba4466936bfa393b22f58ced1f0179bfee6 | 2,214 | Classy | Apache License 2.0 |
core/src/main/kotlin/roost/models/Eta.kt | InkApplications | 138,104,657 | false | {"Kotlin": 24235} | package roost.models
import com.squareup.moshi.FromJson
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.ToJson
import org.threeten.bp.Instant
data class Eta(val id: String, val estimatedArrival: ClosedRange<Instant>)
@JsonClass(generateAdapter = true)
internal data class EtaJson(
@Json(name = "trip_id") val id: String,
@Json(name = "estimated_arrival_window_begin") val windowStart: Instant,
@Json(name = "estimated_arrival_window_end") val windowEnd: Instant
)
internal object EtaAdapter {
@FromJson fun fromJson(jsonModel: EtaJson) = Eta(
id = jsonModel.id,
estimatedArrival = jsonModel.windowStart..jsonModel.windowEnd
)
@ToJson fun toJson(jsonModel: Eta) = EtaJson(
id = jsonModel.id,
windowStart = jsonModel.estimatedArrival.start,
windowEnd = jsonModel.estimatedArrival.endInclusive
)
}
| 0 | Kotlin | 0 | 1 | cc73d21556483ec6aeddd8db3d7d4cd3430b4f5d | 913 | Roost | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/activities/ActivitiesService.kt | ministryofjustice | 445,140,246 | false | null | package uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities
import com.microsoft.applicationinsights.TelemetryClient
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.Activity
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivityPay
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivitySchedule
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.config.trackEvent
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.CreateActivityRequest
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.CreateOffenderProgramProfileRequest
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.EndOffenderProgramProfileRequest
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.NomisApiService
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.PayRateRequest
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.UpdateActivityRequest
import java.math.BigDecimal
import java.time.LocalDateTime
@Service
class ActivitiesService(
private val activitiesApiService: ActivitiesApiService,
private val nomisApiService: NomisApiService,
private val mappingService: ActivitiesMappingService,
private val activitiesUpdateQueueService: ActivitiesUpdateQueueService,
private val telemetryClient: TelemetryClient
) {
private companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
fun createActivity(event: ScheduleDomainEvent) {
activitiesApiService.getActivitySchedule(event.additionalInformation.activityScheduleId).run {
val activity = activitiesApiService.getActivity(activity.id)
val telemetryMap = mutableMapOf(
"activityScheduleId" to id.toString(),
"description" to description,
)
// to protect against repeated create messages for same activity
if (mappingService.getMappingGivenActivityScheduleIdOrNull(id) != null) {
log.warn("Mapping already exists for activity schedule id $id")
return
}
val nomisResponse = try {
nomisApiService.createActivity(toNomisActivity(this, activity))
} catch (e: Exception) {
telemetryClient.trackEvent("activity-create-failed", telemetryMap)
log.error("createActivity() Unexpected exception", e)
throw e
}
telemetryMap["courseActivityId"] = nomisResponse.courseActivityId.toString()
try {
mappingService.createMapping(
ActivityMappingDto(
nomisCourseActivityId = nomisResponse.courseActivityId,
activityScheduleId = id,
mappingType = "ACTIVITY_CREATED",
)
)
} catch (e: Exception) {
telemetryClient.trackEvent("activity-create-map-failed", telemetryMap)
log.error("Unexpected exception, queueing retry", e)
activitiesUpdateQueueService.sendMessage(
ActivityContext(
nomisCourseActivityId = nomisResponse.courseActivityId,
activityScheduleId = id,
)
)
return
}
telemetryClient.trackEvent("activity-created-event", telemetryMap)
}
}
fun updateActivity(event: ScheduleDomainEvent) {
val telemetryMap = mutableMapOf("activityScheduleId" to event.additionalInformation.activityScheduleId.toString())
runCatching {
val activitySchedule = activitiesApiService.getActivitySchedule(event.additionalInformation.activityScheduleId)
val activity = activitiesApiService.getActivity(activitySchedule.activity.id)
.also { telemetryMap["activityId"] = it.id.toString() }
val nomisCourseActivityId = mappingService.getMappingGivenActivityScheduleId(activitySchedule.id).nomisCourseActivityId
.also { telemetryMap["nomisCourseActivityId"] = it.toString() }
activitySchedule.toUpdateActivityRequest(activity.pay)
.also { nomisApiService.updateActivity(nomisCourseActivityId, it) }
}.onSuccess {
telemetryClient.trackEvent("activity-amend-event", telemetryMap, null)
}.onFailure { e ->
telemetryClient.trackEvent("activity-amend-failed", telemetryMap, null)
throw e
}
}
private fun ActivitySchedule.toUpdateActivityRequest(pay: List<ActivityPay>) =
UpdateActivityRequest(
endDate, internalLocation?.id?.toLong(),
pay.map { p ->
PayRateRequest(
incentiveLevel = p.incentiveLevel!!, // TODO SDI-622 this should be made non-nullable in the Activities API soon
payBand = p.prisonPayBand.nomisPayBand.toString(),
rate = BigDecimal(p.rate!!).movePointLeft(2)
)
}
)
fun createAllocation(allocationEvent: AllocationDomainEvent) {
activitiesApiService.getAllocation(allocationEvent.additionalInformation.allocationId).let { allocation ->
mappingService.getMappingGivenActivityScheduleId(allocationEvent.additionalInformation.scheduleId).let { mapping ->
val telemetryMap = mutableMapOf(
"allocationId" to allocation.id.toString(),
"offenderNo" to allocation.prisonerNumber,
"bookingId" to allocation.bookingId.toString(),
)
val nomisResponse = try {
nomisApiService.createAllocation(
mapping.nomisCourseActivityId,
CreateOffenderProgramProfileRequest(
bookingId = allocation.bookingId!!,
startDate = allocation.startDate,
endDate = allocation.endDate,
// TODO SDI-614 We don't know what payBandId means - see JIRA ticket for link to the Slack conv.
payBandCode = allocation.payBandId.toString(), // Nomis appears to always require a payband
)
)
} catch (e: Exception) {
telemetryClient.trackEvent("activity-allocation-create-failed", telemetryMap)
throw e
}
telemetryMap["offenderProgramReferenceId"] = nomisResponse.offenderProgramReferenceId.toString()
telemetryClient.trackEvent("activity-allocation-created-event", telemetryMap)
}
}
}
fun deallocate(allocationEvent: AllocationDomainEvent) {
activitiesApiService.getAllocation(allocationEvent.additionalInformation.allocationId).let { allocation ->
mappingService.getMappingGivenActivityScheduleId(allocationEvent.additionalInformation.scheduleId)
.let { mapping ->
val telemetryMap = mutableMapOf(
"allocationId" to allocation.id.toString(),
"offenderNo" to allocation.prisonerNumber,
"bookingId" to allocation.bookingId.toString(),
)
val nomisResponse = try {
nomisApiService.deallocate(
mapping.nomisCourseActivityId,
allocation.bookingId!!,
EndOffenderProgramProfileRequest(
endDate = allocation.endDate!!,
endReason = allocation.deallocatedReason, // TODO SDI-615 probably will need a mapping
// endComment = allocation.?, // TODO SDI-615 could put something useful in here
)
)
} catch (e: Exception) {
telemetryClient.trackEvent("activity-deallocate-failed", telemetryMap)
throw e
}
telemetryMap["offenderProgramReferenceId"] = nomisResponse.offenderProgramReferenceId.toString()
telemetryClient.trackEvent("activity-deallocate-event", telemetryMap)
}
}
}
private fun toNomisActivity(schedule: ActivitySchedule, activity: Activity): CreateActivityRequest {
return CreateActivityRequest(
code = "${activity.id}-${schedule.id}",
startDate = activity.startDate,
endDate = activity.endDate,
prisonId = activity.prisonCode,
internalLocationId = schedule.internalLocation?.id?.toLong(),
capacity = schedule.capacity,
payRates = activity.pay.map { p ->
PayRateRequest(
incentiveLevel = p.incentiveLevel!!,
payBand = p.prisonPayBand.nomisPayBand.toString(),
rate = BigDecimal(p.rate!!).movePointLeft(2)
)
},
description = "${activity.description} - ${schedule.description}",
minimumIncentiveLevelCode = activity.minimumIncentiveLevel,
programCode = activity.category.code,
payPerSession = activity.payPerSession.value,
)
}
fun createRetry(context: ActivityContext) {
mappingService.createMapping(
ActivityMappingDto(
nomisCourseActivityId = context.nomisCourseActivityId,
activityScheduleId = context.activityScheduleId,
mappingType = "ACTIVITY_CREATED",
)
)
}
}
data class ScheduleDomainEvent(
val eventType: String,
val additionalInformation: ScheduleAdditionalInformation,
val version: String,
val description: String,
val occurredAt: LocalDateTime,
)
data class ScheduleAdditionalInformation(
val activityScheduleId: Long,
)
data class AllocationDomainEvent(
val eventType: String,
val version: String,
val description: String,
val occurredAt: LocalDateTime,
val additionalInformation: AllocationAdditionalInformation,
)
data class AllocationAdditionalInformation(
val scheduleId: Long,
val allocationId: Long,
)
| 0 | Kotlin | 0 | 1 | 42856030d669d44199309cdc6911e13313efc91a | 9,356 | hmpps-prisoner-to-nomis-update | MIT License |
projects/effective-proposal-framework-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/epf/CaseDetailsController.kt | ministryofjustice | 500,855,647 | false | null | package uk.gov.justice.digital.hmpps.epf
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
@RestController
class CaseDetailsController(private val caseDetailsService: CaseDetailsService) {
@PreAuthorize("hasRole('EPF_CONTEXT')")
@GetMapping(value = ["/case-details/{crn}/{eventNumber}"])
fun handle(
@PathVariable("crn") crn: String,
@PathVariable("eventNumber") eventNumber: Int
) = caseDetailsService.caseDetails(crn, eventNumber)
}
| 2 | Kotlin | 0 | 2 | 13b6803617c9fb746072bc5a77fdc43691a4b864 | 663 | hmpps-probation-integration-services | MIT License |
src/test/kotlin/me/stockingd/current/operators/RangeKtTest.kt | dmstocking | 375,025,377 | false | null | package me.stockingd.current.operators
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
internal class RangeKtTest : DescribeSpec({
describe("range") {
it("should provide the values from start to end-1") {
range(0, 10)
.toList()
.shouldBe(listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
}
}
})
| 0 | Kotlin | 0 | 0 | 6e4b04e47038b0a402a5732adfbc70c52347243d | 386 | current | MIT License |
src/main/java/me/han/muffin/client/utils/CrystalRenderUtils.kt | SmallFishDD | 425,272,585 | false | {"Kotlin": 1725682, "Java": 943392, "GLSL": 15937} | package me.han.muffin.client.utils
import org.lwjgl.util.vector.Quaternion
import kotlin.math.pow
object CrystalRenderUtils {
// Rotation of individual cubelets
val cubeletStatus = arrayOf(
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion(),
Quaternion()
)
// Get ID of cublet by position
val cubletLookup = arrayOf(
arrayOf(intArrayOf(17, 9, 0), intArrayOf(20, 16, 3), intArrayOf(23, 15, 6)),
arrayOf(intArrayOf(18, 10, 1), intArrayOf(21, -1, 4), intArrayOf(24, 14, 7)),
arrayOf(intArrayOf(19, 11, 2), intArrayOf(22, 12, 5), intArrayOf(25, 13, 8))
)
// Get cublet IDs of a side
val cubeSides = arrayOf(
intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8),
intArrayOf(19, 18, 17, 22, 21, 20, 25, 24, 23),
intArrayOf(0, 1, 2, 9, 10, 11, 17, 18, 19),
intArrayOf(23, 24, 25, 15, 14, 13, 6, 7, 8),
intArrayOf(17, 9, 0, 20, 16, 3, 23, 15, 6),
intArrayOf(2, 11, 19, 5, 12, 22, 8, 13, 25)
)
// Transformations of cube sides
val cubeSideTransforms = arrayOf(
intArrayOf(0, 0, 1),
intArrayOf(0, 0, -1),
intArrayOf(0, 1, 0),
intArrayOf(0, -1, 0),
intArrayOf(-1, 0, 0),
intArrayOf(1, 0, 0)
)
// extra method from different class
fun easeInOutCubic(t: Double): Double {
return if (t < 0.5) 4 * t * t * t else 1 - (-2 * t + 2).pow(3.0) / 2
}
} | 1 | Kotlin | 2 | 2 | 13235eada9edd9ccca039dea4d3a59cc7a930830 | 1,918 | muffin-0.10.4-src-leaked | MIT License |
src/main/kotlin/su/sonoma/lostriver/client/renderer/FinsRenderer.kt | saddydead1 | 837,735,532 | false | {"Kotlin": 144217, "Java": 475} | package su.sonoma.lostriver.client.renderer
import net.minecraft.resources.ResourceLocation
import software.bernie.geckolib.model.DefaultedItemGeoModel
import software.bernie.geckolib.renderer.GeoArmorRenderer
import su.sonoma.lostriver.item.FinsArmorItem
class FinsRenderer :
GeoArmorRenderer<FinsArmorItem>(DefaultedItemGeoModel(ResourceLocation("lostriver", "armor/fins")))
| 0 | Kotlin | 0 | 2 | 7ba750864341d795c2fd6c2ac0dafff99ab08c3d | 384 | lostriver | MIT License |
src/ar/mangalionz/src/eu/kanade/tachiyomi/extension/ar/mangalionz/MangaLionz.kt | keiyoushi | 740,710,728 | false | {"Kotlin": 5891570, "JavaScript": 2160} | package eu.kanade.tachiyomi.extension.ar.mangalionz
import eu.kanade.tachiyomi.multisrc.madara.Madara
import eu.kanade.tachiyomi.source.model.SManga
import org.jsoup.nodes.Element
class MangaLionz : Madara("MangaLionz", "https://mangalionz.org", "ar") {
override val useLoadMoreRequest = LoadMoreStrategy.Always
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
with(element) {
selectFirst(popularMangaUrlSelector)!!.let {
manga.setUrlWithoutDomain(it.attr("abs:href"))
manga.title = it.ownText()
}
selectFirst("img")?.let {
manga.thumbnail_url = imageFromElement(it)?.replace("mangalionz", "mangalek")
}
}
return manga
}
override val chapterUrlSuffix = ""
}
| 249 | Kotlin | 271 | 1,198 | 16011407c56035f33abbb6cd6b4fabbe630e7ad2 | 852 | extensions-source | Apache License 2.0 |
src/main/kotlin/cn/taskeren/op/gt/init/OP_GTRegistrar.kt | ElytraServers | 842,807,386 | false | {"Kotlin": 193275, "Java": 14047, "TypeScript": 1934} | package cn.taskeren.op.gt.init
import appeng.api.AEApi
import cn.taskeren.op.ae.OP_AEUpgrades
import cn.taskeren.op.gt.addRecipe
import cn.taskeren.op.gt.addRecipeSimple
import cn.taskeren.op.gt.item.OP_GeneratedAEUpgradeItem
import cn.taskeren.op.gt.item.OP_GeneratedItem
import cn.taskeren.op.gt.item.impl.ActiveTransformerExplosionCoreItemBehaviour
import cn.taskeren.op.gt.item.impl.DebugItemBehaviour
import cn.taskeren.op.gt.item.impl.InsuranceReceiptItemBehaviour
import cn.taskeren.op.gt.registerItem
import cn.taskeren.op.gt.registerMachine
import cn.taskeren.op.gt.single.OP_ActiveTransformerRack
import cn.taskeren.op.gt.single.OP_BalancedOutputHatch
import cn.taskeren.op.gt.single.OP_DebugEnergyHatch
import cn.taskeren.op.gt.single.OP_InsuranceCounter
import cn.taskeren.op.gt.single.OP_OverpowerMachine
import cn.taskeren.op.gt.single.OP_UniHatch
import cn.taskeren.op.gt.useItemStackPostInit
import cn.taskeren.op.gt.utils.PatternRecipeBuilder
import cn.taskeren.op.gt.utils.PatternRecipeBuilder.X
import com.github.technus.tectech.thing.CustomItemList
import com.github.technus.tectech.thing.casing.TT_Container_Casings
import gregtech.api.enums.ItemList
import gregtech.api.enums.Materials
import gregtech.api.enums.TierEU
import gregtech.api.recipe.RecipeMaps
import gregtech.api.util.GT_ModHandler
import gregtech.api.util.GT_RecipeBuilder
import gregtech.api.util.GT_Utility
import gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList
import net.minecraft.item.ItemStack
import com.dreammaster.gthandler.CustomItemList as DreamItemList
object OP_GTRegistrar {
fun registerAllMachines() {
registerSimpleItems()
registerAdditionalAEUpgrades()
registerSingleMachines()
}
private fun registerSimpleItems() = with(OP_GeneratedItem) {
OP_ItemList.DyingBioChip.registerItem {
// #tr gt.metaitem.op.32001.name
// #en Dying Bio Chip
// #tr gt.metaitem.op.32001.tooltip
// #en Squeezed Living Bio Chip
addItem(it, "Dying Bio Chip", "Squeezed Living Bio Chip")
}
OP_ItemList.CertifiedElectrician.registerItem {
// #tr gt.metaitem.op.32002.name
// #en Certified Electrician
// #zh 电工资格证
// #tr gt.metaitem.op.32002.tooltip
// #en Proof of your qualifications on Electrical Engineering
// #zh 证明你在电气工程的资历
addItem(it, "Certified Electrician", "Proof of your qualifications on Electrical Engineering")
}
OP_ItemList.InsuranceReceipt.registerItem {
// #tr gt.metaitem.op.32003.name
// #en Insurance Receipt
// #zh 保险单
addItem(it, "Insurance Receipt", null, InsuranceReceiptItemBehaviour)
}
OP_ItemList.ActiveTransformerExplosionCore.registerItem {
// #tr gt.metaitem.op.32004.name
// #en Active Transformer Explosion Core
// #zh 有源变压器爆炸核心
addItem(it, "Active Transformer Explosion Core", null, ActiveTransformerExplosionCoreItemBehaviour)
}.addRecipe(RecipeMaps.hammerRecipes) {
itemInputs(CustomItemList.Machine_Multi_Transformer.get(1)) // active transformer
itemOutputs(it.copy().also { it.stackSize = 8 })
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_LV)
}
OP_ItemList.DebugItem.registerItem {
// #tr gt.metaitem.op.32005.name
// #en Overpowered Debug Item
// #zh Overpowered 侦错物品
addItem(it, "Overpowered Debug Item", null, DebugItemBehaviour)
}
}
private fun registerAdditionalAEUpgrades() = with(OP_GeneratedAEUpgradeItem) {
OP_ItemList.ProgrammedUpgrade.registerItem {
// #tr gt.metaitem.op.ae.32000.name
// #en Programmed Upgrade
// #zh 编程卡
// #tr gt.metaitem.op.ae.32000.tooltip
// #en Adjust Configuration Circuit by Pattern
// #zh 根据样板调整虚拟电路板
addItem(it, "Programmed Upgrade", "Adjust Configuration Circuit by Pattern")
}.useItemStackPostInit {
registerUpgrade(it, OP_AEUpgrades.programmedUpgrade)
}.addRecipeSimple {
val definitions = AEApi.instance().definitions()
GT_ModHandler.addCraftingRecipe(
it,
arrayOf(
"BC",
'B', definitions.materials().basicCard().maybeStack(1).get(),
'C', GT_Utility.getIntegratedCircuit(0)
)
)
}
}
private fun registerSingleMachines() {
// #tr gt.blockmachines.overpower_machine.name
// #en Incredible Malicious Machine Overpowering System
// #zh 超级绝绝子机器强化系统
OP_MachineItemList.OverpowerMachine.registerMachine {
OP_OverpowerMachine(it, "overpower_machine", "Incredible Malicious Machine Overpowering System", 9)
}
// #tr gt.blockmachines.active_transformer_rack.name
// #en Active Transformer Rack
// #zh 有源变压器机械架
// #tw 有源變壓器機械架
OP_MachineItemList.ActiveTransformerRack.registerMachine {
OP_ActiveTransformerRack(it, "active_transformer_rack", "Active Transformer Rack", 9)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemStack(TT_Container_Casings.sBlockCasingsTT, 4), DreamItemList.HighEnergyFlowCircuit.get(1))
itemOutputs(it.copy().also { it.stackSize = 4 })
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_LuV)
}
// #tr gt.blockmachines.insurance_counter.name
// #en Galactic Inc. Insurance Counter
// #zh 星际保险公司柜台
OP_MachineItemList.InsuranceCounter.registerMachine {
OP_InsuranceCounter(it, "insurance_counter", "Galactic Inc. Insurance Counter", 1)
}.addRecipeSimple {
with(PatternRecipeBuilder) {
GT_ModHandler.addCraftingRecipe(
it,
arrayOf(
"WCW",
"XHX",
"WCW",
'W',
X.WIRE,
'C',
X.CIRCUIT,
'X',
GregtechItemList.TransmissionComponent_LV.get(1),
'H',
X.HULL
).withTier(1)
)
}
}
// region UniHatch
// #tr gt.blockmachines.uni_hatch_ulv.name
// #en UniHatch ULV
// #zh 组合式输入仓 ULV
OP_MachineItemList.UniHatch_ULV.registerMachine {
OP_UniHatch(it, "uni_hatch_ulv", "UniHatch ULV", 0)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_ULV.get(1), ItemList.Hatch_Input_Bus_ULV.get(1), ItemList.Hatch_Input_ULV.get(1))
fluidInputs(Materials.Glue.getFluid(2L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(16 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_ULV)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_ULV.get(1), ItemList.Hatch_Input_Bus_ULV.get(1), ItemList.Hatch_Input_ULV.get(1))
fluidInputs(Materials.AdvancedGlue.getFluid(1L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_ULV)
}
// #tr gt.blockmachines.uni_hatch_lv.name
// #en UniHatch LV
// #zh 组合式输入仓 LV
OP_MachineItemList.UniHatch_LV.registerMachine {
OP_UniHatch(it, "uni_hatch_lv", "UniHatch LV", 1)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_LV.get(1), ItemList.Hatch_Input_Bus_LV.get(1), ItemList.Hatch_Input_LV.get(1))
fluidInputs(Materials.AdvancedGlue.getFluid(4L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(16 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_LV)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_LV.get(1), ItemList.Hatch_Input_Bus_LV.get(1), ItemList.Hatch_Input_LV.get(1))
fluidInputs(Materials.Plastic.getMolten(2L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_LV)
}
// #tr gt.blockmachines.uni_hatch_mv.name
// #en UniHatch MV
// #zh 组合式输入仓 MV
OP_MachineItemList.UniHatch_MV.registerMachine {
OP_UniHatch(it, "uni_hatch_mv", "UniHatch MV", 2)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_MV.get(1), ItemList.Hatch_Input_Bus_MV.get(1), ItemList.Hatch_Input_MV.get(1))
fluidInputs(Materials.Plastic.getMolten(16L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(16 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_MV)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_MV.get(1), ItemList.Hatch_Input_Bus_MV.get(1), ItemList.Hatch_Input_MV.get(1))
fluidInputs(Materials.PolyvinylChloride.getMolten(4L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_MV)
}
// #tr gt.blockmachines.uni_hatch_hv.name
// #en UniHatch HV
// #zh 组合式输入仓 HV
OP_MachineItemList.UniHatch_HV.registerMachine {
OP_UniHatch(it, "uni_hatch_hv", "UniHatch HV", 3)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_HV.get(1), ItemList.Hatch_Input_Bus_HV.get(1), ItemList.Hatch_Input_HV.get(1))
fluidInputs(Materials.PolyvinylChloride.getMolten(24L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(16 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_HV)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_HV.get(1), ItemList.Hatch_Input_Bus_HV.get(1), ItemList.Hatch_Input_HV.get(1))
fluidInputs(Materials.Polytetrafluoroethylene.getMolten(4L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_HV)
}
// #tr gt.blockmachines.uni_hatch_ev.name
// #en UniHatch EV
// #zh 组合式输入仓 EV
OP_MachineItemList.UniHatch_EV.registerMachine {
OP_UniHatch(it, "uni_hatch_ev", "UniHatch EV", 4)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_EV.get(1), ItemList.Hatch_Input_Bus_EV.get(1), ItemList.Hatch_Input_EV.get(1))
fluidInputs(Materials.Polytetrafluoroethylene.getMolten(32L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(16 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_EV)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(ItemList.Hull_EV.get(1), ItemList.Hatch_Input_Bus_EV.get(1), ItemList.Hatch_Input_EV.get(1))
fluidInputs(Materials.Polybenzimidazole.getMolten(16L * GT_RecipeBuilder.INGOTS))
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_EV)
}
// endregion
// region Balanced Output Hatch
// #tr gt.blockmachines.balanced_output_hatch_hv.name
// #en Balanced Output Hatch HV
// #zh 平衡输出仓 HV
OP_MachineItemList.BalancedOutputHatch_HV.registerMachine {
OP_BalancedOutputHatch(it, "balanced_output_hatch_hv", "Balanced Output Hatch HV", 3)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(
ItemList.Hatch_Output_HV.get(1),
ItemList.Cover_FluidStorageMonitor.get(1),
ItemList.Cover_Controller.get(1)
)
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_HV)
}
// #tr gt.blockmachines.balanced_output_hatch_luv.name
// #en Balanced Output Hatch LuV
// #zh 平衡输出仓 LuV
OP_MachineItemList.BalancedOutputHatch_LuV.registerMachine {
OP_BalancedOutputHatch(it, "balanced_output_hatch_luv", "Balanced Output Hatch LuV", 6)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(
ItemList.Hatch_Output_LuV.get(1),
ItemList.Cover_FluidStorageMonitor.get(1),
ItemList.Cover_Controller.get(1)
)
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_HV)
}
// #tr gt.blockmachines.balanced_output_hatch_uhv.name
// #en Balanced Output Hatch UHV
// #zh 平衡输出仓 UHV
OP_MachineItemList.BalancedOutputHatch_UHV.registerMachine {
OP_BalancedOutputHatch(it, "balanced_output_hatch_uhv", "Balanced Output Hatch HV", 9)
}.addRecipe(RecipeMaps.assemblerRecipes) {
itemInputs(
ItemList.Hatch_Output_MAX.get(1),
ItemList.Cover_FluidStorageMonitor.get(1),
ItemList.Cover_Controller.get(1)
)
itemOutputs(it)
duration(8 * GT_RecipeBuilder.SECONDS)
eut(TierEU.RECIPE_HV)
}
// endregion
// #tr gt.blockmachines.debug_energy_hatch.name
// #en Ascendant Realm Paracausal Manipulating Unit
// #zh 上维领域超因果单元
// #tw 高等維度超因果單元
OP_MachineItemList.DebugEnergyHatch.registerMachine {
OP_DebugEnergyHatch(it, "debug_energy_hatch", "Ascendant Realm Paracausal Manipulating Unit")
}
}
}
| 0 | Kotlin | 0 | 9 | a6028fc6c7c0635b4b0a7be91deb562dd28938f1 | 11,702 | Overpowered | MIT License |
src/day05/Day05.kt | PoisonedYouth | 571,927,632 | false | null | package day05
import readInput
import java.util.*
val cratesRegex = Regex("""\[(.)\]""")
val instructionRegex = Regex("""move (\d+) from (\d+) to (\d+)""")
data class Instruction(
val amount: Int,
val origin: Int,
val target: Int
)
fun main() {
fun initStack(input: List<String>): List<Stack<String>> {
val stacks = List(9) { Stack<String>() }
input.takeWhile { it.startsWith("[") }.reversed().map { line ->
val crates = cratesRegex.findAll(line)
crates.forEach {
stacks[it.range.first / 4].push(it.groupValues[1])
}
}
return stacks
}
fun initInstructionList(input: List<String>): List<Instruction> {
val instructions = input.dropWhile { !it.startsWith("move") }.map { line ->
val instructionInput = instructionRegex.find(line) ?: error("Invalid Input!")
val (amount, origin, target) = instructionInput.groupValues.drop(1).toList()
Instruction(
amount = amount.toInt(),
origin = origin.toInt(),
target = target.toInt()
)
}
return instructions
}
fun part1(input: List<String>): String {
val stacks = initStack(input)
val instructions = initInstructionList(input)
instructions.forEach { instruction ->
repeat(instruction.amount) {
val value = stacks[instruction.origin - 1].pop()
stacks[instruction.target - 1].push(value)
}
}
return stacks.joinToString("") { it.peek() ?: "" }
}
fun part2(input: List<String>): String {
val stacks = initStack(input)
val instructions = initInstructionList(input)
instructions.forEach { instruction ->
val changes = mutableListOf<String?>()
repeat(instruction.amount) {
changes.add(stacks[instruction.origin - 1].pop())
}
changes.reversed().forEach { stacks[instruction.target - 1].push(it) }
}
return stacks.joinToString("") { it.peek() ?: "" }
}
val input = readInput("day05/Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | dbcb627e693339170ba344847b610f32429f93d1 | 2,230 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/main/kotlin/ru/sandello/binaryconverter/repository/NumberSystemRepository.kt | jedi1150 | 153,152,563 | false | {"Kotlin": 193139, "Ruby": 3060} | package ru.sandello.binaryconverter.repository
import numsys.model.Radix
import ru.sandello.binaryconverter.model.NumberSystem
import ru.sandello.binaryconverter.numsys.NumberSystemDataSource
import javax.inject.Inject
class NumberSystemRepository @Inject constructor(
private val numberSystemDataSource: NumberSystemDataSource,
) {
suspend fun convert(value: NumberSystem, toRadix: Radix): NumberSystem? = numberSystemDataSource.convert(value, toRadix)
}
| 5 | Kotlin | 3 | 14 | 93edb52b1dd9d904a6d0dfc5c1609dd2bc57dba0 | 468 | number-systems | MIT License |
apps/android/app/src/main/kotlin/com/taskodoro/android/app/navigation/graphs/tasks/TaskNewNavigation.kt | felipejoglar | 457,288,734 | false | {"Kotlin": 219352, "Swift": 804} | /*
* Copyright 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.taskodoro.android.app.navigation.graphs.tasks
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.taskodoro.android.app.tasks.new.TaskNewScreen
import com.taskodoro.android.app.tasks.new.TaskNewViewModel
import com.taskodoro.tasks.new.TaskNewUseCase
import kotlinx.coroutines.Dispatchers
import moe.tlaster.precompose.navigation.BackHandler
import moe.tlaster.precompose.navigation.NavOptions
import moe.tlaster.precompose.navigation.Navigator
import moe.tlaster.precompose.navigation.RouteBuilder
import moe.tlaster.precompose.viewmodel.viewModel
const val TASK_NEW_ROUTE = "$TASK_GRAPH_ROUTE/new"
fun Navigator.navigateToTaskNew(options: NavOptions? = null) {
navigate(TASK_NEW_ROUTE, options)
}
fun RouteBuilder.taskNewScreen(
taskNew: TaskNewUseCase,
onNewTask: () -> Unit,
onDiscardChanges: () -> Unit,
) {
scene(
route = TASK_NEW_ROUTE,
) {
val viewModel = viewModel { savedStateHolder ->
TaskNewViewModel(taskNew, Dispatchers.IO, savedStateHolder)
}
val state by viewModel.uiState.collectAsState()
var openConfirmationDialog by remember { mutableStateOf(false) }
val onBackPressed = {
if (state.title.isNotBlank()) {
openConfirmationDialog = true
} else {
onDiscardChanges()
}
}
BackHandler(enabled = state.title.isNotEmpty(), onBack = onBackPressed)
TaskNewScreen(
state = state,
openConfirmationDialog = openConfirmationDialog,
onTitleChanged = viewModel::onTitleChanged,
onDescriptionChanged = viewModel::onDescriptionChanged,
onDueDateChanged = viewModel::onDueDateChanged,
onSubmitClicked = viewModel::onSubmitClicked,
onNewTask = onNewTask,
onErrorShown = viewModel::onErrorShown,
onDismissConfirmationDialog = { openConfirmationDialog = false },
onDiscardChanges = onDiscardChanges,
onBackClicked = { onBackPressed() },
)
}
}
| 9 | Kotlin | 0 | 2 | c121ce38e0d2dbe25a80d96e5e5812fae69f28b8 | 2,877 | taskodoro-apps | Apache License 2.0 |
API/src/main/kotlin/net/sourcebot/impl/command/HelpCommand.kt | TheSourceCodeLLC | 271,902,483 | false | null | package net.sourcebot.impl.command
import me.hwiggy.kommander.arguments.*
import net.dv8tion.jda.api.entities.Message
import net.sourcebot.Source
import net.sourcebot.api.command.PermissionCheck
import net.sourcebot.api.command.PermissionCheck.Type.GUILD_ONLY
import net.sourcebot.api.command.PermissionCheck.Type.VALID
import net.sourcebot.api.command.RootCommand
import net.sourcebot.api.module.SourceModule
import net.sourcebot.api.response.Response
import net.sourcebot.api.response.StandardErrorResponse
import net.sourcebot.api.response.StandardInfoResponse
import net.sourcebot.api.response.error.GlobalAdminOnlyResponse
import net.sourcebot.api.response.error.GuildOnlyCommandResponse
class HelpCommand : RootCommand() {
override val name = "help"
override val description = "Shows command / module information."
override val synopsis = Synopsis {
optParam(
"topic", "The command or module to show help for. Empty to show the module listing.",
Adapter.single()
)
optParam(
"children...", "The sub-command(s) to get help for, in the case that `topic` is a command.",
Adapter.slurp(" ")
)
}
override val deleteSeconds = 60L
private val permissionHandler = Source.PERMISSION_HANDLER
private val commandHandler = Source.COMMAND_HANDLER
private val moduleHandler = Source.MODULE_HANDLER
override fun execute(sender: Message, arguments: Arguments.Processed): Response {
val topic = arguments.optional<String>("topic")
val children = arguments.optional<String>("children...")
if (topic == null) {
val modules = moduleHandler.loader.getExtensions()
val enabled = modules.filter { it.enabled }
if (enabled.isEmpty()) return StandardInfoResponse(
"Module Index",
"There are currently no modules enabled."
)
val sorted = enabled.sortedBy { it.name }.joinToString("\n") {
"**${it.name}**: ${it.description}"
}
return StandardInfoResponse(
"Module Index",
"""
Below are valid module names and descriptions.
Module names may be passed into this command for more detail.
Command names may be passed into this command for usage information.
""".trimIndent()
).also {
if (sender.isFromGuild) {
val prefix = commandHandler.getPrefix(sender.guild)
it.appendDescription("\nThis Guild's prefix is: `$prefix`")
}
it.addField("Modules", sorted, false) as Response
}
}
val asCommand = commandHandler.getCommand(topic)
if (asCommand != null) {
val childArgs = if (children != null) Arguments.parse(children) else Arguments(emptyArray())
val permCheck = commandHandler.checkPermissions(sender, asCommand, childArgs)
val command = permCheck.command
return when (permCheck.type) {
PermissionCheck.Type.GLOBAL_ONLY -> GlobalAdminOnlyResponse()
GUILD_ONLY -> GuildOnlyCommandResponse()
PermissionCheck.Type.NO_PERMISSION -> {
val data = permissionHandler.getData(sender.guild)
val permissible = data.getUser(sender.member!!)
permissionHandler.getPermissionAlert(
command.guildOnly, sender.jda, permissible, command.permission!!
)
}
VALID -> {
StandardInfoResponse(
"Command Information:",
"Arguments surrounded by <> are required, those surrounded by () are optional."
).apply {
addField("Description:", command.description, false)
addField(
"Usage:", when {
sender.isFromGuild -> commandHandler.getSyntax(sender.guild, command)
else -> commandHandler.getSyntax(command)
}, false
)
addField("Detail:", command.synopsis.buildParameterDetail(
{
when (it) {
is Group<*> -> renderGroup(it)
else -> renderParameter(it)
}
},
{ it.joinToString("\n") }
) ?: "This command has no parameters.", false)
if (command.aliases.isNotEmpty())
addField("Aliases:", command.aliases.joinToString(), false)
if (command.permission != null)
addField("Permission:", "`${command.permission}`", false)
if (command.getChildren().isNotEmpty())
addField("Subcommands:", command.getChildren().joinToString(), false)
}
}
}
}
val asModule: SourceModule? = moduleHandler.loader.findExtension(topic)
if (asModule != null) {
val response = StandardInfoResponse("${asModule.name} Module Assistance")
val config = when {
asModule.configurationInfo != null -> {
asModule.configurationInfo!!.resolved.entries.joinToString("\n") { (k, v) ->
"`$k`: $v"
}
}
else -> null
} ?: "This module does not have any configuration info."
response.addField("Configuration", config, false)
val commands = commandHandler.getCommands(asModule)
if (commands.isEmpty()) return response.apply {
addField("Commands", "This module does not have any commands.", false)
}
val grouped = commands.groupBy {
commandHandler.checkPermissions(sender, it).type
}
val valid = grouped[VALID] ?: emptyList()
val guildOnly = grouped[GUILD_ONLY] ?: emptyList()
if (valid.isEmpty() && guildOnly.isEmpty()) return response.apply {
addField("Commands", "You do not have access to any of this module's commands.", false)
}
val prefix =
if (sender.isFromGuild) commandHandler.getPrefix(sender.guild)
else commandHandler.getPrefix()
if (valid.isNotEmpty()) {
val listing = valid.sortedBy { it.name }.joinToString("\n") {
"**$prefix${it.name}**: ${it.description}"
}
response.addField("Usable Commands:", listing, false)
}
if (guildOnly.isNotEmpty()) {
val listing = guildOnly.sortedBy { it.name }.joinToString("\n") {
"**$prefix${it.name}**: ${it.description}"
}
response.addField("Guild Commands:", listing, false)
}
return response
}
return StandardErrorResponse(
"Unknown Topic!",
"There is no command or module named `$topic`!"
)
}
private fun renderParameter(parameter: Parameter<*>) = StringBuilder().apply {
append("**${parameter.name}**: ${parameter.description}")
if (parameter.adapter is BoundAdapter<*>) {
append(" ")
val adapter = parameter.adapter as BoundAdapter<*>
if (adapter.min != null && adapter.max != null) {
append("Min: ${adapter.min}, Max: ${adapter.max}")
} else {
if (adapter.min != null) {
append("Min: ${adapter.min}")
}
if (adapter.max != null) {
append("Max: ${adapter.max}")
}
}
}
if (parameter.default != null) {
append(" (Default: _${parameter.default}_)")
}
}.toString()
private fun renderGroup(group: Group<*>) = StringBuilder().apply {
append("**${group.name}**: ${group.description}")
group.choices.forEach { (option, description) ->
append("\n↳ **${option.synopsisName}**: $description")
}
if (group.default != null) {
append("\n(Default: _${group.default!!.synopsisName}_)")
}
}.toString()
} | 5 | Kotlin | 8 | 9 | ff4a07c69a009d118b10bc4d57f6e567334ed768 | 8,676 | Source | MIT License |
fabric/src/main/kotlin/org/valkyrienskies/mod/fabric/common/ValkyrienSkiesModFabric.kt | Rubydesic | 518,612,089 | false | {"Java Properties": 1, "Gradle": 7, "Shell": 1, "Markdown": 2, "EditorConfig": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Git Config": 1, "XML": 6, "Kotlin": 36, "Java": 48, "JSON": 13, "INI": 3, "TOML": 1, "YAML": 3} | package org.valkyrienskies.mod.fabric.common
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.resource.IdentifiableResourceReloadListener
import net.fabricmc.fabric.api.resource.ResourceManagerHelper
import net.minecraft.core.Registry
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.packs.PackType.SERVER_DATA
import net.minecraft.server.packs.resources.PreparableReloadListener.PreparationBarrier
import net.minecraft.server.packs.resources.ResourceManager
import net.minecraft.util.profiling.ProfilerFiller
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.MobCategory
import net.minecraft.world.item.BlockItem
import net.minecraft.world.item.CreativeModeTab
import net.minecraft.world.item.Item.Properties
import net.minecraft.world.level.block.Block
import org.valkyrienskies.mod.common.ValkyrienSkiesMod
import org.valkyrienskies.mod.common.block.TestChairBlock
import org.valkyrienskies.mod.common.config.MassDatapackResolver
import org.valkyrienskies.mod.common.entity.ShipMountingEntity
import org.valkyrienskies.mod.common.item.ShipCreatorItem
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
class ValkyrienSkiesModFabric : ModInitializer {
override fun onInitialize() {
ValkyrienSkiesMod.TEST_CHAIR = TestChairBlock
ValkyrienSkiesMod.SHIP_CREATOR_ITEM = ShipCreatorItem(Properties().tab(CreativeModeTab.TAB_MISC), 0.5)
ValkyrienSkiesMod.SHIP_CREATOR_ITEM_SMALLER = ShipCreatorItem(Properties().tab(CreativeModeTab.TAB_MISC), 0.5)
ValkyrienSkiesMod.SHIP_MOUNTING_ENTITY_TYPE = EntityType.Builder.of(
::ShipMountingEntity,
MobCategory.MISC
).sized(.3f, .3f)
.build(ResourceLocation(ValkyrienSkiesMod.MOD_ID, "ship_mounting_entity").toString())
ValkyrienSkiesMod.init()
registerBlockAndItem("test_chair", ValkyrienSkiesMod.TEST_CHAIR)
Registry.register(
Registry.ITEM, ResourceLocation(ValkyrienSkiesMod.MOD_ID, "ship_creator"),
ValkyrienSkiesMod.SHIP_CREATOR_ITEM
)
Registry.register(
Registry.ITEM, ResourceLocation(ValkyrienSkiesMod.MOD_ID, "ship_creator_smaller"),
ValkyrienSkiesMod.SHIP_CREATOR_ITEM_SMALLER
)
Registry.register(
Registry.ENTITY_TYPE, ResourceLocation(ValkyrienSkiesMod.MOD_ID, "ship_mounting_entity"),
ValkyrienSkiesMod.SHIP_MOUNTING_ENTITY_TYPE
)
VSFabricNetworking.injectFabricPacketSenders()
VSFabricNetworking.registerServerPacketHandlers()
// registering mass
val loader = MassDatapackResolver.loader // the get makes a new instance so get it only once
ResourceManagerHelper.get(SERVER_DATA)
.registerReloadListener(object : IdentifiableResourceReloadListener {
override fun getFabricId(): ResourceLocation {
return ResourceLocation(ValkyrienSkiesMod.MOD_ID, "vs_mass")
}
override fun reload(
stage: PreparationBarrier,
resourceManager: ResourceManager,
preparationsProfiler: ProfilerFiller,
reloadProfiler: ProfilerFiller,
backgroundExecutor: Executor,
gameExecutor: Executor
): CompletableFuture<Void> {
return loader.reload(
stage, resourceManager, preparationsProfiler, reloadProfiler,
backgroundExecutor, gameExecutor
)
}
})
}
private fun registerBlockAndItem(registryName: String, block: Block) {
Registry.register(
Registry.BLOCK, ResourceLocation(ValkyrienSkiesMod.MOD_ID, registryName),
block
)
Registry.register(
Registry.ITEM, ResourceLocation(ValkyrienSkiesMod.MOD_ID, registryName),
BlockItem(block, Properties().tab(CreativeModeTab.TAB_MISC))
)
}
}
| 1 | null | 1 | 1 | dc3df9559331b38297ee5b44b8e3d75140c244b3 | 4,097 | Valkyrien-Skies-2 | Apache License 2.0 |
app/src/kotlin/java/com/bear2b/sampleapp/App.kt | tdeffains | 226,653,741 | false | {"Batchfile": 1, "Shell": 1, "Markdown": 3, "Java Properties": 1, "Proguard": 1, "Java": 11, "Kotlin": 11} | package com.bear2b.sampleapp
import android.support.multidex.MultiDexApplication
import com.bear.common.sdk.BearSdk
class App : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
BearSdk.getInstance(this).init("ZJ5X1aXNdnpcH7h+XvVNKzmtReZMfMOkZOz+1LVO48l7aahhmH44NXPNTxUulk9NliD2vbHjJe9M+gyq3tZzqrdAZizz79d6zOuBkisLsCRNvTFcuZZ/RSxh3gFg9cPX1exk7zo8yU1lk/RuFtKkPRc03dKTTXR5YI0zf3wJKN3/GQUAv+z3nuq1RmB1DKmma5cDZaIrKxq9leplx9DjwtF2mwxgiyAAnkQIABvPJ1c+cGSMCydKoLCEYbD79abuiCwwZHfOk4vFvY+2aMmc1Zfs3CJlZQ4xnZGH42XA5WodLl4Ex+I1mWqAkBjn8th85TDNQUbNH3/2nyUlLQYXoVdnJhH/aH5beMSXE12+G3o/wIKugRomUUbG9lJiziw541zQYEG5eFBymcSVpbcnT/MgO5H70JY/NDpTR5GAnK6ofhoBMpvw7f5BH4q10kbHMNwsnVYRi4V0qw4X3+p2b2QQX+i66QuHZQ2ofm0/50SCvnLjE6aFvK/mNgxPXSLVlz3q1q7wi6thBsYhsD/pXQFa7nZ/8+aTRDVNbnPczyfzRsPwrN0md+7wql7lFOrDHd9/NinQopJhMxF/XTVwf+yjYKnj6oUNfcUQIjdkiOWcZfCr6n6rcWvJlQwd7ZIhJV6czWt/g+DRi4DFcl4oTAFHyLgMz4ZkyOEgky7UtTglfglO4wdlnV6biVEkQA5H4p9aVEO0eoi4AZL9dAsozgg3DumaOy5sQ6KnG45Xpt4zGAEZmIxN/qxuQtddG7eGJXpjOR97RLXJNjuDJeNs/2X1/BFQ9f+REHzPFBHFi/m+x3M+gKY3jsoYytr0GOjdcnj2Y7Dbl1NaqGEx3e2UB/UVkmjVMM71W5IDylSOFtfF81+ogbzyjpE6cMEAj8OmDWqWSXkEIgQxFle+wCQA8zZEy/Am26IKBPzCOVeMqv9Du6G8nJcGipdAvTZYCKK8TsxfqGgiq5SS8QezAQ11jO3r/ev8TZnVdXeu+VAdmcQ=")
}
} | 1 | null | 1 | 1 | ac4ce337155dee900e24e78556c7927a463f6a05 | 1,264 | bear_sdk_demo_android | Apache License 2.0 |
app/src/main/java/com/example/biodataform/SplashScreen.kt | dickysamudra09 | 260,829,509 | false | null | package com.example.biodataform
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.WindowManager
class SplashScreen : AppCompatActivity() {
private var mDelayHandler: Handler? = null
private val SPLASH_DELAY: Long = 3500
internal val mRunnable: Runnable = Runnable {
if (!isFinishing){
val intent = Intent(applicationContext, MainActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splashscreen)
mDelayHandler = Handler()
mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY)
}
public override fun onDestroy() {
if(mDelayHandler !=null){
mDelayHandler!!.removeCallbacks(mRunnable)
}
super.onDestroy()
}
}
| 0 | Kotlin | 1 | 0 | ffb3372bd13b44ee3a8a8c1df66420f169100e74 | 1,109 | SmkCoding_Project | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/util/ServiceProviderFactory.kt | uk-gov-mirror | 356,783,155 | true | {"Kotlin": 419090, "Python": 24480, "Mustache": 3868, "Dockerfile": 981, "Shell": 523} | package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AuthGroupID
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.ServiceProvider
class ServiceProviderFactory(em: TestEntityManager? = null) : EntityFactory(em) {
fun create(
id: AuthGroupID = "HARMONY_LIVING",
name: String = "<NAME>",
incomingReferralDistributionEmail: String = "<EMAIL>",
): ServiceProvider {
return save(
ServiceProvider(
id = id,
name = name,
incomingReferralDistributionEmail = incomingReferralDistributionEmail
)
)
}
}
| 0 | Kotlin | 0 | 0 | c6472e5b2eef33bbc1db83cd445f5aa51d474670 | 744 | ministryofjustice.hmpps-interventions-service | MIT License |
codes/Java/SqliteDemo/app/src/main/java/cn/edu/bistu/cs/se/sqlitedemo/MainActivity.kt | Haobaoshui | 764,701,687 | false | {"Kotlin": 443642, "Java": 369729, "CMake": 3677, "C++": 748} | package cn.edu.bistu.cs.se.sqlitedemo
import android.content.ContentValues
import android.os.Bundle
import android.provider.BaseColumns
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
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.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import cn.edu.bistu.cs.se.sqlitedemo.database.WordContract
import cn.edu.bistu.cs.se.sqlitedemo.database.WordDBHelper
import cn.edu.bistu.cs.se.sqlitedemo.ui.theme.SqliteDemoTheme
import timber.log.Timber
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.Date
class MainActivity : ComponentActivity() {
private val instance by lazy{this}//延迟加载
private val dbHelper = WordDBHelper(instance)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SqliteDemoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
sqlButtons()
}
}
}
}
//增
private fun insertWord() {
// 数据库
val db = dbHelper.writableDatabase
val values = ContentValues().apply {
put(WordContract.WordEntry.COLUMN_NAME_WORD, "dog")
put(WordContract.WordEntry.COLUMN_NAME_MEANING,"狗")
put(WordContract.WordEntry.COLUMN_NAME_SAMPLE,"I like dogs")
}
//增加新的一条记录,返回新增记录的主键
val newRowId = db?.insert(WordContract.WordEntry.TABLE_NAME, null, values)
Timber.i("$newRowId")
}
private fun insertWordBySql(){
val db = dbHelper.writableDatabase
val word="cat"
val meaning="猫"
val sample="I like cats"
val sql="""
insert into t_word(word,meaning,sample)
values ('$word','$meaning','$sample')
"""
db.execSQL(sql)
Timber.i("$word-$meaning")
}
//删
private fun deleteWord() {
val db = dbHelper.writableDatabase
//定义where子句
val selection = "${WordContract.WordEntry.COLUMN_NAME_WORD} LIKE ?"
val selectionArgs = arrayOf("cat")
val deletedRows = db.delete(WordContract.WordEntry.TABLE_NAME, selection, selectionArgs)
}
private fun deleteWordBySql() {
val db = dbHelper.writableDatabase
val word="dog"
val sql="""
delete from t_word
where word=$word
"""
db.execSQL(sql)
Timber.i("$word")
}
//改
private fun updateWord(){
val db = dbHelper.writableDatabase
val word = "sheepdog"
val values = ContentValues().apply {
put(WordContract.WordEntry.COLUMN_NAME_WORD, word)
}
val selection = "${WordContract.WordEntry.COLUMN_NAME_WORD} LIKE ?"
val selectionArgs = arrayOf("dog")
val count = db.update(
WordContract.WordEntry.TABLE_NAME,
values,
selection,
selectionArgs)
}
private fun updateWordBySql(){
val db = dbHelper.writableDatabase
val newWord="dog"
val oldword="sheepdog"
val sql="""
update t_word set
word='$newWord'
where word='$oldword'
"""
db.execSQL(sql)
}
//查
private fun queryWord(){
val db = dbHelper.readableDatabase
//定义结果集字段"select id,word,meaning,sample"
val projection = arrayOf(BaseColumns._ID,
WordContract.WordEntry.COLUMN_NAME_WORD,
WordContract.WordEntry.COLUMN_NAME_MEANING,
WordContract.WordEntry.COLUMN_NAME_SAMPLE)
//条件WHERE "word" = 'dog'
val selection = "${ WordContract.WordEntry.COLUMN_NAME_WORD} = ?"
val selectionArgs = arrayOf("dog")
//结果集中的记录次序: "order by word DESC"
val sortOrder = "${WordContract.WordEntry.COLUMN_NAME_WORD} DESC"
val cursor = db.query(
WordContract.WordEntry.TABLE_NAME, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
)
with(cursor) {
Timber.i("$count")
while (moveToNext()) {
val itemId = getLong(getColumnIndexOrThrow(BaseColumns._ID))
val word=getString(getColumnIndexOrThrow(WordContract.WordEntry.COLUMN_NAME_WORD))
Timber.i("$itemId-$word")
}
}
cursor.close()
}
private fun queryWordBySql(){
val db = dbHelper.readableDatabase
val word="d"
val sql="""
select * from t_word where word like ? order by word desc
"""
val cursor = db.rawQuery(sql, arrayOf("%$word%"))
with(cursor) {
Timber.i("$count")
while (moveToNext()) {
val itemId = getLong(getColumnIndexOrThrow(BaseColumns._ID))
val word=getString(getColumnIndexOrThrow(WordContract.WordEntry.COLUMN_NAME_WORD))
Timber.i("$itemId-$word")
}
}
cursor.close()
}
@Composable
fun sqlButtons(modifier: Modifier = Modifier) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(onClick = { insertWord() }) {
Text(stringResource(id = R.string.db_insert_method))
}
Button(onClick = { deleteWord() }) {
Text(stringResource(id = R.string.db_delete_method))
}
Button(onClick = { updateWord() }) {
Text(stringResource(id = R.string.db_update_method))
}
Button(onClick = { queryWord() }) {
Text(stringResource(id = R.string.db_query_method))
}
Button(onClick = { insertWordBySql() }) {
Text(stringResource(id = R.string.db_insert_sql))
}
Button(onClick = { deleteWordBySql() }) {
Text(stringResource(id = R.string.db_delete_sql))
}
Button(onClick = { updateWordBySql() }) {
Text(stringResource(id = R.string.db_update_sql))
}
Button(onClick = { queryWordBySql() }) {
Text(stringResource(id = R.string.db_query_sql))
}
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
SqliteDemoTheme {
sqlButtons()
}
}
}
| 0 | Kotlin | 0 | 0 | 5cf57d48cac6c62b7002d94280f0c9f8760f85cd | 7,482 | Android | MIT License |
SecondTempleTimer/src/commonMain/kotlin/sternbach/software/kosherkotlin/util/Location.kt | kdroidFilter | 849,781,239 | false | {"Kotlin": 814129} | package sternbach.software.kosherkotlin.util
import kotlinx.datetime.TimeZone
/**
* Represents a coordinate on the globe. In contrast to [GeoLocation] which has an associated timezone and place name,
* [Location] may not. This is to accommodate various platforms, which may not expose as rich information as [GeoLocation]
* requires.
*
* @param timestamp epoch milliseconds when the location was last updated.
* On some platforms (e.g. Kotlin/JS) this can be significantly delayed (I think e.g. if the user is offline, etc.)
* compared to when the location flow is updated.
* @param accuracy the margin of error in latitude and longitude. A smaller number means the [latitude] and [longitude]
* are more accurate.
* */
data class Location(
val latitude: Double,
val longitude: Double,
val elevation: Double? = null,
val accuracy: Double? = null,
val timestamp: Long? = null,
val tz: TimeZone? = null,
val locationName: String? = null,
) | 0 | Kotlin | 0 | 0 | 577cd4818376400b4acc0f580ef19def3bf9e8d9 | 976 | SecondTempleTimerLibrary | Apache License 2.0 |
python/testSrc/com/jetbrains/python/sdk/flavors/VirtualEnvReaderTest.kt | StingNevermore | 113,538,568 | true | null | package com.jetbrains.python.sdk.flavors
import com.intellij.grazie.grammar.assertIsEmpty
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.testFramework.utils.io.deleteRecursively
import org.junit.Assert.assertEquals
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Path
import java.util.regex.Pattern
import kotlin.io.path.absolutePathString
import kotlin.io.path.exists
class VirtualEnvReaderTest {
inner class Bootstrap {
val PYENV_ROOT = "PYENV_ROOT"
val cwd = FileUtilRt.createTempDirectory("venvreader", "").toPath()
val pyenv = cwd.resolve(".pyenv")
val env = HashMap<String, String>();
val virtualEnvReader = VirtualEnvReader { envVar ->
env[envVar] ?: String()
}
fun setupPyenv(versions: List<String>, binary: String) {
for (version in versions) {
addVersion(pyenv, version, binary)
}
env[PYENV_ROOT] = pyenv.absolutePathString()
}
fun addVersion(root: Path, version: String, binary: String) {
val vsdir = ensureVersions(root)
val vdir = vsdir.resolve(version)
Files.createDirectory(vdir)
if (binary.isNotEmpty()) {
Files.createFile(vdir.resolve(binary))
}
}
fun removeVersion(root: Path, version: String) {
val vsdir = ensureVersions(root)
val vdir = vsdir.resolve(version)
vdir.deleteRecursively()
}
fun ensureVersions(root: Path): Path {
if (!root.exists()) {
Files.createDirectory(root);
}
val versions = root.resolve("versions")
if (!versions.exists()) {
Files.createDirectory(versions)
}
return versions
}
}
val EMPTY_PATTERN = Pattern.compile("")
@Test
fun testHandleEmptyDirs() {
val bootstrap = Bootstrap()
// non existent dir
var interpreters = bootstrap.virtualEnvReader.findLocalInterpreters(bootstrap.pyenv, setOf("python"), EMPTY_PATTERN)
assertIsEmpty(interpreters)
// invalid data
bootstrap.env[bootstrap.PYENV_ROOT] = "aa\u0000bb"
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), EMPTY_PATTERN)
assertIsEmpty(interpreters)
// empty dir
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), EMPTY_PATTERN)
assertIsEmpty(interpreters)
// empty dir
bootstrap.setupPyenv(listOf(), "")
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), EMPTY_PATTERN)
assertIsEmpty(interpreters)
// .pyenv but no versions
Files.createDirectory(bootstrap.pyenv)
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), EMPTY_PATTERN)
assertIsEmpty(interpreters)
}
@Test
fun testCollectPaths() {
val bootstrap = Bootstrap()
// just version
bootstrap.setupPyenv(listOf("3.1.1"), "python")
var interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), EMPTY_PATTERN)
assertEquals(1, interpreters.size)
assert(interpreters[0].absolutePathString().startsWith(bootstrap.pyenv.absolutePathString()))
assert(interpreters[0].absolutePathString().endsWith("python"))
// another version w/o match
bootstrap.addVersion(bootstrap.pyenv, "3.2.1", "xxxx")
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), EMPTY_PATTERN)
assertEquals(1, interpreters.size)
// both in names
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python", "xxxx"), EMPTY_PATTERN)
assertEquals(2, interpreters.size)
assert(interpreters[0] != interpreters[1])
// name + pattern
var pattern = Pattern.compile("xxxx")
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), pattern)
assertEquals(2, interpreters.size)
assert(interpreters[0] != interpreters[1])
pattern = Pattern.compile("python")
bootstrap.removeVersion(bootstrap.pyenv, "3.2.1")
interpreters = bootstrap.virtualEnvReader.findPyenvInterpreters(setOf("python"), pattern)
assertEquals(1, interpreters.size)
assert(interpreters[0].absolutePathString().endsWith("python"))
}
} | 0 | null | 0 | 0 | 68a9dba2e125a7d8ee96ca86e965a30a8ead7e2c | 4,169 | intellij-community | Apache License 2.0 |
navigation/src/iosAndTvOs/kotlin/com/hoc081098/solivagant/navigation/AppLifecycleOwner.kt | hoc081098 | 736,617,487 | false | {"Kotlin": 195727, "Shell": 377} | package com.hoc081098.solivagant.navigation
import com.hoc081098.solivagant.lifecycle.LifecycleOwner
import com.hoc081098.solivagant.navigation.internal.AppLifecycleOwnerImpl
@Suppress("FunctionName") // Factory function
public fun AppLifecycleOwner(): LifecycleOwner = AppLifecycleOwnerImpl()
| 6 | Kotlin | 3 | 5 | 9977b0e2365ef1dc484aa6069b73cf9c4f78e5ae | 296 | solivagant | Apache License 2.0 |
app/src/main/java/com/example/android/architecture/blueprints/todoapp/domain/GetTaskUseCase.kt | valitimisicaviacbs | 416,342,098 | false | null | package com.example.android.architecture.blueprints.todoapp.domain
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import com.example.android.architecture.blueprints.todoapp.util.wrapEspressoIdlingResource
import javax.inject.Inject
class GetTaskUseCase @Inject constructor(
private val tasksRepository: TasksRepository
) {
suspend operator fun invoke(taskId: String, forceUpdate: Boolean = false): Result<Task> {
wrapEspressoIdlingResource {
return tasksRepository.getTask(taskId, forceUpdate)
}
}
} | 0 | Kotlin | 1 | 0 | d079161dab68e146fcd0637938939df39229e194 | 723 | architecture-samples-usecases-hilt-migration | Apache License 2.0 |
composeApp/src/commonMain/kotlin/App.kt | 4mr0m3r0 | 729,256,548 | false | {"Kotlin": 5483, "Swift": 594} | import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import dev.icerock.moko.mvvm.compose.getViewModel
import dev.icerock.moko.mvvm.compose.viewModelFactory
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.imageResource
import org.jetbrains.compose.ui.tooling.preview.Preview
@OptIn(ExperimentalResourceApi::class)
@Composable
@Preview
fun App() {
MaterialTheme {
val viewModel = getViewModel(Unit, viewModelFactory { NasaViewModel() })
val uiState by viewModel.uiState.collectAsState()
LaunchedEffect(viewModel) {
viewModel.updateImages()
}
NasaImageContent(uiState)
}
}
@Composable
private fun NasaImageContent(uiState: NasaImageUiState) {
LazyVerticalGrid(
columns = GridCells.Adaptive(180.dp),
horizontalArrangement = Arrangement.spacedBy(5.dp),
verticalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.fillMaxSize().padding(horizontal = 5.dp)
) {
items(uiState.images) { image ->
NasaImageCell(item = image)
}
}
}
@Composable
private fun NasaImageCell(item: Item) {
KamelImage(
resource = asyncPainterResource(item.links.first().href),
contentDescription = item.data.first().title,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().aspectRatio(1.0f)
)
} | 0 | Kotlin | 0 | 0 | b30f5b616c021e41f3cff410779524cdee0aef95 | 1,890 | our-planet-multiplatform | MIT License |
render/jpql/src/test/kotlin/com/linecorp/kotlinjdsl/render/jpql/serializer/impl/JpqlExpressionSerializerTest.kt | line | 442,633,985 | false | {"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023} | package com.linecorp.kotlinjdsl.render.jpql.serializer.impl
import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expressions
import com.linecorp.kotlinjdsl.querymodel.jpql.expression.impl.JpqlExpression
import com.linecorp.kotlinjdsl.render.TestRenderContext
import com.linecorp.kotlinjdsl.render.jpql.serializer.JpqlSerializerTest
import com.linecorp.kotlinjdsl.render.jpql.writer.JpqlWriter
import io.mockk.impl.annotations.MockK
import io.mockk.verifySequence
import org.assertj.core.api.WithAssertions
import org.junit.jupiter.api.Test
@JpqlSerializerTest
class JpqlExpressionSerializerTest : WithAssertions {
val sut = JpqlExpressionSerializer()
@MockK
private lateinit var writer: JpqlWriter
private val alias1 = "alias1"
@Test
fun handledType() {
// when
val actual = sut.handledType()
// then
assertThat(actual).isEqualTo(JpqlExpression::class)
}
@Test
fun serialize() {
// given
val part = Expressions.expression(
String::class,
alias1,
)
val context = TestRenderContext()
// when
sut.serialize(part as JpqlExpression<*>, writer, context)
// then
verifySequence {
writer.write(alias1)
}
}
}
| 4 | Kotlin | 86 | 705 | 3a58ff84b1c91bbefd428634f74a94a18c9b76fd | 1,294 | kotlin-jdsl | Apache License 2.0 |
greek-clash-td/src/main/kotlin/asher/greek/components/GameState.kt | triathematician | 565,184,861 | false | {"Kotlin": 74763} | /*-
* #%L
* greek-clash-td
* --
* Copyright (C) 2020 - 2022 <NAME> and <NAME>
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package asher.greek.components
import asher.greek.assets.Assets
import tornadofx.booleanBinding
import tornadofx.getProperty
import tornadofx.property
import tornadofx.stringBinding
/** Manages the state of the overall game, including current level, player assets, etc. */
class GameState {
val levels = Assets.levelConfig.createLevels()
var playerFunds by property(0)
var playerLives by property(0)
var levelIndex by property(0)
private var waveIndex by property(0)
var isWaveStarted by property(false)
var isWavePaused by property(false)
var isWaveOver by property(false)
var isPassedWave by property(false)
var isTestMode by property(false)
val playerInfo
get() = PlayerInfo(playerFunds, playerLives)
val curLevel
get() = levels[levelIndex]
val curWave
get() = curLevel.waves[waveIndex]
//region PROPERTIES
val _playerFunds = getProperty(GameState::playerFunds)
val _playerLives = getProperty(GameState::playerLives)
val _levelIndex = getProperty(GameState::levelIndex)
val _waveIndex = getProperty(GameState::waveIndex)
val _waveStarted = getProperty(GameState::isWaveStarted)
val _wavePaused = getProperty(GameState::isWavePaused)
val _waveOver = getProperty(GameState::isWaveOver)
private val _passedWave = getProperty(GameState::isPassedWave)
val _testMode = getProperty(GameState::isTestMode)
//endregion
//region DERIVED PROPERTIES
val levelActive = _waveStarted.booleanBinding(_wavePaused, _waveOver) {
it!! && !isWavePaused && !isWaveOver
}
val hasPreviousLevel = booleanBinding(_levelIndex) { get() > 0 }
val hasNextLevel = booleanBinding(_levelIndex) { get() < levels.size - 1 }
val hasPreviousWave = booleanBinding(_waveIndex) { get() > 0 }
val hasNextWave = booleanBinding(_waveIndex, _levelIndex) { get() < curLevel.waves.size - 1 }
val canProceedToPreviousWave = hasPreviousWave.booleanBinding(_testMode) {
it!! && isTestMode
}
val canProceedToNextWave = hasNextWave.booleanBinding(_passedWave, _testMode) {
it!! && (isTestMode || isPassedWave)
}
val canProceedToPreviousLevel = hasPreviousLevel.booleanBinding(_testMode) {
it!! && isTestMode
}
val canProceedToNextLevel = hasNextLevel.booleanBinding(_passedWave, hasNextWave, _testMode) {
it!! && (isTestMode || (isPassedWave && !hasNextWave.get()))
}
//endregion
init {
initLevel()
}
//region WAVE/LEVEL CHANGE
fun previousWave() {
require(hasPreviousWave.get())
waveIndex--
}
fun nextWave() {
require(hasNextWave.get())
waveIndex++
}
fun previousLevel() {
require(hasPreviousLevel.get())
waveIndex = 0
levelIndex--
initLevel()
}
fun nextLevel() {
require(hasNextLevel.get())
waveIndex = 0
levelIndex++
initLevel()
}
internal fun initLevel() {
waveIndex = 0
playerFunds = curLevel.startingFunds
playerLives = curLevel.startingLives
}
//endregion
}
| 0 | Kotlin | 0 | 0 | 12679e580a424aabdb1d9e498d4013bc624a9944 | 3,809 | experimental-games | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.