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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
features/main-screen/src/main/kotlin/hellokevin/features/mainscreen/bottombar/MainScreenBottomBar.kt
|
kevineder
| 679,907,954 | false | null |
package hellokevin.features.mainscreen.bottombar
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
@Composable
fun MainScreenBottomBar(
navController: NavController
) {
NavigationBar {
val currentRoute = currentRoute(navController)
val items = mutableListOf(
MainScreenBottomBarItem.Home,
MainScreenBottomBarItem.Create,
MainScreenBottomBarItem.Video
)
items.forEach { item ->
NavigationBarItem(
icon = {
Icon(
painterResource(item.icon),
contentDescription = stringResource(id = item.name)
)
},
label = { Text(stringResource(id = item.name)) },
selected = currentRoute == item.route.value,
onClick = {
// This if check gives us a "singleTop" behavior where we do not create a
// second instance of the composable if we are already on that destination
if (currentRoute != item.route.value) {
navController.navigate(item.route.value)
}
}
)
}
}
}
@Composable
private fun currentRoute(navController: NavController): String? {
val navBackStackEntry by navController.currentBackStackEntryAsState()
return navBackStackEntry?.destination?.route
}
@Preview
@Composable
fun PreviewMainScreenBottomBar() {
MainScreenBottomBar(navController = rememberNavController())
}
| 0 |
Kotlin
|
0
| 0 |
89d042ccd47bc3a1509eb06f9abd9c90b799158d
| 2,093 |
parrot
|
MIT License
|
android/app/src/main/java/com/dionchang/podcasttolearn/ui/vocabulary/DailayWordScreen.kt
|
babogoos
| 669,373,864 | false | null |
package com.dionchang.podcasttolearn.ui.vocabulary
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.dionchang.podcasttolearn.R
import com.dionchang.podcasttolearn.domain.model.Word
import com.dionchang.podcasttolearn.ui.common.PreviewContent
import com.dionchang.podcasttolearn.ui.home.ErrorView
import com.dionchang.podcasttolearn.ui.home.ProgressLoadingPlaceholder
import com.dionchang.podcasttolearn.ui.viewmodel.DailyWordViewModel
import com.dionchang.podcasttolearn.util.Resource
/**
* Created by dion on 2023/04/15.
*/
@Composable
fun DailyWordScreen() {
val scrollState = rememberLazyListState()
val dailyWordViewModel = hiltViewModel<DailyWordViewModel>()
DailyWordScreenContent(scrollState, dailyWordViewModel.dailyWord) {
dailyWordViewModel.getDailyWord(dailyWordViewModel.audioId, dailyWordViewModel.article)
}
}
@Composable
private fun DailyWordScreenContent(
scrollState: LazyListState = rememberLazyListState(),
wordList: Resource<List<Word>> = Resource.Success(
listOf(
Word("apple", "蘋果", "this is an apple","這是蘋果"),
Word("banana", "香蕉", "this is a banana","這是香蕉"),
Word("orange", "橘子", "this is an orange","這是橘子"),
)
),
retry: () -> Unit = {}
) {
Surface {
LazyColumn(
state = scrollState,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.padding(top = 24.dp, bottom = dimensionResource(id = R.dimen.podcast_bottom_bar_height), start = 16.dp, end = 16.dp)
.fillMaxSize()
) {
when (wordList) {
is Resource.Loading -> {
item {
ProgressLoadingPlaceholder()
}
}
is Resource.Error -> {
item {
ErrorView(text = wordList.failure.translate()) {
retry.invoke()
}
}
}
is Resource.Success -> {
itemsIndexed(wordList.data) { index, dailyWord ->
Column(
modifier = Modifier
.padding(vertical = 4.dp)
.fillMaxSize()
) {
Text(text = "Daily Word ${index + 1}")
DailyWordView(dailyWord)
}
}
}
}
}
}
}
@Preview(name = "DailyWordScreen (Light)")
@Composable
fun DailyWordScreenPreview() {
PreviewContent() {
DailyWordScreenContent()
}
}
@Preview(name = "DailyWordScreen (Dark)")
@Composable
fun DailyWordScreenDarkPreview() {
PreviewContent(darkTheme = true) {
DailyWordScreenContent()
}
}
@Composable
fun DailyWordView(word: Word) {
Column(
modifier = Modifier
.fillMaxSize()
) {
Text(text = "單字:" + word.word + " (" + word.translate + ")")
Text(text = "例句:" + word.example + " (" + word.exampleTranslate + ")")
}
}
| 0 |
Kotlin
|
0
| 1 |
87354855c3a4c6ca1b98b5d2c182e59ca31f6543
| 4,007 |
PodcastToLearn
|
MIT License
|
app/src/main/java/com/example/azp/utilities/CalendarViewHolder.kt
|
Echo-terminal
| 766,566,687 | false |
{"Kotlin": 102389}
|
package com.example.azp.utilities
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.azp.R
class CalendarViewHolder(
itemView: View,
private val onItemListener: OnItemListener
) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val dayOfMonth: TextView = itemView.findViewById(R.id.cellDayText)
init {
itemView.setOnClickListener(this)
}
override fun onClick(view: View) {
// Проверяем, что дата не пустая
if (dayOfMonth.text.isNotEmpty()) {
// Вызываем метод onItemClick() из OnItemListener
onItemListener.onItemClick(adapterPosition, dayOfMonth.text.toString())
}
}
}
| 0 |
Kotlin
|
0
| 0 |
6911bbdd6c8a943c062e1c4881c8d9f2dae0bd6d
| 743 |
AZP
|
Apache License 2.0
|
app/src/main/java/com/twoics/geo/map/IMap.kt
|
DiabloZX
| 646,790,672 | false | null |
package com.twoics.geo.map
import androidx.compose.runtime.Composable
import com.twoics.geo.data.models.BookMark
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
interface IMap {
val centerMapLocation: GeoPoint
val areaRadius: Double
fun clearPlaces()
fun changeBookmarkActiveState()
fun updateBookMarks(bookMarks: List<BookMark>)
@Composable
fun redrawMap(): MapView
}
| 0 |
Kotlin
|
0
| 0 |
4c09313a547ca1fe505e103b1bb9ab37a6d54b92
| 420 |
RMP
|
MIT License
|
1717.Maximum Score From Removing Substrings.kt
|
sarvex
| 842,260,390 | false |
{"Kotlin": 1775678, "PowerShell": 418}
|
internal class Solution {
fun maximumGain(s: String, x: Int, y: Int): Int {
var x = x
var y = y
var a = 'a'
var b = 'b'
if (x < y) {
val t = x
x = y
y = t
val c = a
a = b
b = c
}
var ans = 0
var cnt1 = 0
var cnt2 = 0
val n = s.length
for (i in 0 until n) {
val c = s[i]
if (c == a) {
cnt1++
} else if (c == b) {
if (cnt1 > 0) {
ans += x
cnt1--
} else {
cnt2++
}
} else {
ans += min(cnt1, cnt2) * y
cnt1 = 0
cnt2 = 0
}
}
ans += min(cnt1, cnt2) * y
return ans
}
}
| 0 |
Kotlin
|
0
| 0 |
17a80985d970c8316fb694e4952692e598d700af
| 674 |
kotlin-leetcode
|
MIT License
|
katana-server/src/main/kotlin/jp/katana/server/network/packet/mcpe/UpdateAttributesPacket.kt
|
hiroki19990625
| 194,672,872 | false | null |
package jp.katana.server.network.packet.mcpe
import jp.katana.core.IServer
import jp.katana.core.actor.IActorPlayer
import jp.katana.core.actor.attribute.IActorAttributes
import jp.katana.debug.appendIndent
import jp.katana.debug.appendProperty
import jp.katana.server.actor.attribute.ActorAttribute
class UpdateAttributesPacket : MinecraftPacket() {
override val packetId: Int = MinecraftProtocols.UPDATE_ATTRIBUTES_PACKET
var actorId: Long = 0
var attributes: IActorAttributes? = null
override fun decodePayload() {
actorId = readActorRuntimeId()
val c = readUnsignedVarInt()
for (i in 1..c) {
val min = readFloatLE()
val max = readFloatLE()
val value = readFloatLE()
val defaultValue = readFloatLE()
val name = readVarString()
attributes!!.setAttribute(ActorAttribute(name, max, min, value, defaultValue))
}
}
override fun encodePayload() {
writeActorRuntimeId(actorId)
val list = attributes!!.getAttributes()
writeUnsignedVarInt(list.size)
for (attribute in list) {
writeFloatLE(attribute.minValue)
writeFloatLE(attribute.maxValue)
writeFloatLE(attribute.value)
writeFloatLE(attribute.defaultValue)
writeVarString(attribute.name)
}
}
override fun handleServer(player: IActorPlayer, server: IServer) {
// No cause
}
override fun toString(): String {
return toPrintString()
}
override fun print(builder: StringBuilder, indent: Int) {
builder.appendIndent("${this.javaClass.simpleName} : 0x${packetId.toString(16)} {\n", indent)
builder.appendProperty(UpdateAttributesPacket::actorId, this, indent + 1)
builder.appendProperty(UpdateAttributesPacket::attributes, this, indent + 1)
builder.appendIndent("}\n", indent)
}
}
| 0 |
Kotlin
|
1
| 2 |
aab8ae69beed267ea0ef9eab2ebd23b994ac0f25
| 1,935 |
katana
|
MIT License
|
opendc-model-odc/core/src/main/kotlin/com/atlarge/opendc/model/odc/platform/scheduler/stages/machine/Selection.kt
|
atlarge-research
| 79,902,611 | false | null |
/*
* MIT License
*
* Copyright (c) 2018 atlarge-research
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.atlarge.opendc.model.odc.platform.scheduler.stages.machine
import com.atlarge.opendc.model.odc.OdcModel
import com.atlarge.opendc.model.odc.platform.scheduler.StageScheduler
import com.atlarge.opendc.model.odc.platform.workload.Task
import com.atlarge.opendc.model.odc.topology.machine.Cpu
import com.atlarge.opendc.model.odc.topology.machine.Machine
import com.atlarge.opendc.model.topology.destinations
import com.atlarge.opendc.simulator.context
import java.util.NavigableMap
import java.util.Random
import java.util.TreeMap
import javax.crypto.Mac
import kotlin.math.abs
/**
* This interface represents the **R5** stage of the Reference Architecture for Schedulers and matches the the selected
* task with a (set of) resource(s), using policies such as First-Fit, Worst-Fit, and Best-Fit.
*/
interface MachineSelectionPolicy {
/**
* Select a machine on which the task should be scheduled.
*
* @param machines The list of machines in the system.
* @param task The task that is to be scheduled.
* @return The selected machine or `null` if no machine could be found.
*/
suspend fun select(machines: List<Machine>, task: Task): Machine?
}
/**
* A [MachineSelectionPolicy] that selects the first machine that is available.
*/
class FirstFitMachineSelectionPolicy : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? = machines.firstOrNull()
}
/**
* A [MachineSelectionPolicy] that selects the machine using a Best-Fit allocation algorithm: select the machine with
* the smallest amount of available cores such that the given task can be scheduled on it.
*/
class BestFitMachineSelectionPolicy : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
machines
.sortedBy { abs(task.cores - (state.machineCores[it] ?: 0)) }
.firstOrNull()
}
}
/**
* A [MachineSelectionPolicy] that selects the machine using a Worst-Fit allocation algorithm: select the machine with
* the largest amount of available cores such that the given task can be scheduled on it.
*/
class WorstFitMachineSelectionPolicy : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
machines
.sortedByDescending { abs(task.cores - (state.machineCores[it] ?: 0)) }
.firstOrNull()
}
}
/**
* A [MachineSelectionPolicy] that selects the machine randomly.
*
* @property random The [Random] instance used to pick the machine.
*/
class RandomMachineSelectionPolicy(private val random: Random = Random()) : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
if (machines.isNotEmpty())
machines[random.nextInt(machines.size)]
else
null
}
/**
* Heterogeneous Earliest Finish Time (HEFT) scheduling.
*
* https://en.wikipedia.org/wiki/Heterogeneous_Earliest_Finish_Time
*/
class HeftMachineSelectionPolicy : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
model.run {
// NOTE: higher is better.
fun communication(task: Task, machine: Machine): Double {
return machine.ethernetSpeed / task.inputSize
}
fun availableCompute(machine: Machine): Double {
val cpus = machine.outgoingEdges.destinations<Cpu>("cpu")
val cores = cpus.map { it.cores }.sum()
val speed = cpus.fold(0) { acc, cpu -> acc + cpu.clockRate * cpu.cores } / cores
return (1.0 - machine.state.load) * speed
}
machines.maxBy { machine -> communication(task, machine) + availableCompute(machine) }
}
}
}
/**
* Critical-Path-on-a-Processor (CPOP) scheduling as described by H. Topcuoglu et al. in
* "Task Scheduling Algorithms for Heterogeneous Processors".
*/
class CpopMachineSelectionPolicy : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
model.run {
// NOTE: higher is better.
fun communication(task: Task, machine: Machine): Double {
return machine.ethernetSpeed.toDouble() / task.inputSize
}
fun availableCompute(machine: Machine): Double {
val cpus = machine.outgoingEdges.destinations<Cpu>("cpu")
val cores = cpus.map { it.cores }.sum()
val speed = cpus.fold(0) { acc, cpu -> acc + cpu.clockRate * cpu.cores } / cores
return (1.0 - machine.state.load) * speed
}
machines.maxBy { machine -> communication(task, machine) + availableCompute(machine) }
}
}
}
/**
* Round robin (RR) scheduling.
*
* https://en.wikipedia.org/wiki/Round-robin_scheduling
*/
class RrMachineSelectionPolicy(private var current: Int = 0) : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
model.run {
if (machines.isEmpty()) {
return null
}
val ids: NavigableMap<Int, Machine> = TreeMap(machines.associateBy { it.id })
current = ids.higherKey(current) ?: ids.firstKey()
return ids[current]
}
}
}
/**
* Delay Scheduling (DS) algorithm.
* https://cs.stanford.edu/~matei/papers/2010/eurosys_delay_scheduling.pdf
*
*/
class DSMachineSelectionPolicy(private var current: Int = 0) : MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
model.run {
if (machines.isEmpty()) {
return null
} else {
if (state.machinesPerJob.get(task.owner_id) == null) {
return machines.firstOrNull()
} else {
// Try to schedule a task on a machine where its dependencies are also executed
val setMachines = state.machinesPerJob.get(task.owner_id)!!
for (prevMachine in setMachines) {
if (prevMachine in machines) {
return prevMachine
}
}
}
return machines.firstOrNull()
}
}
}
}
/**
* Lottery Scheduling
*
* https://en.wikipedia.org/wiki/Lottery_scheduling
*/
class LotteryMachineSelectionPolicy(private var defaultTickets: Int = 100,
private var distributionMap: Map<Machine, Int> = mutableMapOf(),
private val random: Random = Random()) : MachineSelectionPolicy {
/**
* A map where the key number maps to the machine
* that owns the range of tickets that
* start at that number and end at the next
* index
*/
val ticketMap: MutableMap<Int, Machine> = mutableMapOf()
val knownMachines: MutableSet<Machine> = mutableSetOf()
var totalTickets = 0
fun pushMachine(machine: Machine, tickets: Int = defaultTickets) {
ticketMap.set(totalTickets, machine)
totalTickets += tickets
knownMachines.add(machine)
}
init {
// Fill the map based on the already known values
for ((machine, tickets) in distributionMap) {
pushMachine(machine, tickets)
}
}
fun ensureMachineChances(machines: List<Machine>) {
for (machine in machines) {
if (!knownMachines.contains(machine)) {
// Not known yet, add it to this list
// and assign it a ticket range
pushMachine(machine)
}
}
}
fun findWinner(number: Int, startRange: Int = 0, endRange: Int = ticketMap.size): Machine? {
// Get half of the passed range
val halfRange: Int = startRange + ((endRange - startRange) / 2)
// Get the start value there
val startValue = ticketMap.keys.elementAt(halfRange)
if (startValue > number) {
// Search to the left of this
return findWinner(number, startRange, halfRange)
} else if (startValue == number || halfRange == ticketMap.size - 1 || number < ticketMap.keys.elementAt(halfRange + 1)) {
// We found it
return ticketMap.get(startValue)
} else {
// Search to the right of this
return findWinner(number, halfRange, endRange)
}
}
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
model.run {
if (machines.isEmpty()) {
return null
}
// Make sure all machines are actually in the ticket map
ensureMachineChances(machines)
var winner: Machine?;
do {
// Draw a ticket
val ticket: Int = random.nextInt(totalTickets)
// Find the winner
winner = findWinner(ticket)
// Check if the winner is present
} while (winner == null || !(winner in machines))
return winner
}
}
}
/** Fast Critical Path (FCP) Scheduling machine selection
*
* FCP considers two machines candidates, one which has sent the last message (last message received), and
* the other which has became idle earliest. The procedure then selects the one with the earliest start time.
*/
class FCPMachineSelectionPolicy: MachineSelectionPolicy {
override suspend fun select(machines: List<Machine>, task: Task): Machine? =
context<StageScheduler.State, OdcModel>().run {
model.run {
if (machines.isEmpty()) {
return null
}
// Sort by the time they are done with tasks
// Times are managed by the scheduler, so no
// inconsistencies
val earliest = machines.sortedBy { it.state.endTime }[0]
val last = machines.sortedBy { it.state.startTime }[0]
if (earliest.state.endTime < last.state.startTime) {
return earliest
}
return last
}
}
}
| 2 |
Kotlin
|
6
| 9 |
f399e3d598d156926d0a74aa512f777ff0d9ad10
| 12,205 |
opendc-simulator
|
MIT License
|
src/test/kotlin/dsl/wiremock/request/body/XPathBodyPatternTest.kt
|
valentin-goncharov
| 447,352,842 | false |
{"Kotlin": 208558}
|
package dsl.wiremock.request.body
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.matching.MatchesXPathPattern
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.util.function.Consumer
internal class XPathBodyPatternTest {
private val body = RequestBodyScope()
@Test
fun `matchingXPath should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val pattern = body xmlPath xPath
assertThat(pattern.matchingXPath(xPath)).isSameAs(pattern)
assertThat(pattern.getPattern())
.isInstanceOf(MatchesXPathPattern::class.java)
.satisfies( Consumer {
val jsonPathPattern = it as MatchesXPathPattern
assertThat(jsonPathPattern.matchesXPath).isEqualTo(xPath)
})
val vmPattern = WireMock.matchingXPath(xPath)
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `namespace should create pattern equals to WireMock pattern`() {
val xPath = "//test:key/more:inner/text()"
val pattern = body xmlPath
xPath namespace "test = http://test.example.com" namespace "more = http://more.example.com"
val vmPattern = WireMock.matchingXPath(xPath)
.withXPathNamespace("test", "http://test.example.com")
.withXPathNamespace("more", "http://more.example.com")
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `equalToJson should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val jsonBody = """{"key":"value"}"""
val pattern = body xmlPath xPath equalToJson jsonBody
val vmPattern = WireMock.matchingXPath(xPath, WireMock.equalToJson(jsonBody))
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `equalToXml should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val xmlBody = """<xml>value</xml>"""
val pattern = body xmlPath xPath equalToXml xmlBody
val vmPattern = WireMock.matchingXPath(xPath, WireMock.equalToXml(xmlBody))
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `equalTo should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val string = "string"
val pattern = body xmlPath xPath equalTo string
val vmPattern = WireMock.matchingXPath(xPath, WireMock.equalTo(string))
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `contains should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val string = "string"
val pattern = body xmlPath xPath contains string
val vmPattern = WireMock.matchingXPath(xPath, WireMock.containing(string))
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `matches should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val regex = ".*aaa.*"
val pattern = body xmlPath xPath matches regex
val vmPattern = WireMock.matchingXPath(xPath, WireMock.matching(regex))
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
@Test
fun `doesNotMatch should create pattern equals to WireMock pattern`() {
val xPath = "//key/text()"
val regex = ".*aaa.*"
val pattern = body xmlPath xPath doesNotMatch regex
val vmPattern = WireMock.matchingXPath(xPath, WireMock.notMatching(regex))
assertThat(pattern.getPattern()).isEqualTo(vmPattern)
}
}
| 2 |
Kotlin
|
0
| 0 |
ad0aac9ce014a6f53c51c0e1aedb846414358b8d
| 3,747 |
wiremock-kotlin-dsl
|
Apache License 2.0
|
app/src/main/java/cn/cqautotest/sunnybeach/viewmodel/fishpond/FishPondViewModel.kt
|
anjiemo
| 378,095,612 | false | null |
package cn.cqautotest.sunnybeach.viewmodel.fishpond
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import cn.cqautotest.sunnybeach.http.network.Repository
import cn.cqautotest.sunnybeach.model.Fish
import cn.cqautotest.sunnybeach.model.FishPondComment
import cn.cqautotest.sunnybeach.paging.source.FishDetailCommendListPagingSource
import cn.cqautotest.sunnybeach.paging.source.FishDetailPagingSource
import cn.cqautotest.sunnybeach.paging.source.FishPagingSource
import cn.cqautotest.sunnybeach.paging.source.UserFishPagingSource
import kotlinx.coroutines.flow.Flow
/**
* author : A Lonely Cat
* github : https://github.com/anjiemo/SunnyBeach
* time : 2021/07/10
* desc : 摸鱼列表的 ViewModel
*/
class FishPondViewModel : ViewModel() {
private val _fishListStateLiveData = MutableLiveData(Unit)
val fishListStateLiveData = _fishListStateLiveData.switchMap { MutableLiveData(it) }
fun refreshFishList() {
_fishListStateLiveData.value = Unit
}
fun unfollowFishTopic(topicId: String) = Repository.unfollowFishTopic(topicId)
fun followFishTopic(topicId: String) = Repository.followFishTopic(topicId)
fun loadTopicList() = Repository.loadTopicList()
fun dynamicLikes(momentId: String) = Repository.dynamicLikes(momentId)
fun postComment(momentComment: Map<String, Any?>, isReply: Boolean) =
Repository.postComment(momentComment, isReply)
fun getFishCommendListById(momentId: String): Flow<PagingData<FishPondComment.FishPondCommentItem>> {
return Pager(
config = PagingConfig(30),
pagingSourceFactory = {
FishDetailCommendListPagingSource(momentId)
}).flow.cachedIn(viewModelScope)
}
fun putFish(moment: Map<String, Any?>) = Repository.putFish(moment)
fun getFishDetailById(momentId: String): Flow<PagingData<Fish.FishItem>> {
return Pager(
config = PagingConfig(30),
pagingSourceFactory = {
FishDetailPagingSource(momentId)
}).flow.cachedIn(viewModelScope)
}
fun getFishListByCategoryId(topicId: String): Flow<PagingData<Fish.FishItem>> {
return Pager(config = PagingConfig(30),
pagingSourceFactory = {
FishPagingSource(topicId)
}).flow.cachedIn(viewModelScope)
}
fun getUserFishList(userId: String): Flow<PagingData<Fish.FishItem>> {
return Pager(
config = PagingConfig(30),
pagingSourceFactory = {
UserFishPagingSource(userId)
}).flow.cachedIn(viewModelScope)
}
}
| 0 |
Kotlin
|
18
| 95 |
a2402da1cb6af963c829a69d9783053f15d866b5
| 2,835 |
SunnyBeach
|
Apache License 2.0
|
lib_utils/src/main/java/com/ndhzs/lib/utils/adapter/FragmentVpAdapter.kt
|
VegetableChicken-Group
| 497,243,579 | false |
{"Kotlin": 315359, "Shell": 8775}
|
package com.ndhzs.lib.utils.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
/**
* ...
* @author 985892345 (<NAME>)
* @email <EMAIL>
* @date 2022/7/25 18:22
*/
class FragmentVpAdapter private constructor(
fragmentManager: FragmentManager,
lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {
constructor(activity: FragmentActivity) : this(activity.supportFragmentManager, activity.lifecycle)
constructor(fragment: Fragment) : this(fragment.childFragmentManager, fragment.lifecycle)
private val mFragments = arrayListOf<() -> Fragment>()
fun add(fragment: () -> Fragment): FragmentVpAdapter {
mFragments.add(fragment)
return this
}
fun add(fragment: Class<out Fragment>): FragmentVpAdapter {
// 官方源码中在恢复 Fragment 时就是调用的这个反射方法,该方法应该不是很耗性能 :)
mFragments.add { fragment.newInstance() }
return this
}
override fun getItemCount(): Int = mFragments.size
override fun createFragment(position: Int): Fragment = mFragments[position].invoke()
}
| 0 |
Kotlin
|
14
| 30 |
3455309ef00ecbe61dbc2c80b8871f8981b412e2
| 1,203 |
WanAndroid_Multi
|
MIT License
|
app/src/main/java/br/com/lucasfe/droidauth/model/User.kt
|
lucasfe
| 126,185,214 | false | null |
package br.com.lucasfe.droidauth.model
import br.com.lucasfe.droidauth.webapi.RetrofitInit
import java.util.Observable;
class User : Observable() {
var name: String = ""
set (value) {
field = value
setChangedAndNotify("name")
}
var email: String = ""
set(value) {
field = value
setChangedAndNotify("email")
}
var password: String = ""
set(value) {
field = value
setChangedAndNotify("password")
}
private fun setChangedAndNotify(field: Any) {
setChanged()
notifyObservers(field)
}
}
| 0 |
Kotlin
|
0
| 0 |
748659a287cedecfb20bec1e648e10e4f61cb782
| 647 |
droid_auth
|
Apache License 2.0
|
StudyPlanet/src/main/java/com/qwict/studyplanetandroid/common/EncryptedPreferencesService.kt
|
Qwict
| 698,396,315 | false |
{"Kotlin": 199488}
|
package com.qwict.studyplanetandroid.common
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import com.qwict.studyplanetandroid.StudyPlanetApplication
// TODO: this is deprecated? What should we replace it with...
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
// TODO: also declare sharedPreference variable here to make code more elegant?
/**
* Retrieves an encrypted preference value associated with the given [key].
*
* This function fetches an encrypted preference value stored in the SharedPreferences.
* It uses the [getSharedPreferences] function to access the SharedPreferences instance.
* If the preference value for the specified [key] is not found, an empty string is returned.
*
* @param key The key associated with the preference value to retrieve.
*
* @return The encrypted preference value for the given [key] or an empty string if not found.
*/
fun getEncryptedPreference(key: String): String {
return getSharedPreferences().getString(key, "") ?: ""
}
/**
* Saves an encrypted preference value for the given [key].
*
* This function stores the provided [preference] as an encrypted value in the SharedPreferences
* using the specified [key]. It uses the [getSharedPreferences] function to access the SharedPreferences instance.
*
* @param key The key under which the preference value will be stored.
* @param preference The encrypted preference value to be saved.
*/
fun saveEncryptedPreference(key: String, preference: String) {
getSharedPreferences().edit().putString(key, preference).apply()
}
/**
* Removes the encrypted preference value associated with the given [key].
*
* This function removes the encrypted preference value stored in the SharedPreferences
* for the specified [key]. It uses the [getSharedPreferences] function to access the SharedPreferences instance.
*
* @param key The key associated with the preference value to be removed.
*/
fun removeEncryptedPreference(key: String) {
val sharedPreferences = getSharedPreferences()
sharedPreferences.edit().remove(key).apply()
}
/**
* Retrieves the encrypted SharedPreferences instance used for storing sensitive data.
*
* This function creates and returns an instance of [EncryptedSharedPreferences] with the specified configurations.
* It uses the provided master key alias, application context from [StudyPlanetApplication], and encryption schemes
* for both preference keys and values.
*
* @return An [EncryptedSharedPreferences] instance for securely storing sensitive data.
*/
private fun getSharedPreferences(): SharedPreferences {
return EncryptedSharedPreferences.create(
"preferences",
masterKeyAlias,
StudyPlanetApplication.appContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
)
}
| 0 |
Kotlin
|
0
| 0 |
9cb5ba383a6e1b30e261cd379739583cc3219c8a
| 2,984 |
StudyPlanetAndroid
|
MIT License
|
app/src/main/java/com/kylecorry/trail_sense/tools/maps/ui/WarpMapFragment.kt
|
kylecorry31
| 215,154,276 | false | null |
package com.kylecorry.trail_sense.tools.maps.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isInvisible
import com.kylecorry.andromeda.alerts.Alerts
import com.kylecorry.andromeda.fragments.BoundFragment
import com.kylecorry.trail_sense.R
import com.kylecorry.trail_sense.databinding.FragmentMapsPerspectiveBinding
import com.kylecorry.trail_sense.shared.extensions.inBackground
import com.kylecorry.trail_sense.shared.extensions.onIO
import com.kylecorry.trail_sense.shared.extensions.onMain
import com.kylecorry.trail_sense.shared.io.FileSubsystem
import com.kylecorry.trail_sense.tools.maps.domain.Map
import com.kylecorry.trail_sense.tools.maps.infrastructure.MapRepo
import com.kylecorry.trail_sense.tools.maps.infrastructure.fixPerspective
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
class WarpMapFragment : BoundFragment<FragmentMapsPerspectiveBinding>() {
private val mapRepo by lazy { MapRepo.getInstance(requireContext()) }
private val files by lazy { FileSubsystem.getInstance(requireContext()) }
private var mapId = 0L
private var map: Map? = null
private var onDone: () -> Unit = {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mapId = requireArguments().getLong("mapId")
}
override fun generateBinding(
layoutInflater: LayoutInflater,
container: ViewGroup?
): FragmentMapsPerspectiveBinding {
return FragmentMapsPerspectiveBinding.inflate(layoutInflater, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.perspectiveToggleBtn.setOnClickListener {
binding.perspective.isPreview = !binding.perspective.isPreview
if (binding.perspective.isPreview) {
binding.perspectiveToggleBtn.text = getString(R.string.edit)
} else {
binding.perspectiveToggleBtn.text = getString(R.string.preview)
}
}
binding.nextButton.setOnClickListener {
inBackground {
next()
}
}
binding.nextButton.isInvisible = true
inBackground {
withContext(Dispatchers.IO) {
map = mapRepo.getMap(mapId)
}
withContext(Dispatchers.Main) {
map?.let {
onMapLoad(it)
}
}
}
}
private fun onMapLoad(map: Map) {
this.map = map
binding.perspective.mapRotation = map.calibration.rotation.toFloat()
binding.perspective.setImage(map.filename)
binding.nextButton.isInvisible = false
}
fun setOnCompleteListener(listener: () -> Unit) {
onDone = listener
}
private suspend fun next() {
val map = map ?: return
val percentBounds = binding.perspective.getPercentBounds() ?: return
val loading = onMain {
Alerts.loading(requireContext(), getString(R.string.saving))
}
onIO {
if (binding.perspective.hasChanges) {
val bitmap = files.bitmap(map.filename)
val bounds =
percentBounds.toPixelBounds(bitmap.width.toFloat(), bitmap.height.toFloat())
val warped = bitmap.fixPerspective(bounds)
bitmap.recycle()
try {
files.save(map.filename, warped, recycleOnSave = true)
} catch (e: IOException) {
onMain {
loading.dismiss()
}
return@onIO
}
}
mapRepo.addMap(map.copy(calibration = map.calibration.copy(warped = true)))
}
onMain {
loading.dismiss()
onDone.invoke()
}
}
}
| 336 |
Kotlin
|
39
| 525 |
f4bfb38d536a9ce5e1b60e001a9b9bdd5a4dd06a
| 4,051 |
Trail-Sense
|
MIT License
|
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/DataLine.kt
|
Konyaco
| 574,321,009 | false | null |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.DataLine: ImageVector
get() {
if (_dataLine != null) {
return _dataLine!!
}
_dataLine = fluentIcon(name = "Filled.DataLine") {
fluentPath {
moveTo(16.0f, 6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, 2.52f, 2.96f)
lineToRelative(-2.03f, 3.36f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, -4.75f, 3.65f)
lineTo(8.0f, 17.84f)
verticalLineTo(18.0f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, -0.47f, -1.6f)
lineToRelative(3.54f, -1.77f)
arcTo(3.01f, 3.01f, 0.0f, false, true, 14.0f, 11.0f)
curveToRelative(0.48f, 0.0f, 0.94f, 0.11f, 1.34f, 0.32f)
lineToRelative(1.8f, -2.97f)
arcTo(3.0f, 3.0f, 0.0f, false, true, 16.0f, 6.0f)
close()
}
}
return _dataLine!!
}
private var _dataLine: ImageVector? = null
| 1 |
Kotlin
|
3
| 83 |
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
| 1,245 |
compose-fluent-ui
|
Apache License 2.0
|
app/src/main/java/com/ahmadhamwi/tabsync_example/ui/MainActivity.kt
|
Ahmad-Hamwi
| 398,466,672 | false | null |
package com.ahmadhamwi.tabsync_example.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.ahmadhamwi.tabsync_example.R
import com.ahmadhamwi.tabsync_example.model.Category
import com.ahmadhamwi.tabsync_example.model.Item
import com.ahmadhamwi.tabsync.TabbedListMediator
import com.google.android.material.tabs.TabLayout
class MainActivity : AppCompatActivity() {
private lateinit var tabLayout: TabLayout
private lateinit var recyclerView: RecyclerView
private val categories = mutableListOf(
Category(
"Category 1",
Item("Item 1"),
Item("Item 2"),
Item("Item 3"),
Item("Item 4"),
Item("Item 5"),
Item("Item 6")
),
Category(
"Category 2",
Item("Item 1"),
Item("Item 2"),
Item("Item 3"),
Item("Item 4"),
),
Category(
"Category 3",
Item("Item 1"),
Item("Item 2"),
Item("Item 3"),
Item("Item 4"),
Item("Item 5"),
Item("Item 6"),
Item("Item 7"),
Item("Item 8"),
),
Category(
"Category 4",
Item("Item 1"),
Item("Item 2"),
Item("Item 3"),
Item("Item 4"),
Item("Item 5"),
Item("Item 6")
),
Category(
"Category 5",
Item("Item 1"),
Item("Item 2"),
Item("Item 4"),
Item("Item 5"),
),
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initViews()
initTabLayout()
initRecycler()
initMediator()
}
private fun initViews() {
tabLayout = findViewById(R.id.tabLayout)
recyclerView = findViewById(R.id.recyclerView)
}
private fun initTabLayout() {
for (category in categories) {
tabLayout.addTab(tabLayout.newTab().setText(category.name))
}
}
private fun initRecycler() {
recyclerView.adapter = CategoriesAdapter(this, categories)
}
private fun initMediator() {
TabbedListMediator(
recyclerView,
tabLayout,
categories.indices.toList()
).attach()
}
}
| 0 |
Kotlin
|
6
| 78 |
f9a75544576675422f8b8c6be4a7a8e922bbdd5a
| 2,489 |
TabSync
|
Apache License 2.0
|
app/src/main/java/com/shopapp/ui/custom/zoomable/ZoomableDraweeView.kt
|
rubygarage
| 105,554,295 | false | null |
package com.shopapp.ui.custom.zoomable
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.RectF
import android.graphics.drawable.Animatable
import android.support.v4.view.ScrollingView
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import com.facebook.common.internal.Preconditions
import com.facebook.drawee.controller.AbstractDraweeController
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchy
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.generic.GenericDraweeHierarchyInflater
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.drawee.view.DraweeView
class ZoomableDraweeView : DraweeView<GenericDraweeHierarchy>, ScrollingView {
companion object {
private const val HUGE_IMAGE_SCALE_FACTOR_THRESHOLD = 1.1f
}
private val mImageBounds = RectF()
private val mViewBounds = RectF()
private val mTapListenerWrapper = GestureListenerWrapper()
private var mHugeImageController: DraweeController? = null
private lateinit var mZoomableController: ZoomableController
private val mControllerListener = object : BaseControllerListener<Any>() {
override fun onFinalImageSet(
id: String?,
imageInfo: Any?,
animatable: Animatable?) {
[email protected]()
}
override fun onRelease(id: String?) {
[email protected]()
}
}
private val mZoomableListener = object : ZoomableController.Listener {
override fun onTransformChanged(transform: Matrix) {
[email protected]()
}
}
private lateinit var mTapGestureDetector: GestureDetector
private var mAllowTouchInterceptionWhileZoomed = true
constructor(context: Context, hierarchy: GenericDraweeHierarchy) : super(context) {
setHierarchy(hierarchy)
init()
}
constructor(context: Context) : super(context) {
inflateHierarchy(context, null)
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context) {
inflateHierarchy(context, attrs)
init()
}
@Suppress("UNUSED_PARAMETER")
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context) {
inflateHierarchy(context, attrs)
init()
}
protected fun inflateHierarchy(context: Context, attrs: AttributeSet?) {
val resources = context.resources
val builder = GenericDraweeHierarchyBuilder(resources)
.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
GenericDraweeHierarchyInflater.updateBuilder(builder, context, attrs)
aspectRatio = builder.desiredAspectRatio
hierarchy = builder.build()
}
private fun init() {
mZoomableController = createZoomableController()
mZoomableController.setListener(mZoomableListener)
mTapGestureDetector = GestureDetector(context, mTapListenerWrapper)
}
/**
* Gets the original image bounds, in view-absolute coordinates.
*
*
*
* The original image bounds are those reported by the hierarchy. The hierarchy itself may
* apply scaling on its own (e.g. due to scale type) so the reported bounds are not necessarily
* the same as the actual bitmap dimensions. In other words, the original image bounds correspond
* to the image bounds within this view when no zoomable transformation is applied, but including
* the potential scaling of the hierarchy.
* Having the actual bitmap dimensions abstracted away from this view greatly simplifies
* implementation because the actual bitmap may change (e.g. when a high-res image arrives and
* replaces the previously set low-res image). With proper hierarchy scaling (e.g. FIT_CENTER),
* this underlying change will not affect this view nor the zoomable transformation in any way.
*/
protected fun getImageBounds(outBounds: RectF) {
hierarchy.getActualImageBounds(outBounds)
}
/**
* Gets the bounds used to limit the translation, in view-absolute coordinates.
*
*
*
* These bounds are passed to the zoomable controller in order to limit the translation. The
* image is attempted to be centered within the limit bounds if the transformed image is smaller.
* There will be no empty spaces within the limit bounds if the transformed image is bigger.
* This applies to each dimension (horizontal and vertical) independently.
*
* Unless overridden by a subclass, these bounds are same as the view bounds.
*/
protected fun getLimitBounds(outBounds: RectF) {
outBounds.set(0f, 0f, width.toFloat(), height.toFloat())
}
/**
* Gets the zoomable controller.
*
*
*
* Zoomable controller can be used to zoom to point, or to map point from view to image
* coordinates for instance.
*/
fun getZoomableController(): ZoomableController {
return mZoomableController
}
/**
* Sets a custom zoomable controller, instead of using the default one.
*/
fun setZoomableController(zoomableController: ZoomableController) {
Preconditions.checkNotNull(zoomableController)
mZoomableController.setListener(null)
mZoomableController = zoomableController
mZoomableController.setListener(mZoomableListener)
}
/**
* Check whether the parent view can intercept touch events while zoomed.
* This can be used, for example, to swipe between images in a view pager while zoomed.
*
* @return true if touch events can be intercepted
*/
fun allowsTouchInterceptionWhileZoomed(): Boolean {
return mAllowTouchInterceptionWhileZoomed
}
/**
* If this is set to true, parent views can intercept touch events while the view is zoomed.
* For example, this can be used to swipe between images in a view pager while zoomed.
*
* @param allowTouchInterceptionWhileZoomed true if the parent needs to intercept touches
*/
fun setAllowTouchInterceptionWhileZoomed(
allowTouchInterceptionWhileZoomed: Boolean) {
mAllowTouchInterceptionWhileZoomed = allowTouchInterceptionWhileZoomed
}
/**
* Sets the tap listener.
*/
fun setTapListener(tapListener: GestureDetector.SimpleOnGestureListener) {
mTapListenerWrapper.setListener(tapListener)
}
/**
* Sets whether long-press tap detection is enabled.
* Unfortunately, long-press conflicts with onDoubleTapEvent.
*/
fun setIsLongpressEnabled(enabled: Boolean) {
mTapGestureDetector.setIsLongpressEnabled(enabled)
}
/**
* Sets the image controller.
*/
override fun setController(controller: DraweeController?) {
setControllers(controller, null)
}
/**
* Sets the controllers for the normal and huge image.
*
*
*
* The huge image controller is used after the image gets scaled above a certain threshold.
*
*
*
* IMPORTANT: in order to avoid a flicker when switching to the huge image, the huge image
* controller should have the normal-image-uri set as its low-res-uri.
*
* @param controller controller to be initially used
* @param hugeImageController controller to be used after the client starts zooming-in
*/
private fun setControllers(
controller: DraweeController?,
hugeImageController: DraweeController?) {
setControllersInternal(null, null)
mZoomableController.setEnabled(false)
setControllersInternal(controller, hugeImageController)
}
private fun setControllersInternal(
controller: DraweeController?,
hugeImageController: DraweeController?) {
removeControllerListener(getController())
addControllerListener(controller)
mHugeImageController = hugeImageController
super.setController(controller)
}
private fun maybeSetHugeImageController() {
if (mHugeImageController != null && mZoomableController.getScaleFactor() > HUGE_IMAGE_SCALE_FACTOR_THRESHOLD) {
setControllersInternal(mHugeImageController, null)
}
}
private fun removeControllerListener(controller: DraweeController?) {
(controller as? AbstractDraweeController<*, *>)?.removeControllerListener(mControllerListener)
}
private fun addControllerListener(controller: DraweeController?) {
(controller as? AbstractDraweeController<*, *>)?.addControllerListener(mControllerListener)
}
override fun onDraw(canvas: Canvas) {
val saveCount = canvas.save()
canvas.concat(mZoomableController.getTransform())
try {
super.onDraw(canvas)
} catch (e: Exception) {
val controller = controller
if (controller != null && controller is AbstractDraweeController<*, *>) {
val callerContext = controller.callerContext
if (callerContext != null) {
throw RuntimeException(
String.format("Exception in onDraw, callerContext=%s", callerContext.toString()),
e)
}
}
throw e
}
canvas.restoreToCount(saveCount)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (mTapGestureDetector.onTouchEvent(event)) {
return true
}
if (mZoomableController.onTouchEvent(event)) {
if (!mAllowTouchInterceptionWhileZoomed && !mZoomableController.isIdentity()) {
parent.requestDisallowInterceptTouchEvent(true)
}
return true
}
if (super.onTouchEvent(event)) {
return true
}
// None of our components reported that they handled the touch event. Upon returning false
// from this method, our parent won't send us any more events for this gesture. Unfortunately,
// some components may have started a delayed action, such as a long-press timer, and since we
// won't receive an ACTION_UP that would cancel that timer, a false event may be triggered.
// To prevent that we explicitly send one last cancel event when returning false.
val cancelEvent = MotionEvent.obtain(event)
cancelEvent.action = MotionEvent.ACTION_CANCEL
mTapGestureDetector.onTouchEvent(cancelEvent)
mZoomableController.onTouchEvent(cancelEvent)
cancelEvent.recycle()
return false
}
override fun computeHorizontalScrollRange(): Int {
return mZoomableController.computeHorizontalScrollRange()
}
override fun computeHorizontalScrollOffset(): Int {
return mZoomableController.computeHorizontalScrollOffset()
}
override fun computeHorizontalScrollExtent(): Int {
return mZoomableController.computeHorizontalScrollExtent()
}
override fun computeVerticalScrollRange(): Int {
return mZoomableController.computeVerticalScrollRange()
}
override fun computeVerticalScrollOffset(): Int {
return mZoomableController.computeVerticalScrollOffset()
}
override fun computeVerticalScrollExtent(): Int {
return mZoomableController.computeVerticalScrollExtent()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
updateZoomableControllerBounds()
}
private fun onFinalImageSet() {
if (!mZoomableController.isEnabled()) {
updateZoomableControllerBounds()
mZoomableController.setEnabled(true)
}
}
private fun onRelease() {
mZoomableController.setEnabled(false)
}
protected fun onTransformChanged() {
maybeSetHugeImageController()
invalidate()
}
protected fun updateZoomableControllerBounds() {
getImageBounds(mImageBounds)
getLimitBounds(mViewBounds)
mZoomableController.setImageBounds(mImageBounds)
mZoomableController.setViewBounds(mViewBounds)
}
protected fun createZoomableController(): ZoomableController {
return AnimatedZoomableController.newInstance()
}
}
| 6 |
Kotlin
|
100
| 148 |
133b0060626a064b437683c3f0182d2bb3066bdb
| 12,707 |
shopapp-android
|
Apache License 2.0
|
libs/tangleLib095/src/main/java/tangle/benchmark/tangleLib095/TangleLib095ViewModel.kt
|
RBusarow
| 415,108,675 | false | null |
package tangle.benchmark.tangleLib095
import androidx.lifecycle.ViewModel
import tangle.viewmodel.VMInject
class TangleLib095ViewModel @VMInject constructor() : ViewModel()
| 0 |
Kotlin
|
0
| 1 |
b271faeb36f8f57977dd2b43d276098e1932f4eb
| 175 |
tangle-benchmark-project
|
Apache License 2.0
|
app/src/main/java/de/lmu/personalflashcards/datahandling/PersonalFlashcardsRepository.kt
|
fionade
| 639,599,746 | false | null |
package de.lmu.personalflashcards.datahandling
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import de.lmu.personalflashcards.model.Quiz
import de.lmu.personalflashcards.model.QuizDao
class PersonalFlashcardsRepository(private val quizDao: QuizDao) {
val allQuizzes: LiveData<List<Quiz>> = quizDao.getAllQuizzes()
val quizCount: LiveData<Int> = quizDao.countQuizzes()
suspend fun insert(quiz: Quiz) {
quizDao.insert(quiz)
}
fun getQuiz(id: Long): LiveData<List<Quiz>> {
return quizDao.getQuiz(id)
}
fun getQuizByImage(imagePath: String): LiveData<List<Quiz>> {
return quizDao.getQuizByImage(imagePath)
}
suspend fun deleteQuiz(quiz: Quiz) {
quizDao.deleteQuiz(quiz)
}
}
| 0 |
Kotlin
|
0
| 0 |
2e0da65c075b97f2d7214ffe2cf6a0fc48fb5aa6
| 779 |
photo-flashcards-client
|
MIT License
|
app/src/main/java/com/noslipclub/noslipclub/ui/search/SearchResultScreen.kt
|
no-slip-club
| 660,735,322 | false |
{"Kotlin": 936245}
|
package com.noslipclub.noslipclub.ui.search
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIosNew
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.noslipclub.noslipclub.data.remote.community.dto.PostWithUserInfo
import com.noslipclub.noslipclub.ui.common.ElevatedSection
import com.noslipclub.noslipclub.ui.common.PostNavigationEvent
import com.noslipclub.noslipclub.ui.community.post.AlignExpandedDropdown
import com.noslipclub.noslipclub.ui.community.post.PostItem
import com.noslipclub.noslipclub.ui.theme.NoSlipTheme
import com.noslipclub.noslipclub.ui.theme.PretendardFamily
import kotlinx.coroutines.flow.MutableStateFlow
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchResultScreen(
keyword: String,
searchResult: LazyPagingItems<PostWithUserInfo>,
currentUid: String,
onPostNavigationEvent: (PostNavigationEvent) -> Unit,
onBack: () -> Unit,
) {
Scaffold(topBar = {
Column(modifier = Modifier.fillMaxWidth()) {
Surface(
shadowElevation = 16.dp, modifier = Modifier
.fillMaxWidth()
.background(Color.White)
) {
TopAppBar(title = {
Text(
text = keyword,
fontSize = 16.sp,
lineHeight = 16.sp,
fontFamily = PretendardFamily,
maxLines = 1
)
}, navigationIcon = {
IconButton(onClick = { onBack() }) {
Icon(
imageVector = Icons.Default.ArrowBackIosNew,
modifier = Modifier
.width(20.dp)
.height(20.dp),
contentDescription = null
)
}
})
}
}
}) { paddingValues ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
color = Color(0xFFF7F7F7)
) {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(6.dp)
//contentPadding = PaddingValues(horizontal = 20.dp, vertical = 16.dp)
) {
item {
ElevatedSection {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${searchResult.itemCount}개의 결과",
fontSize = 12.sp,
lineHeight = 12.sp,
fontFamily = PretendardFamily,
fontWeight = FontWeight.SemiBold,
color = Color(0xFF191919),
)
Spacer(modifier = Modifier.weight(1f, true))
AlignExpandedDropdown(
false,
onExpandedChange = {},
"asdf",
onSelectedOptionChange = {},
listOf("asdf")
) {
}
}
}
}
when (searchResult.loadState.refresh) {
LoadState.Loading -> {}
is LoadState.Error -> {}
else -> {
if (searchResult.itemCount == 0) {
item {
Text(
text = "검색 결과가 없습니다.",
fontSize = 16.sp,
fontFamily = PretendardFamily,
modifier = Modifier.padding(
horizontal = 20.dp,
vertical = 16.dp
)
)
}
} else {
items(count = searchResult.itemCount) { index ->
PostItem(
searchResult[index]!!,
currentUid = currentUid,
onPostItemEvent = onPostNavigationEvent,
)
}
}
}
}
}
}
}
}
@Composable
@Preview
fun PreviewSearchResultScreen() {
NoSlipTheme {
SearchResultScreen(keyword = "검색어",
searchResult = MutableStateFlow(PagingData.from(listOf(PostWithUserInfo()))).collectAsLazyPagingItems(),
onBack = {},
currentUid = "",
onPostNavigationEvent = {})
}
}
| 1 |
Kotlin
|
0
| 0 |
2c72a57f664be0797692f52a470cb97eb9a2197a
| 6,828 |
NoSlipClubAndroid
|
Apache License 2.0
|
src/main/kotlin/me/haroldmartin/detektrules/NoVarsInConstructor.kt
|
hbmartin
| 671,255,622 | false |
{"Kotlin": 39931}
|
package me.haroldmartin.detektrules
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.identifierName
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.allConstructors
class NoVarsInConstructor(config: Config) : Rule(config) {
override val issue: Issue = Issue(
id = javaClass.simpleName,
severity = Severity.CodeSmell,
description = "Do not use `var`s in a class constructor.",
debt = Debt.FIVE_MINS,
)
override fun visitClass(klass: KtClass) {
super.visitClass(klass)
klass.allConstructors.forEach { constructor ->
constructor.valueParameters.forEach { parameter ->
if (parameter.isMutable) {
report(
CodeSmell(
issue = issue,
entity = Entity.from(constructor),
message = "Disallowed `var` parameter ${parameter.text} in constructor for " +
"${klass.identifierName()}, please make it a val.",
),
)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 5 |
615dcf7e25789e2bf45a71e979f193180b5ec8e3
| 1,479 |
hbmartin-detekt-rules
|
Apache License 2.0
|
user/src/main/java/com/example/user/view/user/DeclarationFragment.kt
|
joog-lim
| 382,022,630 | false | null |
package com.study.bamboo.view.fragment.user
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.study.bamboo.R
import com.study.bamboo.data.network.models.user.report.ReportRequest
import com.study.bamboo.databinding.FragmentDeclarationBinding
import com.study.bamboo.view.fragment.user.viewmodel.DeclarationViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class DeclarationFragment : Fragment(
) {
private lateinit var binding: FragmentDeclarationBinding
private val viewModel by viewModels<DeclarationViewModel>()
private val args by navArgs<DeclarationFragmentArgs>()
private var checkPopBackStack = false
private lateinit var callback: OnBackPressedCallback
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onAttach(context: Context) {
super.onAttach(context)
callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d("TAG", "handleOnBackPressed: ")
findNavController().navigate(R.id.action_declarationFragment_to_userMainFragment)
}
}
requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
override fun onDetach() {
super.onDetach()
callback.remove()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_declaration, container, false)
binding.fragment = this
viewModel.setMessage("none")
checkPopBackStack = false
observeViewModel()
return binding.root
}
override fun onResume() {
super.onResume()
checkPopBackStack = false
}
private fun observeViewModel() {
viewModel.message.observe(requireActivity(), Observer {
when (it) {
"success" -> {
Toast.makeText(requireContext(), "신고에 성공했습니다", Toast.LENGTH_SHORT).show()
viewModel.setMessage("none")
Log.d("로그","신고 성공 후 $checkPopBackStack")
if (!checkPopBackStack){
checkPopBackStack = true
[email protected]().popBackStack()
}
}
"fail" ->{ Toast.makeText(requireContext(), "신고에 실패했습니다", Toast.LENGTH_SHORT).show()
binding.btn.isEnabled = true
binding.btn.setBackgroundColor(Color.parseColor("#E75858"))
}
}
})
}
fun backBtnClick(view: View) {
this.findNavController().popBackStack()
}
fun uploadBtn(view: View) {
binding.btn.isEnabled = false
binding.btn.setBackgroundColor(Color.parseColor("#C2C1C1"))
val body = ReportRequest(binding.contents.text.toString())
Log.d("로그", "안에 인 : ${args.id}")
viewModel.report(args.id, body)
}
}
| 3 |
Kotlin
|
0
| 6 |
6ef2fcd7ba798493fc64d6dfdb2be0e506c81c54
| 3,587 |
bamboo-android
|
Apache License 2.0
|
src/main/kotlin/com/redissi/trakt/enums/ListSort.kt
|
IliasRedissi
| 235,675,675 | true |
{"Kotlin": 307912}
|
package com.redissi.trakt.enums
import java.util.*
import kotlin.collections.HashMap
enum class ListSort(val value: String) : TraktEnum {
POPULAR("popular"),
LIKES("likes"),
COMMENTS("comments"),
ITEMS("items"),
ADDED("added"),
UPDATED("updated");
companion object {
private val STRING_MAPPING: MutableMap<String, ListSort> = HashMap()
fun fromValue(value: String): ListSort? {
return STRING_MAPPING[value.toUpperCase(Locale.ROOT)]
}
init {
for (value in values()) {
STRING_MAPPING[value.toString().toUpperCase(Locale.ROOT)] = value
}
}
}
override fun toString(): String {
return value
}
}
| 4 |
Kotlin
|
0
| 0 |
c980c5c428edd8ba2d4b147be5e247e6e1356574
| 736 |
trakt-kotlin
|
The Unlicense
|
src/main/kotlin/moirai/transport/TransportTypes.kt
|
moirai-lang
| 301,230,998 | false |
{"Kotlin": 1306861, "ANTLR": 9622}
|
package moirai.transport
/**
* This type provides a stable public surface for the output of the type system. Whereas
* the internal type system may change at any time, this public surface should never change
* for library consumers. The types in this file can be used as part of a system that translates
* transport formats to Moirai code, such as JSON to Moirai conversion.
*/
sealed interface TransportType
sealed interface TransportCostExpression : TransportType
sealed interface TransportPlatformSumMember : TransportType
data class TransportBinder(val name: String, val type: TransportType)
data object NonPublicTransportType: TransportType
data class TransportFunctionType(
val formalParamTypes: List<TransportType>,
val returnType: TransportType
) : TransportType
data class TransportStandardTypeParameter(
val name: String
) : TransportType
data class TransportFinTypeParameter(
val name: String
) : TransportCostExpression
data class TransportFin(val magnitude: Long) : TransportCostExpression
data object TransportConstantFin : TransportCostExpression
data class TransportSumCostExpression(val args: List<TransportCostExpression>) : TransportCostExpression
data class TransportProductCostExpression(val args: List<TransportCostExpression>) : TransportCostExpression
data class TransportMaxCostExpression(val args: List<TransportCostExpression>) : TransportCostExpression
data class TransportPlatformObjectType(
val name: String
) : TransportType
data class TransportObjectType(
val name: String
) : TransportType
data class TransportGroundRecordType(
val name: String,
val fields: List<TransportBinder>
) : TransportType
data class TransportParameterizedRecordType(
val name: String,
val typeArgs: List<TransportType>,
val fields: List<TransportBinder>
) : TransportType
data class TransportBasicType(
val name: String,
) : TransportType
data class TransportParameterizedBasicType(
val name: String,
val typeArgs: List<TransportType>
) : TransportType
data class TransportPlatformSumType(
val name: String,
val typeArgs: List<TransportType>,
val memberTypes: List<TransportPlatformSumMember>
) : TransportType
data class TransportPlatformSumRecordType(
val sumTypeName: String,
val name: String,
val typeArgs: List<TransportType>,
val fields: List<TransportBinder>
) : TransportPlatformSumMember
data class TransportPlatformSumObjectType(
val sumTypeName: String,
val name: String
) : TransportPlatformSumMember
| 5 |
Kotlin
|
1
| 24 |
9177ca2984084c79494055d321db5abf8360c479
| 2,534 |
moirai-kt
|
MIT License
|
src/main/kotlin/com/github/vp811/customplugin/services/MyApplicationService.kt
|
vp811
| 284,296,286 | false | null |
package com.github.vp811.customplugin.services
import com.github.vp811.customplugin.MyBundle
class MyApplicationService {
init {
println(MyBundle.message("applicationService"))
}
}
| 0 |
Kotlin
|
0
| 0 |
0f54a50036f4429fbe11d152499fe71adf896373
| 200 |
custom-plugin
|
Apache License 2.0
|
paymentsheet/src/main/java/com/stripe/android/paymentsheet/forms/TransformSpecToElement.kt
|
vlad-roid
| 283,964,949 | true |
{"Kotlin": 7742919, "Java": 67407, "Shell": 18256, "Python": 13146, "Ruby": 5171}
|
package com.stripe.android.paymentsheet.forms
import android.content.Context
import com.stripe.android.paymentsheet.addresselement.toIdentifierMap
import com.stripe.android.paymentsheet.paymentdatacollection.FormFragmentArguments
import com.stripe.android.paymentsheet.paymentdatacollection.getInitialValuesMap
import com.stripe.android.ui.core.address.AddressRepository
import com.stripe.android.ui.core.elements.FormItemSpec
import com.stripe.android.ui.core.forms.TransformSpecToElements
import com.stripe.android.ui.core.forms.resources.ResourceRepository
import javax.inject.Inject
/**
* Wrapper around [TransformSpecToElements] that uses the parameters from [FormFragmentArguments].
*/
internal class TransformSpecToElement @Inject constructor(
addressResourceRepository: ResourceRepository<AddressRepository>,
formFragmentArguments: FormFragmentArguments,
context: Context
) {
private val transformSpecToElements =
TransformSpecToElements(
addressResourceRepository = addressResourceRepository,
initialValues = formFragmentArguments.getInitialValuesMap(),
amount = formFragmentArguments.amount,
saveForFutureUseInitialValue = formFragmentArguments.showCheckboxControlledFields,
merchantName = formFragmentArguments.merchantName,
context = context,
shippingValues = formFragmentArguments.shippingDetails
?.toIdentifierMap(formFragmentArguments.billingDetails)
)
internal fun transform(list: List<FormItemSpec>) = transformSpecToElements.transform(list)
}
| 5 |
Kotlin
|
0
| 1 |
b3086c08a51dcc95408359537892711121601749
| 1,602 |
stripe-android
|
MIT License
|
core/dataStore/impl/src/main/kotlin/odoo/miem/android/core/dataStore/impl/DataStore.kt
|
19111OdooApp
| 546,191,502 | false | null |
package odoo.miem.android.core.dataStore.impl
import android.content.Context
import androidx.core.content.edit
import odoo.miem.android.core.dataStore.api.IDataStore
import odoo.miem.android.core.dataStore.impl.preferences.delegates
import odoo.miem.android.core.di.impl.api
import odoo.miem.android.core.platform.di.PlatformApi
import timber.log.Timber
import javax.inject.Inject
// TODO Maybe move to DataStore?
/**
* [DataStore] - implementation of [IDataStore]
*
* @author <NAME>
*/
class DataStore @Inject constructor() : IDataStore {
private val context by api(PlatformApi::context)
private val sharedPreferences by lazy {
context.getSharedPreferences(
PREFERENCES_NAME,
Context.MODE_PRIVATE
)
}
override val url by sharedPreferences.delegates.string()
override fun setUrl(baseUrl: String) {
if (baseUrl != url) {
sharedPreferences.edit {
putString(::url.name, baseUrl)
}
Timber.d("setUrl(): url = $url")
}
}
override val currentUID by sharedPreferences.delegates.int()
override fun setUID(uid: Int) {
if (uid != currentUID) {
sharedPreferences.edit {
putInt(::currentUID.name, uid)
}
Timber.d("setUID(): currentUID = $currentUID")
}
}
override val isAuthorized by sharedPreferences.delegates.boolean()
override fun setAuthorized(authorized: Boolean) {
if (authorized != isAuthorized) {
sharedPreferences.edit {
putBoolean(::isAuthorized.name, authorized)
}
Timber.d("setHseAuthorized(): authorized = $authorized")
}
}
override val sessionId by sharedPreferences.delegates.string()
override fun setSessionId(newSessionId: String) {
if (newSessionId != sessionId) {
sharedPreferences.edit {
putString(::sessionId.name, newSessionId)
}
Timber.d("setSessionId(): sessionId = $newSessionId")
}
}
private companion object {
const val PREFERENCES_NAME = "dataStore"
}
}
| 0 |
Kotlin
|
1
| 2 |
7eb654a950ead064c629031bba47eebdb9505655
| 2,170 |
OdooApp-Android
|
Apache License 2.0
|
core/src/main/java/com/wolking/core/domain/stock_alert/use_cases/SetStocksAlert.kt
|
paulowolking
| 509,890,806 | false | null |
package com.wolking.core.domain.stock_alert.use_cases
import com.wolking.core.data.database.models.StockAlertDB
import com.wolking.core.data.finance.models.mocks.StockMock
import com.wolking.core.data.shared.CoroutineDispatchers
import com.wolking.core.domain.shared.UseCase
import com.wolking.core.extensions.moneyToDoublePrice
import com.wolking.core.domain.database.repositories.StockAlertDBRepository
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Inject
class SetStocksAlert @Inject constructor(
coroutineDispatchers: CoroutineDispatchers,
private val stockAlertDBRepository: StockAlertDBRepository,
) : UseCase<List<StockMock>, Boolean>(coroutineDispatchers.defaultContext as CoroutineDispatcher) {
override suspend fun execute(params: List<StockMock>): Boolean {
val stocksMoneyReal: MutableList<StockAlertDB> = mutableListOf()
params.forEach {
stocksMoneyReal.add(
StockAlertDB(
code = it.code,
priceAlert = it.priceAlert.moneyToDoublePrice(),
typeStock = it.typeStockEnum,
companyImage = it.companyImage
)
)
}
return stockAlertDBRepository.insertOrUpdate(stocksMoneyReal)
}
}
| 8 |
Kotlin
|
0
| 2 |
3a98ef920ffd4b6ee7b7c27ca06cb2b5fa4695ae
| 1,291 |
investing-android
|
Apache License 2.0
|
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffKeys.kt
|
JetBrains
| 2,489,216 | false | null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diff.tools.combined
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.util.Key
val COMBINED_DIFF_VIEWER = DataKey.create<CombinedDiffViewer>("combined_diff_viewer")
val COMBINED_DIFF_PROCESSOR = Key.create<CombinedDiffRequestProcessor>("combined_diff_processor")
| 191 | null |
4372
| 13,319 |
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 434 |
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/sunnyweather/android/ui/adapter/HomeAdapter.kt
|
zml254
| 278,017,936 | false | null |
package com.sunnyweather.android.ui.adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sunnyweather.android.R
import com.sunnyweather.android.ui.activity.WebActivity
import com.sunnyweather.android.bean.Article
import com.sunnyweather.android.bean.Banner
class HomeAdapter(
private val articleList: List<Article>,
private val recyclerView: RecyclerView,
private val banners: List<Banner>
) : RecyclerView.Adapter<HomeAdapter.ViewHolder>() {
private var parent: ViewGroup? = null
open class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var chapterName: TextView? = itemView.findViewById(R.id.tv_home_item_chapterName)
var niceDate: TextView? = itemView.findViewById(R.id.tv_home_item_niceDate)
var author: TextView? = itemView.findViewById(R.id.tv_home_item_author)
var title: TextView? = itemView.findViewById(R.id.tv_home_item_title)
var link: String? = null
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
this.parent = parent
when (viewType) {
VIEW_TYPE_ONE -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_home_banner, recyclerView, false)
return BannerViewHolder(
view,
parent,
banners
)
}
VIEW_TYPE_TWO -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.rv_header_home, recyclerView, false)
return ViewHolder(view)
}
else -> {
val view = LayoutInflater.from(parent.context).inflate(
R.layout.rv_item_home, parent, false
)
return ViewHolder(view)
}
}
}
override fun onBindViewHolder(
holder: ViewHolder,
position: Int
) {
if (position == 0 || position == 1) {
return
}
val article: Article = articleList[position - 2]
holder.title?.text = article.title
holder.author?.text = article.author
holder.chapterName?.text = article.chapterName
holder.niceDate?.text = article.niceDate
holder.link = article.link
holder.title?.setOnClickListener {
val intent = Intent(parent!!.context, WebActivity::class.java)
intent.putExtra("webUrl", holder.link)
parent!!.context.startActivity(intent)
}
}
override fun getItemViewType(position: Int): Int {
return if (position == 0) {
VIEW_TYPE_ONE
} else if (position == 1) {
VIEW_TYPE_TWO
} else {
VIEW_TYPE_THREE
}
}
override fun getItemCount(): Int {
return articleList.size
}
companion object {
private const val VIEW_TYPE_ONE = 1
private const val VIEW_TYPE_TWO = 2
private const val VIEW_TYPE_THREE = 3
}
}
| 0 |
Kotlin
|
0
| 0 |
48dbd33992506fd07e87f0cbaf421abd3edfddd9
| 3,246 |
SunnyWeather
|
Apache License 2.0
|
ffmpeg-recorder/src/main/java/com/github/windsekirun/naraeaudiorecorder/ffmpeg/listener/OnConvertStateChangeListener.kt
|
WindSekirun
| 164,206,852 | false | null |
package com.github.windsekirun.naraeaudiorecorder.ffmpeg.listener
import com.github.windsekirun.naraeaudiorecorder.ffmpeg.model.FFmpegConvertState
/**
* Listener for handling state changes
*/
interface OnConvertStateChangeListener {
/**
* Call when [FFmpegConvertState] is changed
*/
fun onState(state: FFmpegConvertState)
}
| 9 |
Kotlin
|
19
| 85 |
dd59377b2a41db32b4244e4d0135d0c7e82bdad6
| 347 |
NaraeAudioRecorder
|
Apache License 2.0
|
ffmpeg-recorder/src/main/java/com/github/windsekirun/naraeaudiorecorder/ffmpeg/listener/OnConvertStateChangeListener.kt
|
WindSekirun
| 164,206,852 | false | null |
package com.github.windsekirun.naraeaudiorecorder.ffmpeg.listener
import com.github.windsekirun.naraeaudiorecorder.ffmpeg.model.FFmpegConvertState
/**
* Listener for handling state changes
*/
interface OnConvertStateChangeListener {
/**
* Call when [FFmpegConvertState] is changed
*/
fun onState(state: FFmpegConvertState)
}
| 9 |
Kotlin
|
19
| 85 |
dd59377b2a41db32b4244e4d0135d0c7e82bdad6
| 347 |
NaraeAudioRecorder
|
Apache License 2.0
|
app/src/main/java/net/eucalypto/timetracker/data/database/TimeTrackerDatabase.kt
|
eucalypto
| 290,498,874 | false | null |
package net.eucalypto.timetracker.data.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import net.eucalypto.timetracker.data.database.entities.DatabaseActivity
import net.eucalypto.timetracker.data.database.entities.DatabaseCategory
import net.eucalypto.timetracker.data.database.entities.RoomTypeConverters
@Database(entities = [DatabaseCategory::class, DatabaseActivity::class], version = 1)
@TypeConverters(RoomTypeConverters::class)
abstract class TimeTrackerDatabase : RoomDatabase() {
abstract val categoryDao: DatabaseCategoryDao
abstract val activityDao: DatabaseActivityDao
}
@Volatile
private lateinit var INSTANCE: TimeTrackerDatabase
fun getDatabase(context: Context): TimeTrackerDatabase {
synchronized(TimeTrackerDatabase::class.java) {
if (!::INSTANCE.isInitialized) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
TimeTrackerDatabase::class.java,
"timetracker.db"
).build()
}
return INSTANCE
}
}
| 22 |
Kotlin
|
0
| 0 |
5cfd66c0d11f0fc23bd3787f66448445cd5f2359
| 1,164 |
time-tracker
|
MIT License
|
app/src/main/java/com/ice/ktuice/al/gradeTable/GradeTableManager.kt
|
vysnia121
| 188,022,529 | true |
{"Kotlin": 198545, "Java": 125470}
|
package com.ice.ktuice.al.gradeTable
import com.ice.ktuice.al.gradeTable.gradeTableModels.GradeTableFactory
import com.ice.ktuice.al.gradeTable.gradeTableModels.GradeTableModel
import com.ice.ktuice.al.gradeTable.gradeTableModels.SemesterAdapterItem
import com.ice.ktuice.models.YearGradesCollectionModel
import com.ice.ktuice.models.YearModel
import com.ice.ktuice.al.services.scrapers.base.exceptions.AuthenticationException
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import org.jetbrains.anko.getStackTraceString
import org.koin.standalone.KoinComponent
/**
* Created by Andrius on 2/15/2018.
* A helper class to contain the logic of the grade table and supply the models
*/
class GradeTableManager: KoinComponent, AnkoLogger{
fun constructGradeTableModel(yearGradesList: YearGradesCollectionModel): GradeTableModel?{
try{
val table = GradeTableFactory.buildGradeTableFromYearGradesModel(yearGradesList)
table.printRowCounts()
return table
}catch (it: Exception){
when(it.javaClass){
AuthenticationException::class.java -> {
try {
//recursive auth trying
return constructGradeTableModel(yearGradesList)
}catch (e: Exception){
info(e.getStackTraceString())
}
}
}
info(it.getStackTraceString())
}
return null
}
fun constructSemesterAdapterSpinnerItemList(yearsList: YearGradesCollectionModel):List<SemesterAdapterItem>{
val itemList = mutableListOf<SemesterAdapterItem>()
yearsList.forEach {
val year = it.year
it.semesterList.forEach {
itemList.add(SemesterAdapterItem(it.semester, it.semester_number, YearModel(year.id, year.year)))
}
}
return itemList
}
}
| 0 |
Kotlin
|
0
| 0 |
b102bd4a6dbcc915f40236fce5f389c8f147fe45
| 1,960 |
KTU-ice
|
MIT License
|
app/src/main/java/io/traxa/ui/upload/UploadActivityViewModel.kt
|
chrisinvb
| 517,052,842 | false |
{"Kotlin": 213490, "Java": 18186}
|
package io.traxa.ui.upload
import android.app.Application
import android.content.Intent
import android.media.MediaPlayer
import android.util.Log
import android.view.View
import androidx.lifecycle.*
import androidx.work.WorkManager
import dispatch.core.launchIO
import io.traxa.R
import io.traxa.persistence.AppDatabase
import io.traxa.persistence.entities.CaptureFile
import io.traxa.persistence.entities.ContainerCapture
import io.traxa.persistence.entities.RecordingStatus
import io.traxa.repositories.PlayerTokenRepository
import io.traxa.services.Prefs
import io.traxa.services.network.AwsService
import io.traxa.ui.containers.detail.ContainerDetailActivity
import io.traxa.utils.Constants
import io.traxa.workers.UploadWorker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import java.io.File
class UploadActivityViewModel(app: Application) : AndroidViewModel(app), KoinComponent {
private val prefs: Prefs by inject()
private val db: AppDatabase by inject()
private val awsService: AwsService by inject()
private val tokenRepository: PlayerTokenRepository by inject()
private val recordingDao = db.recordingDao()
private val containerDao = db.containerDao()
private val captureFileDao = db.captureFileDao()
private val explorerWallet =
"https://viewblock.io/arweave/address/OK_m2Tk41N94KZLl5WQSx_-iNWbvcp8EMfrYsel_QeQ"
private val workManager = WorkManager.getInstance(app)
private var levelupSound = MediaPlayer.create(app.applicationContext, R.raw.levelup).also {
it.isLooping = false
it.setVolume(.8f, .8f)
}
var waitingTime: Float = Constants.waitingTime
suspend fun getContainerCount() = containerDao.getContainerCount()
fun calculateSecondsPassed() = prefs.getUploadStartTime().let {
if (it == 0L) 0
else (System.currentTimeMillis() / 1000) - it
}
val secondsPassed = MutableLiveData(calculateSecondsPassed())
val container = MutableLiveData<ContainerCapture>()
val timeLeft = secondsPassed.map {
val timeLeftSeconds = (waitingTime * 60) - it
val minutes = (timeLeftSeconds / 60).toInt()
val seconds = (timeLeftSeconds % 60).toInt()
"$minutes:${"$seconds".padStart(2, '0')}"
}
private val latestRecordingId = MutableLiveData<Int>()
private val latestRecordingCaptureFile = MutableLiveData<CaptureFile>()
val recordingStatus = latestRecordingId
.switchMap { recordingDao.loadAllByIdsLiveData(it) }
.map { it.firstOrNull() }
.map { it?.status }
val message = latestRecordingId
.switchMap { recordingStatus }
.map {
if (it == RecordingStatus.DONE) R.string.processing
else R.string.uploading_picture
}
val recordingUploadProgress = latestRecordingId
.switchMap { workManager.getWorkInfosByTagLiveData("$it") }
.map { UploadWorker.getProgress(it).toInt() }
val isMonitorWalletVisible = MutableLiveData(false)
fun shareDiscord(view: View) {
val context = view.context
context.startActivity(Intent.parseUri(Constants.DISCORD, 0))
}
fun shareFeedback(view: View) {
val context = view.context
context.startActivity(Intent.parseUri(Constants.FEEDBACK, 0))
}
fun monitorWallet(view: View) {
val context = view.context
val uid = container.value?.uid ?: ""
context.startActivity(
Intent(context, ContainerDetailActivity::class.java)
.putExtra("uid", uid)
)
}
suspend fun checkToken() {
val tokens = withContext(Dispatchers.IO) { tokenRepository.getPlayerTokens() }
val token = tokens.find { it.captureKey == ""+latestRecordingId.value!! }
if (token != null) {
levelupSound.start()
isMonitorWalletVisible.value = true
}else {
delay(30 * 1000L)
checkToken()
}
}
suspend fun uploadThumbnail(thumbnail: File) {
val recordingId = prefs.getLatestRecordingId()
val captureFile = captureFileDao.loadAllByRecordingId(recordingId)
.lastOrNull()
Log.d("UploadActivityViewModel", "captureFile: $captureFile")
val filename = captureFile?.aliasFilename
?.replace(".mp4", ".${thumbnail.extension}")
Log.d("UploadActivityViewModel", "uploadThumbnail: $filename")
awsService.uploadFile(thumbnail, filename, "thumbnails")
}
init {
viewModelScope.launchIO {
val recordingId = prefs.getLatestRecordingId()
latestRecordingId.postValue(recordingId)
container.postValue(containerDao.getByRecordingId(recordingId).firstOrNull())
}
}
}
| 0 |
Kotlin
|
0
| 0 |
a21ba2aa3dfa3056083b0f72c644c913c3df45b8
| 4,937 |
traxaio_android_polygon_filecoin
|
MIT License
|
src/main/java/jp/ex_t/kazuaki/change_vision/event_listener/MindmapDiagramEventListener.kt
|
ChangeVision
| 348,599,666 | false | null |
/*
* MindmapDiagramEventListener.kt - pair-modeling
* Copyright © 2021 HyodaKazuaki.
*
* Released under the MIT License.
* see https://opensource.org/licenses/MIT
*/
package jp.ex_t.kazuaki.change_vision.event_listener
import com.change_vision.jude.api.inf.model.IMindMapDiagram
import com.change_vision.jude.api.inf.model.INamedElement
import com.change_vision.jude.api.inf.presentation.ILinkPresentation
import com.change_vision.jude.api.inf.presentation.INodePresentation
import com.change_vision.jude.api.inf.project.ProjectEditUnit
import jp.ex_t.kazuaki.change_vision.Logging
import jp.ex_t.kazuaki.change_vision.logger
import jp.ex_t.kazuaki.change_vision.network.*
import kotlinx.serialization.ExperimentalSerializationApi
class MindmapDiagramEventListener(private val entityTable: EntityTable, private val mqttPublisher: MqttPublisher) :
IEventListener {
@ExperimentalSerializationApi
override fun process(projectEditUnit: List<ProjectEditUnit>) {
logger.debug("Start process")
val removeProjectEditUnit = projectEditUnit.filter { it.operation == Operation.REMOVE.ordinal }
val removeDiagramUnit = removeProjectEditUnit.filter { it.entity is IMindMapDiagram }
val removeDiagramOperation = removeDiagramUnit.mapNotNull { deleteMindMapDiagram(it.entity as IMindMapDiagram) }
if (removeDiagramOperation.isNotEmpty()) {
ProjectChangedListener.encodeAndPublish(Transaction(removeDiagramOperation), mqttPublisher)
return
}
val otherRemoveUnit = removeProjectEditUnit - removeDiagramUnit
val removeOperations = otherRemoveUnit.mapNotNull { editUnit ->
Operation.values()[editUnit.operation].let { op -> logger.debug("Op: $op -> ") }
when (val entity = editUnit.entity) {
is INodePresentation -> deleteTopic(entity)
else -> {
logger.debug("$entity(Unknown)")
null
}
}
}
if (removeOperations.isNotEmpty()) {
val removeTransaction = Transaction(removeOperations)
ProjectChangedListener.encodeAndPublish(removeTransaction, mqttPublisher)
return
}
val addProjectEditUnit = projectEditUnit.filter { it.operation == Operation.ADD.ordinal }
val addDiagramUnit = addProjectEditUnit.filter { it.entity is IMindMapDiagram }
addDiagramUnit.forEach {
val createDiagramTransaction = Transaction(listOf(createMindMapDiagram(it.entity as IMindMapDiagram)))
ProjectChangedListener.encodeAndPublish(createDiagramTransaction, mqttPublisher)
return
}
val otherAddUnit = addProjectEditUnit - addDiagramUnit
val createOperations = otherAddUnit.mapNotNull {
val operation = Operation.values()[it.operation]
logger.debug("Op: $operation -> ")
when (val entity = it.entity) {
is INodePresentation -> {
when (entity.diagram) {
is IMindMapDiagram -> {
when (entity.parent) {
null -> createFloatingTopic(entity)
else -> createTopic(entity) ?: return
}
}
else -> {
logger.debug("${entity.label}(Unknown)")
null
}
}
}
is ILinkPresentation -> {
val source = entity.source.model
val target = entity.target.model
logger.debug("$source(Unknown) - ${entity.label}(ILinkPresentation) - $target(Unknown)")
null
}
else -> {
logger.debug("$entity(Unknown)")
null
}
}
}
if (createOperations.isNotEmpty()) {
val createTransaction = Transaction(createOperations)
ProjectChangedListener.encodeAndPublish(createTransaction, mqttPublisher)
return
}
val modifyProjectEditUnit = projectEditUnit.filter { it.operation == Operation.MODIFY.ordinal }
val modifyOperations = modifyProjectEditUnit.mapNotNull {
val operation = Operation.values()[it.operation]
logger.debug("Op: $operation -> ")
when (val entity = it.entity) {
is IMindMapDiagram -> modifyMindMapDiagram(entity)
is INodePresentation -> modifyTopic(entity)
else -> {
logger.debug("$entity(Unknown)")
null
}
}
}
if (modifyOperations.isNotEmpty()) {
val modifyTransaction = Transaction(modifyOperations)
ProjectChangedListener.encodeAndPublish(modifyTransaction, mqttPublisher)
}
}
private fun createMindMapDiagram(entity: IMindMapDiagram): CreateMindmapDiagram {
val owner = entity.owner as INamedElement
val rootTopic = entity.root
logger.debug("${entity.name}(IMindMapDiagram)")
entityTable.entries.add(Entry(entity.id, entity.id))
entityTable.entries.add(Entry(rootTopic.id, rootTopic.id))
return CreateMindmapDiagram(entity.name, owner.name, rootTopic.id, entity.id)
}
private fun createFloatingTopic(entity: INodePresentation): CreateFloatingTopic? {
val location = Pair(entity.location.x, entity.location.y)
val size = Pair(entity.width, entity.height)
entityTable.entries.add(Entry(entity.id, entity.id))
logger.debug("${entity.label}(INodePresentation, FloatingTopic)")
val diagramEntry = entityTable.entries.find { it.mine == entity.diagram.id } ?: run {
logger.debug("${entity.diagram.id} not found on LUT.")
return null
}
return CreateFloatingTopic(entity.label, location, size, diagramEntry.common, entity.id)
}
private fun createTopic(entity: INodePresentation): CreateTopic? {
entityTable.entries.add(Entry(entity.id, entity.id))
val parentEntry = entityTable.entries.find { it.mine == entity.parent.id } ?: run {
logger.debug("${entity.parent.id} not found on LUT.")
return null
}
logger.debug("${entity.parent.label}(INodePresentation) - ${entity.label}(INodePresentation)")
val diagramEntry = entityTable.entries.find { it.mine == entity.diagram.id } ?: run {
logger.debug("${entity.diagram.id} not found on LUT.")
return null
}
return CreateTopic(parentEntry.common, entity.label, diagramEntry.common, entity.id)
}
private fun modifyMindMapDiagram(entity: IMindMapDiagram): ModifyDiagram? {
val entry = entityTable.entries.find { it.mine == entity.id } ?: run {
logger.debug("${entity.id} not found on LUT.")
return null
}
val ownerEntry = entityTable.entries.find { it.mine == entity.owner.id } ?: run {
logger.debug("${entity.owner.id} not found on LUT.")
return null
}
logger.debug("${entity.name}(IMindMapDiagram), owner ${entity.owner}")
return ModifyDiagram(entity.name, entry.common, ownerEntry.common)
}
private fun modifyTopic(entity: INodePresentation): ModifyTopic? {
return when (val diagram = entity.diagram) {
is IMindMapDiagram -> {
val location = Pair(entity.location.x, entity.location.y)
val size = Pair(entity.width, entity.height)
logger.debug(
"${entity.label}(INodePresentation)::Topic(${
Pair(
entity.width,
entity.height
)
} at ${entity.location}) @MindmapDiagram${diagram.name}"
)
val entry = entityTable.entries.find { it.mine == entity.id } ?: run {
logger.debug("${entity.id} not found on LUT.")
return null
}
// Root topic and floating topic have no parent, so parent entry is empty. (It means parent id is also empty.)
val parentEntry =
if (entity.parent == null) Entry(
"",
""
) else entityTable.entries.find { it.mine == entity.parent.id }
?: run {
logger.debug("${entity.parent.id} not found on LUT.")
return null
}
val diagramEntry = entityTable.entries.find { it.mine == entity.diagram.id } ?: run {
logger.debug("${entity.diagram.id} not found on LUT.")
return null
}
ModifyTopic(entity.label, location, size, parentEntry.common, diagramEntry.common, entry.common)
}
else -> {
logger.debug("${entity.label}(INodePresentation) @UnknownDiagram")
null
}
}
}
private fun deleteMindMapDiagram(entity: IMindMapDiagram): DeleteMindmapDiagram? {
return run {
val lut = entityTable.entries.find { it.mine == entity.id } ?: run {
logger.debug("${entity.id} not found on LUT.")
return null
}
entityTable.entries.remove(lut)
logger.debug("${entity}(IMindMapDiagram)")
DeleteMindmapDiagram(lut.common)
}
}
private fun deleteTopic(entity: INodePresentation): DeleteTopic? {
return run {
val lut = entityTable.entries.find { it.mine == entity.id } ?: run {
logger.debug("${entity.id} not found on LUT.")
return null
}
entityTable.entries.remove(lut)
logger.debug("${entity}(INodePresentation) @MindmapDiagram")
val diagramEntry = entityTable.entries.find { it.mine == entity.diagram.id } ?: run {
logger.debug("${entity.diagram.id} not found on LUT.")
return null
}
DeleteTopic(lut.common, diagramEntry.common)
}
}
companion object : Logging {
private val logger = logger()
}
}
| 0 |
Kotlin
|
0
| 0 |
4cd87dc26496f79b39be300a351f7a3f9453189d
| 10,534 |
astah-pair-modeling-plugin
|
MIT License
|
app/src/main/java/com/battlelancer/seriesguide/ui/search/ShowsPopularDataSourceFactory.kt
|
NYStud
| 287,155,464 | true |
{"Java Properties": 2, "Markdown": 10, "Gradle": 9, "Shell": 1, "Text": 2, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 1, "XML": 379, "Java": 314, "Kotlin": 170, "CSS": 1, "YAML": 2, "INI": 1, "Proguard": 1, "JSON": 5}
|
package com.battlelancer.seriesguide.ui.search
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.paging.DataSource
import com.uwetrottmann.trakt5.services.Shows
class ShowsPopularDataSourceFactory(
val context: Context,
val traktShows: Shows
) : DataSource.Factory<Int, SearchResult>() {
val dataSourceLiveData = MutableLiveData<ShowsPopularDataSource>()
override fun create(): DataSource<Int, SearchResult> {
val source = ShowsPopularDataSource(context, traktShows)
dataSourceLiveData.postValue(source)
return source
}
}
| 0 | null |
0
| 1 |
61679ed1f755cecc021ba684f6b63dafc149161e
| 617 |
SeriesGuide
|
The Unlicense
|
models/src/main/java/com/vimeo/networking2/enums/SlackLanguagePreferenceType.kt
|
vimeo
| 41,306,732 | false | null |
package com.vimeo.networking2.enums
/**
* Language preference of the Slack channel being notified.
*/
enum class SlackLanguagePreferenceType(override val value: String?) : StringValue {
/**
* German.
*/
GERMAN("de-DE"),
/**
* English.
*/
ENGLISH("en"),
/**
* Spanish.
*/
SPANISH("es"),
/**
* French.
*/
FRENCH("fr-FR"),
/**
* Japanese.
*/
JAPANESE("ja-JP"),
/**
* Korean.
*/
KOREAN("ko-KR"),
/**
* Brazilian Portuguese.
*/
BRAZILIAN_PORTUGUESE("pt-BR"),
/**
* Unknown language preference.
*/
UNKNOWN(null)
}
| 21 |
Kotlin
|
52
| 123 |
e4f31d4fa144756d576101b3a82120657e9e8a51
| 663 |
vimeo-networking-java
|
MIT License
|
posts-server/src/main/kotlin/com/peterkrauz/postsapp/config/WebMvcConfig.kt
|
peterkrauz
| 187,952,877 | false |
{"JavaScript": 17439, "Kotlin": 13695, "HTML": 1615}
|
package com.peterkrauz.postsapp.config
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Configuration
class WebMvcConfig: WebMvcConfigurer {
private val MAX_AGE: Long = 3600
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
.maxAge(MAX_AGE)
}
}
| 0 |
JavaScript
|
0
| 0 |
eb0c1862bacb60e677caec32f3275dfc84ba4926
| 602 |
posts-app
|
Apache License 2.0
|
sdk/src/main/java/io/customer/sdk/util/DateUtil.kt
|
customerio
| 355,691,391 | false |
{"Kotlin": 458145, "Shell": 4485, "Makefile": 1568, "Ruby": 257}
|
package io.customer.sdk.util
import io.customer.base.extenstions.getUnixTimestamp
import java.util.*
/**
* Exists to make test functions easier to write since we can mock the date.
*/
interface DateUtil {
val now: Date
val nowUnixTimestamp: Long
}
internal class DateUtilImpl : DateUtil {
override val now: Date
get() = Date()
override val nowUnixTimestamp: Long
get() = this.now.getUnixTimestamp()
}
| 2 |
Kotlin
|
9
| 9 |
022a5b53605395ec5f7a8cd790b9cb38ada367df
| 439 |
customerio-android
|
MIT License
|
idea/testData/inspectionsLocal/ImplicitNullableNothingType/val.kt
|
JakeWharton
| 99,388,807 | true | null |
// PROBLEM: none
val <caret>x = null
| 0 |
Kotlin
|
28
| 83 |
4383335168338df9bbbe2a63cb213a68d0858104
| 37 |
kotlin
|
Apache License 2.0
|
compose/src/main/kotlin/io/github/kakaocup/compose/intercept/operation/ComposeOperationType.kt
|
KakaoCup
| 403,825,613 | false |
{"Kotlin": 76070, "Ruby": 84}
|
package io.github.kakaocup.compose.intercept.operation
/**
* Type of the concrete action executing on the given element of Jetpack Compose
*/
interface ComposeOperationType {
val name: String
}
| 7 |
Kotlin
|
6
| 99 |
69c8a16f5dcfe684a594ee4c0b6c7fac4fb8ccaa
| 200 |
Compose
|
Apache License 2.0
|
app/src/main/java/com/jutikorn/eddieplayer/song/structure/MusicPlayerImpl.kt
|
jutikorn
| 144,380,852 | false | null |
package com.jutikorn.eddieplayer.song.structure
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.media.AudioManager
import android.support.v4.app.Fragment
import com.jutikorn.eddieplayer.song.SongContract
import android.media.MediaPlayer
import android.net.Uri
import android.media.AudioAttributes
import android.os.Build
class MusicPlayerImpl(val fragment: Fragment) : SongContract.MusicPlayer, LifecycleObserver {
override fun isPlaying(): Boolean = mediaPlayer.isPlaying
override fun seekTo(seek: Int) {
}
var mediaPlayer: MediaPlayer = MediaPlayer()
// "http://www.samisite.com/sound/cropShadesofGrayMonkees.mp3"
override fun setSource(url: String) {
fragment.context?.let {
mediaPlayer.setDataSource(it, Uri.parse("http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3"))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mediaPlayer.setAudioAttributes(AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build())
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
}
mediaPlayer.prepare()
}
}
override fun play() {
if (!isPlaying()) {
mediaPlayer.start()
}
}
override fun pause() {
if (isPlaying()) {
mediaPlayer.pause()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
override fun stop() {
mediaPlayer.stop()
mediaPlayer.release()
}
override fun getDuration(): Int = mediaPlayer.duration
}
| 0 |
Kotlin
|
0
| 0 |
122082e17817795792cfda957e7ce090b1daf03b
| 1,819 |
eddieplayer
|
MIT License
|
definitions-builder/src/main/kotlin/fledware/definitions/util/FunctionWrapper.kt
|
fledware
| 408,627,203 | false |
{"Kotlin": 545508}
|
package fledware.definitions.util
import fledware.utilities.TypedMap
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
/**
* This utility wraps a function to create utility methods with
* easy to understand error messages.
*
* This leverages [safeCallBy] and [safeCall] methods that will
* check every parameter and validate them.
*
* There are three varieties of call methods:
* callWithParams:
* these calls happen like normal calls where param order/type matter
*
* callWithContext: these calls try to find the correct types needed for the
* params. this allows callers to not know the exact types/order of the
* params to be a successful call. They will automatically find the [KParameter]
* needed and build the [KFunction.callBy] input.
*
* This strategy also allows users to build a common context that can be
* used for all methods.
*/
@Suppress("MemberVisibilityCanBePrivate")
class FunctionWrapper(val function: KFunction<*>) {
/**
* used to cache the map used in [callWithContexts]
*/
val parametersByName by lazy {
function.parameters.associateBy {
it.name ?: throw UnsupportedOperationException("parameters must have a name: $function")
}
}
/**
* calls the function with no arguments.
*/
fun call(): Any? {
return function.safeCallBy(this, emptyMap())
}
/**
* calls the function with the params in the list.
*/
fun callWithParams(params: List<Any?>): Any? {
return function.safeCall(this, *params.toTypedArray())
}
/**
* calls the function with the params in the list.
*/
fun callWithParams(vararg params: Any?): Any? {
return function.safeCall(this, *params)
}
/**
* this will attempt to call the method based on the types
* that are in [contexts].
*/
fun callWithContexts(contexts: List<Any>): Any? {
val inputs = mutableMapOf<KParameter, Any?>()
function.parameters.forEach { parameter ->
val klass = parameter.type.classifier as KClass<*>
val value = contexts.firstOrNull { klass.isInstance(it) }
inputs.setParam(parameter, value)
}
return function.safeCallBy(this, inputs)
}
/**
* this will attempt to call the method based on the types
* that are in [contexts].
*/
fun callWithContexts(vararg contexts: Any?): Any? {
val inputs = mutableMapOf<KParameter, Any?>()
function.parameters.forEach { parameter ->
val klass = parameter.type.classifier as KClass<*>
val value = contexts.firstOrNull { klass.isInstance(it) }
inputs.setParam(parameter, value)
}
return function.safeCallBy(this, inputs)
}
/**
* this will attempt to call the method based on the names of the
* parameters of the method.
*/
fun callWithContexts(contexts: Map<String, Any>): Any? {
val inputs = mutableMapOf<KParameter, Any?>()
parametersByName.forEach { (name, parameter) ->
inputs.setParam(parameter, contexts[name])
}
return function.safeCallBy(this, inputs)
}
/**
*
*/
fun callWithContexts(contexts: TypedMap<Any>): Any? {
val inputs = mutableMapOf<KParameter, Any?>()
function.parameters.forEach { parameter ->
val klass = parameter.type.classifier as KClass<*>
val value = contexts.getOrNull(klass)
inputs.setParam(parameter, value)
}
return function.safeCallBy(this, inputs)
}
}
| 6 |
Kotlin
|
0
| 0 |
2422b5f3bce36d5e7ea5e0962e94f2f2bcd3997e
| 3,400 |
FledDefs
|
Apache License 2.0
|
src/main/kotlin/engine/math/geometry/Rectangle.kt
|
Medina1402
| 388,346,616 | false | null |
package engine.math.geometry
import engine.math.Vector
import engine.scene.Actor
import java.awt.Color
import java.awt.Graphics
/**
* Create rectangle based to point top left and dimensions of rectangle, color is optional
*
* @example:
* > ...
* Rectangle rect = new Rectangle(0, 0, 5, 5);
* Rectangle rect2 = new Rectangle(0, 0, 5, 5, Color.DARK_GRAY);
* Rectangle rect3 = new Rectangle(new Vector<Int>(0, 0), new Vector<Int>(5, 5));
* > ...
*
* @author Abraham Medina Carrillo <https://github.com/medina1402>
*/
class Rectangle : Actor {
var size: Vector<Int>
var location: Vector<Int>
var color: Color? = null
constructor(position: Vector<Int>, size: Vector<Int>, color: Color? = null) {
this.location = position
this.size = size
if(color != null) this.color = color
}
constructor(x: Int, y: Int, width: Int, height: Int, color: Color? = null) {
location = Vector(x, y)
size = Vector(width, height)
if(color != null) this.color = color
}
/**
* Draw rectangle fill content
*
* @param g is Graphics Context
*/
override fun draw(g: Graphics) {
if(color != null) {
val color2 = g.color
g.color = color
g.fillRect(location.x, location.y, size.x, size.y)
g.color = color2
}
}
}
| 0 |
Kotlin
|
0
| 0 |
549fa9d3cc978379d74050dd5e862d13a468929e
| 1,364 |
KGame2D
|
MIT License
|
app/basic/src/main/kotlin/zhupf/gadget/basic/activity/GadgetActivity.kt
|
Zhupff
| 425,161,721 | false |
{"Gradle Kotlin DSL": 25, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 8, "TOML": 1, "Kotlin": 61, "Proguard": 1, "Text": 2, "XML": 17, "Java": 85}
|
package zhupf.gadget.basic.activity
import android.content.res.Configuration
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowInsetsControllerCompat
import zhupf.gadgets.basic.OnConfigurationChangedDispatcher
import zhupf.gadgets.basic.OnConfigurationChangedListener
import zhupf.gadgets.logger.logV
import java.util.concurrent.CopyOnWriteArraySet
abstract class GadgetActivity : AppCompatActivity(), OnConfigurationChangedDispatcher {
protected open val TAG: String = "${this::class.java.simpleName}(${hashCode()})"
protected val onConfigurationChangedListeners = CopyOnWriteArraySet<OnConfigurationChangedListener>()
protected lateinit var windowInsetsControllerCompat: WindowInsetsControllerCompat
private set
override fun onAttachedToWindow() {
super.onAttachedToWindow()
TAG.logV("onAttachedToWindow()")
windowInsetsControllerCompat = WindowInsetsControllerCompat(window, window.decorView)
windowInsetsControllerCompat.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
TAG.logV("onRestoreInstanceState($savedInstanceState)")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
TAG.logV("onCreate($savedInstanceState)")
}
override fun onRestart() {
super.onRestart()
TAG.logV("onRestart()")
}
override fun onStart() {
super.onStart()
TAG.logV("onStart()")
}
override fun onResume() {
super.onResume()
TAG.logV("onResume()")
}
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
super.onTopResumedActivityChanged(isTopResumedActivity)
TAG.logV("onTopResumedActivityChanged($isTopResumedActivity)")
}
override fun onPause() {
super.onPause()
TAG.logV("onPause()")
}
override fun onStop() {
super.onStop()
TAG.logV("onStop()")
}
override fun onDestroy() {
super.onDestroy()
TAG.logV("onDestroy()")
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
TAG.logV("onSaveInstanceState(${outState})")
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
TAG.logV("onDetachedFromWindow()")
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
TAG.logV("onConfigurationChanged($newConfig)")
onConfigurationChangedListeners.forEach { it.onConfigurationChanged(newConfig) }
}
override fun addOnConfigurationChangedListener(listener: OnConfigurationChangedListener): Boolean =
onConfigurationChangedListeners.add(listener)
override fun removeOnConfigurationChangedListener(listener: OnConfigurationChangedListener): Boolean =
onConfigurationChangedListeners.remove(listener)
override fun clearOnConfigurationChangedListeners() {
onConfigurationChangedListeners.clear()
}
}
| 0 |
Java
|
0
| 1 |
d83533358962f966aecdab91cf42bea54496b9f7
| 3,258 |
Gadget
|
Apache License 2.0
|
app/src/main/java/com/cameronvwilliams/raise/ui/poker/views/adapter/PokerAdapter.kt
|
RaiseSoftware
| 119,627,507 | false | null |
package com.cameronvwilliams.raise.ui.poker.views.adapter
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.cameronvwilliams.raise.data.model.PokerGame
import com.cameronvwilliams.raise.ui.poker.views.PlayerCardFragment
import com.cameronvwilliams.raise.ui.poker.views.PokerCardFragment
class PokerAdapter(fm: FragmentManager, pokerGame: PokerGame) : FragmentPagerAdapter(fm) {
private var fragments: Array<Fragment>
init {
val pokerCardFragment = PokerCardFragment.newInstance()
val bundle = Bundle()
with(PokerCardFragment.BundleOptions) {
bundle.setDeckType(pokerGame.deckType!!)
}
pokerCardFragment.arguments = bundle
fragments = arrayOf(
pokerCardFragment,
PlayerCardFragment.newInstance()
)
}
override fun getItem(position: Int) = fragments[position]
override fun getCount(): Int = fragments.size
}
| 1 | null |
1
| 4 |
3cd0786dba77645efa5508a662478e5893037919
| 1,045 |
Raise-Android
|
MIT License
|
app/src/main/java/com/intermediate/storyapp/view/signup/SignupViewModel.kt
|
raflizocky
| 714,306,033 | false |
{"Kotlin": 83541}
|
package com.intermediate.storyapp.view.signup
import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import com.intermediate.storyapp.data.repository.UserRepository
import com.intermediate.storyapp.data.response.ErrorResponse
import com.intermediate.storyapp.data.response.RegisterResponse
import retrofit2.HttpException
class SignupViewModel(private val repository: UserRepository) : ViewModel() {
suspend fun register(name: String, email: String, password: String): RegisterResponse {
return try {
Log.d(
"SignupViewModel",
"Mengirim permintaan registrasi ke server"
) // Pesan log ini akan muncul saat permintaan registrasi dikirim.
val response = repository.register(name, email, password)
Log.d(
"SignupViewModel",
"Registrasi berhasil"
) // Pesan log ini akan muncul jika registrasi berhasil.
response
} catch (e: HttpException) {
Log.e(
"SignupViewModel",
"Registrasi gagal",
e
) // Pesan log ini akan muncul jika registrasi gagal.
val jsonInString = e.response()?.errorBody()?.string()
val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java)
Log.e("SignupViewModel", "Error response: $errorBody")
throw e
}
}
}
| 0 |
Kotlin
|
0
| 2 |
4f7984d710fad3bbf25eece9c46ccc22ec2b8d76
| 1,461 |
StoryApp
|
Apache License 2.0
|
geary-papermc-bridge/src/main/kotlin/com/mineinabyss/geary/papermc/configlang/systems/TriggerWhenTargetListener.kt
|
MineInAbyss
| 592,086,123 | false | null |
package com.mineinabyss.geary.papermc.configlang.systems
import com.mineinabyss.geary.annotations.Handler
import com.mineinabyss.geary.papermc.commons.events.configurable.components.TriggerWhenTarget
import com.mineinabyss.geary.papermc.configlang.helpers.runFollowUp
import com.mineinabyss.geary.systems.GearyListener
import com.mineinabyss.geary.systems.accessors.EventScope
import com.mineinabyss.geary.systems.accessors.SourceScope
import com.mineinabyss.geary.systems.accessors.TargetScope
class TriggerWhenTargetListener : GearyListener() {
val TargetScope.trigger by getRelations<TriggerWhenTarget, Any?>()
@Handler
fun TargetScope.tryFollowUpEvents(event: EventScope, source: SourceScope) {
// If event has our trigger
if (trigger.target.id in event.entity.type) {
trigger.data.runEvents.runFollowUp(trigger.data.runAsSource, entity, source.entity)
}
}
}
| 0 |
Kotlin
|
0
| 1 |
0be838e5a3d922612de035529c270a0d6b3b7bf5
| 918 |
geary-papermc
|
MIT License
|
kotlin/goi/src/main/kotlin/net/paploo/goi/persistence/database/vocabulary/VocabularyDomainToRecordTransform.kt
|
paploo
| 526,415,165 | false |
{"Kotlin": 559165, "Ruby": 153592, "Java": 50673, "ANTLR": 2888, "CSS": 1961, "PLpgSQL": 274}
|
package net.paploo.goi.persistence.database.vocabulary
import net.paploo.goi.common.extensions.constCase
import net.paploo.goi.common.extensions.snakeCase
import net.paploo.goi.common.util.createUuidV5
import net.paploo.goi.domain.data.vocabulary.Vocabulary
import net.paploo.goi.persistence.db.goi.vocabulary.tables.records.*
import java.util.*
internal class VocabularyDomainToRecordTransform : (Vocabulary) -> Result<VocabularyRecordGroup> {
override fun invoke(vocab: Vocabulary): Result<VocabularyRecordGroup> = Result.runCatching {
buildRecordGroup(vocab)
}
private fun buildRecordGroup(vocab: Vocabulary): VocabularyRecordGroup =
VocabRecords(
vocabularyRecord = buildVocabularyRecord(vocab),
preferredDefinition = buildPreferredDefinition(vocab),
preferredSpelling = buildPreferredSpelling(vocab),
phoneticSpelling = buildPhoneticSpelling(vocab),
altPhoneticSpelling = buildAltPhoneticSpelling(vocab),
kanjiSpelling = buildKanjiSpelling(vocab),
references = buildReferences(vocab),
conjugationSet = buildConjugationSet(vocab),
conjugations = buildConjugations(vocab),
).toRecordGroup()
/**
* Intermediate grouping of records with their contextual information.
*
* This allows proper creation of a linkages record without making assumptions.
*/
private data class VocabRecords(
val vocabularyRecord: VocabularyRecord,
val preferredDefinition: DefinitionRecord,
val preferredSpelling: SpellingRecord,
val phoneticSpelling: SpellingRecord,
val altPhoneticSpelling: SpellingRecord?,
val kanjiSpelling: SpellingRecord?,
val references: List<ReferenceRecord>,
val conjugationSet: ConjugationSetRecord?,
val conjugations: List<ConjugationRecord>?,
) {
val linkages: LinkagesRecord = LinkagesRecord(
vocabularyId = vocabularyRecord.id,
preferredDefinitionId = preferredDefinition.id,
preferredSpellingId = preferredSpelling.id,
phoneticSpellingId = phoneticSpelling.id,
altPhoneticSpellingId = altPhoneticSpelling?.id,
kanjiSpellingId = kanjiSpelling?.id,
conjugationSetId = conjugationSet?.id
)
fun toRecordGroup(): VocabularyRecordGroup = VocabularyRecordGroup(
vocabularyRecord = vocabularyRecord,
linkagesRecord = linkages,
definitions = listOf(preferredDefinition),
spellings = listOfNotNull(preferredSpelling, phoneticSpelling, altPhoneticSpelling, kanjiSpelling),
references = references,
conjugationSet = conjugationSet,
conjugations = conjugations,
)
}
private fun buildvocabularyRecord(vocab: Vocabulary): VocabularyRecord =
VocabularyRecord(
id = vocab.id.value,
wordClassCode = vocab.wordClass.name.constCase(),
conjugationKindCode = vocab.conjugationKind?.name?.constCase(),
jlptLevel = vocab.jlptLevel?.levelNumber,
rowNum = vocab.rowNumber,
dateAdded = vocab.dateAdded,
tags = vocab.tags.sorted().map { it.value.snakeCase() }.toTypedArray(),
)
/*
* Note: The old Ruby Goi code generated the IDs using UUIDv5 from a selection of fields.
* It did this to ensure IDs were preserved across loads. We start with compatible
* ID generation.
*/
private fun buildVocabularyRecord(vocab: Vocabulary): VocabularyRecord =
VocabularyRecord(
id = vocab.id.value,
wordClassCode = vocab.wordClass.name.constCase(),
conjugationKindCode = vocab.conjugationKind?.name?.constCase(),
jlptLevel = vocab.jlptLevel?.levelNumber,
rowNum = vocab.rowNumber,
dateAdded = vocab.dateAdded,
tags = vocab.tags.map { it.value.snakeCase() }.toTypedArray()
)
private val definitionIdNamespace: UUID = UUID.fromString("c7812647-678a-4bf5-bed3-b33fe499469c")
private fun buildPreferredDefinition(vocab: Vocabulary): DefinitionRecord =
vocab.preferredDefinition.let {
DefinitionRecord(
id = listOf(
vocab.id.value.toString(),
"preferred_definition"
).createUuidV5(definitionIdNamespace),
vocabularyId = vocab.id.value,
sortRank = 1, //Preferred definition is always rank one, other definitions (if added later) fall below it.
value = it.value
)
}
private val spellingIdNamespace: UUID = UUID.fromString("546a4b2c-6b83-4fe9-902e-7c7ade990930")
private fun buildPreferredSpelling(vocab: Vocabulary): SpellingRecord =
vocab.preferredWritten.preferredSpelling.let {
SpellingRecord(
id = listOf(
vocab.id.value.toString(),
"preferred_spelling"
).createUuidV5(spellingIdNamespace),
vocabularyId = vocab.id.value,
spellingKindCode = it.kind.name.constCase(),
value = it.value,
)
}
private fun buildPhoneticSpelling(vocab: Vocabulary): SpellingRecord =
vocab.preferredWritten.phoneticSpelling?.let {
SpellingRecord(
id = listOf(
vocab.id.value.toString(),
"phonetic_spelling"
).createUuidV5(spellingIdNamespace),
vocabularyId = vocab.id.value,
spellingKindCode = it.kind.name.constCase(),
value = it.value,
)
} ?: throw IllegalArgumentException("Expected phonetic spelling for preferredWritten = ${vocab.preferredWritten} on vocabulary ${vocab.id}")
private fun buildAltPhoneticSpelling(vocab: Vocabulary): SpellingRecord? =
vocab.altPhoneticSpelling?.let {
SpellingRecord(
id = listOf(
vocab.id.value.toString(),
"alt_phon_spell" //Copy the typo from Goi Ruby to match its output. TODO: once its deprecated, fix this.
).createUuidV5(spellingIdNamespace),
vocabularyId = vocab.id.value,
spellingKindCode = it.kind.name.constCase(),
value = it.value,
)
}
private fun buildKanjiSpelling(vocab: Vocabulary): SpellingRecord? =
vocab.kanjiSpelling?.let {
SpellingRecord(
id = listOf(
vocab.id.value.toString(),
"kanji_spelling"
).createUuidV5(spellingIdNamespace),
vocabularyId = vocab.id.value,
spellingKindCode = it.kind.name.constCase(),
value = it.value,
)
}
private fun buildReferences(vocab: Vocabulary): List<ReferenceRecord> =
vocab.references.map {
ReferenceRecord(
vocabularyId = vocab.id.value,
lessonCode = it.value.constCase()
)
}
private fun buildConjugationSet(vocab: Vocabulary): ConjugationSetRecord? =
vocab.conjugations?.let {
//Due to the constraints on Vocabulary, we can assume that it will only be non-null if it is conjugable.
//Note that this will produce an empty conjugation set if conjugable but has no conjugations. This seems correct.
ConjugationSetRecord(
id = createConjugationSetId(vocab.id),
vocabularyId = vocab.id.value
)
}
private fun buildConjugations(vocab: Vocabulary): List<ConjugationRecord>? =
vocab.conjugations?.groupBy { it.inflection }?.flatMap { (inflection, conjugations) ->
conjugations.mapIndexed { index, conjugation ->
val sortRank = index + 1
ConjugationRecord(
id = listOf(
createConjugationSetId(vocab.id).toString(),
conjugation.inflection.politeness.name.constCase(),
conjugation.inflection.charge.name.constCase(),
conjugation.inflection.form.name.constCase(),
sortRank.toString()
).createUuidV5(UUID.fromString("a55893fe-f4fd-4e84-a9f0-6a6d6495b53b")),
conjugationSetId = createConjugationSetId(vocab.id),
politenessCode = conjugation.inflection.politeness.name.constCase(),
chargeCode = conjugation.inflection.charge.name.constCase(),
formCode = conjugation.inflection.form.name.constCase(),
sortRank = sortRank,
value = conjugation.value
)
}
}
private fun createConjugationSetId(vocabularyId: Vocabulary.Id): UUID =
listOf(vocabularyId.value.toString()).createUuidV5(UUID.fromString("8724ca34-1e4a-4e78-8474-b359cdf33b66"))
}
| 3 |
Kotlin
|
0
| 0 |
8edef8afa574097d66b2a4f89d75d1e4c69bd219
| 9,162 |
goi
|
MIT License
|
image-loader/src/jvmMain/kotlin/com/seiko/imageloader/Bitmap.jvm.kt
|
qdsfdhvh
| 502,954,331 | false | null |
package com.seiko.imageloader
internal actual inline val Bitmap.identityHashCode: Int
get() = System.identityHashCode(this)
| 8 |
Kotlin
|
4
| 90 |
d9c86b3bb21817f1c0d2517dc2bebcd7ebf8642a
| 129 |
compose-imageloader
|
MIT License
|
app/src/main/java/com/gauvain/seigneur/theofficequote/view/favQuotes/FavQuotesViewModel.kt
|
GauvainSeigneur
| 264,162,160 | false | null |
package com.gauvain.seigneur.theofficequote.view.favQuotes
import androidx.lifecycle.*
import androidx.paging.DataSource
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import com.gauvain.seigneur.data_adapter.adapter.GetTokenAdapter
import com.gauvain.seigneur.data_adapter.database.TheOfficequoteDataBase
import com.gauvain.seigneur.data_adapter.model.QuoteItemEntity
import com.gauvain.seigneur.domain.usecase.GetUserFavoriteQuotesUseCase
import com.gauvain.seigneur.domain.usecase.InsertQuoteUseCase
import com.gauvain.seigneur.theofficequote.model.*
import com.gauvain.seigneur.theofficequote.utils.event.Event
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
typealias DisplayDetailsEventState = Event<LiveDataState<QuoteDetailsData>>
typealias InitialLoadingState = LiveDataState<LoadingState>
class FavQuotesViewModel(
private val useCase: GetUserFavoriteQuotesUseCase,
private val insertQuoteUseCase: InsertQuoteUseCase,
private val dataBase: TheOfficequoteDataBase
) : ViewModel(), CoroutineScope {
companion object {
const val PAGE_SIZE = 25
}
private val config = PagedList.Config.Builder()
.setPageSize(PAGE_SIZE)
.setEnablePlaceholders(false)
.build()
private var isLastRequestConnected = true
var quoteDetailsModelList = mutableListOf<QuoteDetailsData>()
var quoteList: LiveData<PagedList<QuoteItemData>>? = null
// ...because this is what we'll want to expose
val initialLoadingState = MediatorLiveData<InitialLoadingState>()
val displayDetailsEvent = MutableLiveData<DisplayDetailsEventState>()
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
fun resetList() {
quoteList?.value?.dataSource?.invalidate()
}
fun getFavQuotes(isConnected: Boolean) {
quoteDetailsModelList.clear()
if (isConnected) {
getOnLineList()
} else {
getOffLineList()
}
}
fun getQuotesDetails(id: Int) {
val item = quoteDetailsModelList.firstOrNull { it.id == id }
item?.let {
displayDetailsEvent.value = Event(LiveDataState.Success(it))
} ?: handleNoDetailsItemFound()
}
private fun handleNoDetailsItemFound() {
displayDetailsEvent.value = Event(LiveDataState.Error(ErrorData(ErrorDataType.INFORMATIVE)))
}
private fun getOnLineList() {
isLastRequestConnected = true
val dataSourceFactory = QuoteDataSourceFactory(
GetTokenAdapter.constUserName,
viewModelScope,
useCase,
insertQuoteUseCase
)
quoteList = LivePagedListBuilder<Int, QuoteItemData>(dataSourceFactory.map {
quoteDetailsModelList.add(it.toDetailsData())
it.toData()
}, config).build()
val initialLoadingData =
Transformations.switchMap(dataSourceFactory.quoteDataSourceLiveData) {
it.initialLoadingData
}
val initialErrorData = Transformations.switchMap(dataSourceFactory.quoteDataSourceLiveData)
{ it.initialError }
initialLoadingState
.addSource(initialErrorData) { result: ErrorData ->
result.let {
initialLoadingState.value = LiveDataState.Error(result)
}
}
initialLoadingState.addSource(initialLoadingData) {
initialLoadingState.value = LiveDataState.Success(it)
}
}
private fun getOffLineList() {
isLastRequestConnected = false
val offLineFactory: DataSource.Factory<Int, QuoteItemEntity> = dataBase.quoteDao()
.getAllPagedItem()
quoteList = LivePagedListBuilder<Int, QuoteItemData>(
offLineFactory.map {
quoteDetailsModelList.add(it.toDetailsData())
it.toData()
},
config
).build()
}
override fun onCleared() {
job.cancel()
}
}
| 0 |
Kotlin
|
0
| 0 |
d44a86973c242473fd27ddd0845d12a43fe91fe5
| 4,069 |
TheOfficeQuote
|
Apache License 2.0
|
core/remote/src/main/kotlin/com/alexeymerov/radiostations/core/remote/di/NetworkModule.kt
|
AlexeyMerov
| 636,705,016 | false | null |
package com.alexeymerov.radiostations.core.remote.di
import com.alexeymerov.radiostations.core.common.BuildConfig
import com.alexeymerov.radiostations.core.remote.client.NetworkDefaults
import com.alexeymerov.radiostations.core.remote.interceptor.JsonResponseInterceptor
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Converter
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Provides
@Singleton
fun provideJsonAdapterFactory(): JsonAdapter.Factory = NetworkDefaults.getJsonAdapterFactory()
@Provides
@Singleton
fun provideMoshi(factory: JsonAdapter.Factory): Moshi = NetworkDefaults.getMoshi(factory)
@Provides
@Singleton
fun provideConverterFactory(moshi: Moshi): Converter.Factory = NetworkDefaults.getConverterFactory(moshi)
@Provides
@Singleton
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
}
@Provides
@Singleton
fun provideForceJsonInterceptor(): JsonResponseInterceptor = NetworkDefaults.getForceJsonInterceptor()
@Provides
@Singleton
fun provideOkHttpClient(jsonResponseInterceptor: JsonResponseInterceptor, loggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
return NetworkDefaults.getOkHttpClient(interceptors = arrayOf(jsonResponseInterceptor, loggingInterceptor))
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient, converterFactory: Converter.Factory): Retrofit {
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(converterFactory)
.build()
}
}
| 0 | null |
0
| 2 |
469f3de3f15e2ce6120b785885c9270369a94bb9
| 2,081 |
RadioStations
|
MIT License
|
app/src/androidTest/java/com/fahim/example_employee_app/EmployeeDatabaseTest.kt
|
fahim44
| 217,901,596 | false | null |
package com.fahim.example_employee_app
import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.paging.Config
import androidx.paging.toLiveData
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.fahim.example_employee_app.model.Employee
import com.fahim.example_employee_app.db.EmployeeDao
import com.fahim.example_employee_app.db.EmployeeDatabase
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import java.io.IOException
@RunWith(AndroidJUnit4::class)
class EmployeeDatabaseTest {
@get:Rule val testRule = InstantTaskExecutorRule()
private lateinit var dao : EmployeeDao
private lateinit var db : EmployeeDatabase
@Before
fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(context,EmployeeDatabase::class.java)
.build()
dao = db.employeeDao()
}
@After
@Throws(IOException::class)
fun tearDown(){
db.close()
}
@Test
@Throws(Exception::class)
fun insertData(){ //insert and get data test
val expected = Employee(1,"fahim",100000.99f,21,5.0f)
val id = dao.insert(expected)
val actual = TestUtils.getValue(dao.getEmployee(id[0].toInt()))
assertEquals(expected.name, actual.name)
assertEquals(expected.id, actual.id)
assertEquals(expected.salary,actual.salary)
assertEquals(expected.rating,actual.rating)
assertEquals(expected.age,actual.age)
}
@Test
fun insertMultipleData(){
val expected1 = Employee(1,"fahim",100000.99f,21,5.0f)
val expected2 = Employee(2,"rahul",10.93f,35,0.23f)
val expected3 = Employee(3,"piash",1000.65f,10,3.4f)
dao.insert(expected3,expected1,expected2)
val actualList = TestUtils.getValue(dao.getAllEmployees().toLiveData(Config(pageSize = 30,enablePlaceholders = false,maxSize = 1000)))
assertEquals(3,actualList.size)
assertEquals(expected1.name, actualList[0]?.name)
assertEquals(expected1.id, actualList[0]?.id)
assertEquals(expected1.salary,actualList[0]?.salary)
assertEquals(expected1.rating,actualList[0]?.rating)
assertEquals(expected1.age,actualList[0]?.age)
assertEquals(expected2.name, actualList[1]?.name)
assertEquals(expected2.id, actualList[1]?.id)
assertEquals(expected2.salary,actualList[1]?.salary)
assertEquals(expected2.rating,actualList[1]?.rating)
assertEquals(expected2.age,actualList[1]?.age)
assertEquals(expected3.name, actualList[2]?.name)
assertEquals(expected3.id, actualList[2]?.id)
assertEquals(expected3.salary,actualList[2]?.salary)
assertEquals(expected3.rating,actualList[2]?.rating)
assertEquals(expected3.age,actualList[2]?.age)
}
@Test
@Throws(Exception::class)
fun updateData(){
val expected = Employee(1,"fahim",100000.99f,21,5.0f)
val id = dao.insert(expected)
expected.rating = 0.3f
expected.name = "salam"
expected.age = 27
expected.id = 44
expected.salary = 223355.887f
expected .uid = id[0].toInt()
dao.update(expected)
val actual = TestUtils.getValue(dao.getEmployee(id[0].toInt()))
assertEquals(expected.name, actual.name)
assertEquals(expected.id, actual.id)
assertEquals(expected.salary,actual.salary)
assertEquals(expected.rating,actual.rating)
assertEquals(expected.age,actual.age)
}
@Test
@Throws(Exception::class)
fun deleteData(){
val expected = Employee(1,"fahim",100000.99f,21,5.0f)
val id = dao.insert(expected)
expected.uid = id[0].toInt()
dao.delete(expected)
val actual = TestUtils.getValue(dao.getEmployee(id[0].toInt()))
assertNull(actual)
}
@Test
fun updateRating(){
val insertedValue = Employee(1,"fahim",100000.99f,21,5.0f)
val id = dao.insert(insertedValue)
val rating = 2.01f
dao.updateRating(id[0].toInt(),rating)
val actual = TestUtils.getValue(dao.getEmployee(id[0].toInt()))
assertNotEquals(insertedValue.rating,actual.rating)
assertEquals(rating,actual.rating)
}
@Test
fun getAllData(){
val expected1 = Employee(1,"fahim",100000.99f,21,5.0f)
val id1 = dao.insert(expected1)
expected1.uid = id1[0].toInt()
val expected2 = Employee(2,"rahul",10.93f,35,0.23f)
val id2 = dao.insert(expected2)
expected2.uid = id2[0].toInt()
val expected3 = Employee(3,"piash",1000.65f,10,3.4f)
val id3 = dao.insert(expected3)
expected3.uid = id3[0].toInt()
val actualList = TestUtils.getValue(dao.getAllEmployees().toLiveData(Config(pageSize = 30,enablePlaceholders = false,maxSize = 1000)))
assertEquals(3,actualList.size)
assertEquals(expected1.uid, actualList[0]?.uid)
assertEquals(expected1.name, actualList[0]?.name)
assertEquals(expected1.id, actualList[0]?.id)
assertEquals(expected1.salary,actualList[0]?.salary)
assertEquals(expected1.rating,actualList[0]?.rating)
assertEquals(expected1.age,actualList[0]?.age)
assertEquals(expected2.uid, actualList[1]?.uid)
assertEquals(expected2.name, actualList[1]?.name)
assertEquals(expected2.id, actualList[1]?.id)
assertEquals(expected2.salary,actualList[1]?.salary)
assertEquals(expected2.rating,actualList[1]?.rating)
assertEquals(expected2.age,actualList[1]?.age)
assertEquals(expected3.uid, actualList[2]?.uid)
assertEquals(expected3.name, actualList[2]?.name)
assertEquals(expected3.id, actualList[2]?.id)
assertEquals(expected3.salary,actualList[2]?.salary)
assertEquals(expected3.rating,actualList[2]?.rating)
assertEquals(expected3.age,actualList[2]?.age)
}
@Test
fun getSearchedData(){
val expected1 = Employee(1,"abcd",100000.99f,21,2.4f)
val id1 = dao.insert(expected1)
expected1.uid = id1[0].toInt()
val expected2 = Employee(2,"bcf",10.93f,35,4.3f)
val id2 = dao.insert(expected2)
expected2.uid = id2[0].toInt()
val expected3 = Employee(3,"abeeeec",1000.65f,10,5.0f)
val id3 = dao.insert(expected3)
expected3.uid = id3[0].toInt()
val actualList = TestUtils.getValue(dao.employeesSortByName("%bc%").toLiveData(Config(pageSize = 30,enablePlaceholders = false,maxSize = 1000)))
assertEquals(2,actualList.size)
assertFalse(actualList.contains(expected3))
assertTrue(actualList.contains(expected1))
assertTrue(actualList.contains(expected2))
assertEquals(expected2.uid, actualList[0]?.uid)
assertEquals(expected2.name, actualList[0]?.name)
assertEquals(expected2.id, actualList[0]?.id)
assertEquals(expected2.salary,actualList[0]?.salary)
assertEquals(expected2.rating,actualList[0]?.rating)
assertEquals(expected2.age,actualList[0]?.age)
assertEquals(expected1.uid, actualList[1]?.uid)
assertEquals(expected1.name, actualList[1]?.name)
assertEquals(expected1.id, actualList[1]?.id)
assertEquals(expected1.salary,actualList[1]?.salary)
assertEquals(expected1.rating,actualList[1]?.rating)
assertEquals(expected1.age,actualList[1]?.age)
}
}
| 0 |
Kotlin
|
1
| 2 |
003de32135692f8006313f59c8d01dba0c4f63ce
| 7,709 |
Example-Employee-App
|
MIT License
|
storage-service/src/main/kotlin/com/vnapnic/storage/repositories/AccountRepository.kt
|
alphaNumericEntity
| 763,513,563 | false |
{"Kotlin": 397164, "Java": 8775, "HTML": 6673, "Dockerfile": 224}
|
package com.vnapnic.storage.repositories
import com.vnapnic.common.db.Account
import com.vnapnic.common.db.Device
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
@Repository
interface AccountRepository : MongoRepository<Account, String>
| 0 |
Kotlin
|
0
| 0 |
495581ca09d1c4a03e2643ce8601886009b39665
| 306 |
kotlin-spring-boot-microservices
|
Apache License 2.0
|
verik-compiler/src/main/kotlin/io/verik/compiler/serialize/source/SerializerUtil.kt
|
frwang96
| 269,980,078 | false | null |
/*
* Copyright (c) 2021 <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 io.verik.compiler.serialize.source
import io.verik.compiler.ast.element.common.EElement
import io.verik.compiler.ast.element.declaration.common.EEnumEntry
import io.verik.compiler.ast.element.declaration.sv.EClockingBlock
import io.verik.compiler.ast.element.declaration.sv.EModulePort
object SerializerUtil {
fun declarationIsHidden(element: EElement): Boolean {
return element is EModulePort ||
element is EClockingBlock ||
element is EEnumEntry
}
}
| 0 | null |
1
| 7 |
a40d6195f3b57bebac813b3e5be59d17183433c7
| 1,099 |
verik
|
Apache License 2.0
|
src/test/kotlin/cn/edu/cug/cs/gtl/series/SeriesTest.kt
|
longshirong
| 273,202,203 | true |
{"Maven POM": 1, "Java Properties": 2, "Markdown": 1, "Text": 1, "XML": 1, "Ignore List": 1, "Kotlin": 11, "Java": 58}
|
package cn.edu.cug.cs.gtl.series
import cn.edu.cug.cs.gtl.common.Pair
import cn.edu.cug.cs.gtl.config.Config
import cn.edu.cug.cs.gtl.io.File
import cn.edu.cug.cs.gtl.series.common.Series
import cn.edu.cug.cs.gtl.series.common.SeriesBuilder
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.*
class SeriesTest {
var testFileName:String =""
@Before
fun setUp() {
Config.setConfigFile("series.properties")
testFileName = (Config.getTestOutputDirectory()
+ File.separator + "test.series")
}
@Test
fun copy() {
val ys = doubleArrayOf(50.0, 10.0, 20.0, 30.0, 40.0, 70.0, 90.0, 10.0, 30.0, 40.0)
val s1 = SeriesBuilder.build("test","value",ys, Pair("label","1"))
try {
val f = FileOutputStream(testFileName)
s1.write(f)
f.close()
val f2 = FileInputStream(testFileName)
val s3 = SeriesBuilder.parseFrom(f2)
Assert.assertArrayEquals(ys, s3.values, 0.001)
} catch (e: IOException) {
e.printStackTrace()
}
}
@Test
fun load() {
val ys = doubleArrayOf(50.0, 10.0, 20.0, 30.0, 40.0, 70.0, 90.0, 10.0, 30.0, 40.0)
val s1 = SeriesBuilder.build("test","value",ys, Pair("label","1"))
try {
val baos = ByteArrayOutputStream()
s1.write(baos)
val bytes = baos.toByteArray()
baos.close()
val bais = ByteArrayInputStream(bytes)
val s3 = SeriesBuilder.parseFrom(bais)
Assert.assertArrayEquals(ys, s3.values, 0.001)
} catch (e: IOException) {
e.printStackTrace()
}
}
@Test
fun store() {
val ys = doubleArrayOf(50.0, 10.0, 20.0, 30.0, 40.0, 70.0, 90.0, 10.0, 30.0, 40.0)
val s1 = SeriesBuilder.build("test","value",ys, Pair("label","1"))
try {
val bytes = s1.storeToByteArray()
val s3 = SeriesBuilder.parseFrom(bytes)
Assert.assertArrayEquals(ys, s3.values, 0.001)
} catch (e: IOException) {
e.printStackTrace()
}
}
companion object {
}
}
| 0 | null |
0
| 0 |
9eb2a0ce951f69fb5a728ba1a4d896f936c0280e
| 2,195 |
series
|
Apache License 2.0
|
app/src/main/java/com/org/capstone/nutrifish/ui/customview/EmailEditText.kt
|
RexRama
| 806,637,314 | false |
{"Kotlin": 108231}
|
package com.org.capstone.nutrifish.ui.customview
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import com.google.android.material.textfield.TextInputEditText
import com.org.capstone.nutrifish.R
class EmailEditText : TextInputEditText {
constructor(context: Context) : super(context) {
setup()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setup()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
setup()
}
private fun setup() {
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
validateEmail(s.toString())
}
})
}
private fun validateEmail(email: String) {
val pattern = Regex("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+")
val isValid = pattern.matches(email)
if (!isValid) showError() else removeError()
}
private fun removeError() {
this.error = null
}
private fun showError() {
this.error = context.getString(R.string.invalid_email)
}
}
| 0 |
Kotlin
|
1
| 0 |
cdfefcceb1d74858f4bf02a6f2762f0822645362
| 1,486 |
Nutrifish-C241-PS164
|
MIT License
|
app/src/main/java/com/gerasimosGk/kotlinmvvmsample/presentation/base/BaseActivity.kt
|
GerasimosGots
| 582,719,293 | false |
{"Kotlin": 58244}
|
package com.gerasimosGk.kotlinmvvmsample.presentation.base
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.navigation.fragment.NavHostFragment
import androidx.viewbinding.ViewBinding
import com.gerasimosGk.kotlinmvvmsample.R
abstract class BaseActivity<B : ViewBinding> : AppCompatActivity() {
var binding: B? = null
abstract fun getActivityBinding(inflater: LayoutInflater): B
abstract fun onViewCreated()
abstract fun setObservers()
abstract fun getNavHostFragment(): NavHostFragment
protected val navController by lazy {
getNavHostFragment().navController
}
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.Theme_KotlinMvvmSample)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
super.onCreate(savedInstanceState)
binding = getActivityBinding(layoutInflater)
setContentView(binding?.root)
onViewCreated()
setObservers()
}
override fun onDestroy() {
super.onDestroy()
binding = null
}
}
| 0 |
Kotlin
|
0
| 0 |
cb6e5779f09d8553d18642ca98b1bed5463592c5
| 1,191 |
KotlinMVVMSample
|
Apache License 2.0
|
app/src/main/java/com/quizapp/core/ui/component/CircleCheckbox.kt
|
AhmetOcak
| 591,704,302 | false | null |
package com.quizapp.core.ui.component
import androidx.compose.foundation.background
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import com.quizapp.R
@Composable
fun CircleCheckbox(
modifier: Modifier,
onChecked: () -> Unit,
selected: Boolean = false,
tint: Color = if (selected) MaterialTheme.colors.secondary else MaterialTheme.colors.primaryVariant
) {
val imageVector = if (selected) R.drawable.ic_baseline_check_circle else R.drawable.ic_outline_circle_24
val background = if (selected) MaterialTheme.colors.background else Color.Transparent
IconButton(onClick = onChecked) {
Icon(
modifier = modifier.background(color = background, shape = CircleShape),
painter = painterResource(id = imageVector),
contentDescription = null,
tint = tint
)
}
}
| 0 |
Kotlin
|
0
| 5 |
cc9d467fcd37cc88c9bbac315bd9aae920722bac
| 1,154 |
QuizApp
|
MIT License
|
app/src/main/java/com/karna/mycards/data/data_source/CardDao.kt
|
karnasurendra
| 794,693,409 | false |
{"Kotlin": 85804}
|
package com.karna.mycards.data.data_source
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.karna.mycards.domain.model.Card
import kotlinx.coroutines.flow.Flow
@Dao
interface CardDao {
@Query("SELECT * FROM card")
fun getCards(): Flow<List<Card>>
@Query("SELECT * FROM card WHERE id = :id")
suspend fun getCardById(id: Int): Card?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCard(card: Card)
@Delete
suspend fun deleteCard(card: Card)
}
| 0 |
Kotlin
|
0
| 1 |
4f5af198217c5c09e5c3728144de028da6025072
| 608 |
Android-Compose-MVVM-MyCards
|
MIT License
|
applications/examples/sandbox-app/example-cpi/src/main/kotlin/com/example/cpk/crypto/TripleSHA256.kt
|
corda
| 346,070,752 | false |
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
|
package com.example.cpk.crypto
import net.corda.v5.crypto.DigestAlgorithmName
import java.io.InputStream
import java.security.MessageDigest
import net.corda.v5.crypto.DigestAlgorithmName.SHA2_256
import net.corda.v5.crypto.extensions.DigestAlgorithm
import net.corda.v5.crypto.extensions.DigestAlgorithmFactory
@Suppress("unused")
class TripleSHA256 : DigestAlgorithmFactory {
override fun getAlgorithm() = TripleSHA256Digest.ALGORITHM
override fun getInstance(): DigestAlgorithm = TripleSHA256Digest()
}
private class TripleSHA256Digest : DigestAlgorithm {
companion object {
const val ALGORITHM = "SHA-256-TRIPLE"
}
override fun getAlgorithm() = ALGORITHM
override fun getDigestLength() = 32
override fun digest(bytes: ByteArray): ByteArray = bytes.sha256Bytes().sha256Bytes().sha256Bytes()
override fun digest(inputStream: InputStream): ByteArray {
val messageDigest = MessageDigest.getInstance(SHA2_256.name)
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val bytesRead = inputStream.read(buffer)
if (bytesRead < 0) {
break
}
messageDigest.update(buffer, 0, bytesRead)
}
return messageDigest.digest().sha256Bytes().sha256Bytes()
}
}
private fun messageDigestSha256(): MessageDigest =
MessageDigest.getInstance(DigestAlgorithmName.SHA2_256.name)
fun ByteArray.sha256Bytes(): ByteArray = messageDigestSha256().digest(this)
| 14 |
Kotlin
|
27
| 69 |
0766222eb6284c01ba321633e12b70f1a93ca04e
| 1,497 |
corda-runtime-os
|
Apache License 2.0
|
ios/repository/background/src/commonMain/kotlin/com/oztechan/ccc/ios/repository/background/BackgroundRepository.kt
|
Oztechan
| 102,633,334 | false |
{"Kotlin": 569897, "Swift": 92548, "Ruby": 5756, "HTML": 526}
|
package com.oztechan.ccc.ios.repository.background
interface BackgroundRepository {
fun shouldSendNotification(): Boolean
}
| 20 |
Kotlin
|
30
| 331 |
b245b00b507f29102beb18640e65cefd6e8666fb
| 129 |
CCC
|
Apache License 2.0
|
s5-database-relationship/final-project/app/src/main/java/com/droidcon/easyinvoice/ui/home/invoices/detail/InvoiceDetail.kt
|
droidcon-academy
| 557,290,152 | false |
{"Kotlin": 1511048}
|
package com.droidcon.easyinvoice.ui.home.invoices.detail
import android.content.res.Configuration
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.droidcon.easyinvoice.ui.theme.AppTheme
import com.droidcon.easyinvoice.ui.theme.spacing
import com.droidcon.easyinvoice.R
import com.droidcon.easyinvoice.data.utils.toDateTime
import com.droidcon.easyinvoice.ui.faker.FakeViewModelProvider
import com.droidcon.easyinvoice.ui.home.invoices.InvoiceViewModel
import com.droidcon.easyinvoice.ui.utils.toStringOrEmpty
@Composable
fun InvoiceDetail(viewModel: InvoiceViewModel, navController: NavController) {
val spacing = MaterialTheme.spacing
val invoice = viewModel.currentInvoice.collectAsState()
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(spacing.medium)
) {
Text(
text = invoice.value?.business?.name.toStringOrEmpty(),
style = MaterialTheme.typography.displaySmall,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = invoice.value?.business?.address.toStringOrEmpty(),
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Divider(modifier = Modifier.padding(top = spacing.medium))
Text(
text = stringResource(id = R.string.invoice),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Divider(modifier = Modifier.padding(bottom = spacing.medium))
Row(
modifier = Modifier.padding(bottom = spacing.medium)
) {
Column(
modifier = Modifier.weight(0.6f)
) {
Text(
text = stringResource(id = R.string.to),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.fillMaxWidth()
)
Text(
text = invoice.value?.customer?.name.toStringOrEmpty(),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.fillMaxWidth()
)
Text(
text = invoice.value?.customer?.address.toStringOrEmpty(),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.fillMaxWidth()
)
}
Column(
modifier = Modifier.weight(0.4f)
) {
Text(
text = stringResource(id = R.string.date),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.End,
modifier = Modifier.fillMaxWidth()
)
Text(
text = invoice.value?.invoice?.created_at.toDateTime(),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.End,
modifier = Modifier.fillMaxWidth()
)
}
}
Row {
TableCell(text = stringResource(id = R.string.particulars), heading = true, weight = 0.45f)
TableCell(text = stringResource(id = R.string.qty), alignment = TextAlign.End, heading = true, weight = 0.15f)
TableCell(text = stringResource(id = R.string.price), alignment = TextAlign.End, heading = true, weight = 0.2f)
TableCell(text = stringResource(id = R.string.amount), alignment = TextAlign.End, heading = true, weight = 0.2f)
}
invoice.value?.items?.forEach { item ->
Row {
TableCell(text = item.desc, weight = 0.45f)
TableCell(text = item.qty.toString(), alignment = TextAlign.End, weight = 0.15f)
TableCell(text = item.price.toString(), alignment = TextAlign.End, weight = 0.2f)
TableCell(text = item.amount.toString(), alignment = TextAlign.End, weight = 0.2f)
}
}
Row {
TableCell(text = stringResource(id = R.string.total_amount), heading = true, alignment = TextAlign.End, weight = 0.8f)
TableCell(text = invoice.value?.totalAmount.toString(), alignment = TextAlign.End, weight = 0.2f)
}
Row {
TableCell(text = invoice.value?.tax?.taxLabel.toStringOrEmpty(), heading = true, alignment = TextAlign.End, weight = 0.8f)
TableCell(text = invoice.value?.taxAmount.toString(), alignment = TextAlign.End, weight = 0.2f)
}
Row {
TableCell(text = stringResource(id = R.string.invoice_amount), heading = true, alignment = TextAlign.End, weight = 0.8f)
TableCell(text = invoice.value?.invoiceAmount.toString(), alignment = TextAlign.End, weight = 0.2f)
}
}
}
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Composable
fun InvoiceDetailPreviewLight() {
AppTheme {
InvoiceDetail(FakeViewModelProvider.provideInvoiceViewModel(), rememberNavController())
}
}
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun InvoiceDetailPreviewDark() {
AppTheme {
InvoiceDetail(FakeViewModelProvider.provideInvoiceViewModel(), rememberNavController())
}
}
| 0 |
Kotlin
|
1
| 0 |
2477b9978d7497c80e4d35288ac0bc4e36b96d0e
| 6,612 |
android-room-database-course-materials
|
Apache License 2.0
|
src/main/java/com/vortexa/refinery/result/Metadata.kt
|
VorTECHsa
| 423,415,893 | false |
{"Kotlin": 171148}
|
package com.vortexa.refinery.result
class Metadata(private val data: Map<String, Any>) {
private var divider: String? = null
fun getDivider(): String? {
return divider
}
fun setDivider(value: String) {
this.divider = value
}
fun getWorkbookName(): String {
return data[WORKBOOK_NAME]!! as String
}
fun getSheetName(): String {
return data[SPREADSHEET_NAME]!! as String
}
fun getAnchor(): String {
return data[ANCHOR]!! as String
}
operator fun plus(element: Pair<String, Any>): Metadata {
return Metadata(this.data + mapOf(element))
}
operator fun get(key: String): Any = this.data[key]!!
fun allData(): Map<String, Any> {
return if (divider == null) {
data
} else {
data + (DIVIDER to divider!!)
}
}
companion object {
const val WORKBOOK_NAME = "workbook_name"
const val SPREADSHEET_NAME = "spreadsheet_name"
const val ANCHOR = "anchor"
const val DIVIDER = "divider"
const val ROW_NUMBER = "row_number"
}
}
| 3 |
Kotlin
|
5
| 40 |
d5a95c52ffff9a1be350ef62de6746c8648e56aa
| 1,127 |
refinery
|
MIT License
|
src/main/java/th/weixia/sakuya/http/HttpUtil.kt
|
NatsumeWeiXia
| 147,758,160 | false | null |
package th.weixia.sakuya.http
import java.net.URL
import kotlin.text.Charsets.UTF_8
/***
*
* 网络接口
*
* @author SongYang
*
* @date 2018-8-23
*
*/
fun get(url: String): String {
return URL(url).readText(charset = UTF_8)
}
| 0 |
Kotlin
|
0
| 0 |
b703fac2554be1bb09d842a0f3137167d4cdfbb4
| 238 |
SakuyaWork_Ant2Mvn
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/com/chattriggers/ctjs/api/world/block/BlockPos.kt
|
ChatTriggers
| 635,543,231 | false |
{"Kotlin": 680597, "JavaScript": 62357, "Java": 58105}
|
package com.chattriggers.ctjs.api.world.block
import com.chattriggers.ctjs.api.CTWrapper
import com.chattriggers.ctjs.api.entity.Entity
import com.chattriggers.ctjs.api.vec.Vec3i
import com.chattriggers.ctjs.MCBlockPos
import net.minecraft.util.math.Vec3d
import kotlin.math.floor
import kotlin.math.sqrt
class BlockPos(x: Int, y: Int, z: Int) : Vec3i(x, y, z), CTWrapper<MCBlockPos> {
override val mcValue = MCBlockPos(x, y, z)
constructor(x: Number, y: Number, z: Number) : this(
floor(x.toDouble()).toInt(),
floor(y.toDouble()).toInt(),
floor(z.toDouble()).toInt()
)
constructor(pos: Vec3i) : this(pos.x, pos.y, pos.z)
constructor(pos: MCBlockPos) : this(pos.x, pos.y, pos.z)
constructor(source: Entity) : this(source.getPos())
override fun translated(dx: Int, dy: Int, dz: Int) = BlockPos(super.translated(dx, dy, dz))
override fun scaled(scale: Int) = BlockPos(super.scaled(scale))
override fun scaled(xScale: Int, yScale: Int, zScale: Int) = BlockPos(super.scaled(xScale, yScale, zScale))
override fun crossProduct(other: Vec3i) = BlockPos(super.crossProduct(other))
override operator fun unaryMinus() = BlockPos(super.unaryMinus())
override operator fun plus(other: Vec3i) = BlockPos(super.plus(other))
override operator fun minus(other: Vec3i) = BlockPos(super.minus(other))
@JvmOverloads
fun up(n: Int = 1) = offset(BlockFace.UP, n)
@JvmOverloads
fun down(n: Int = 1) = offset(BlockFace.DOWN, n)
@JvmOverloads
fun north(n: Int = 1) = offset(BlockFace.NORTH, n)
@JvmOverloads
fun south(n: Int = 1) = offset(BlockFace.SOUTH, n)
@JvmOverloads
fun east(n: Int = 1) = offset(BlockFace.EAST, n)
@JvmOverloads
fun west(n: Int = 1) = offset(BlockFace.WEST, n)
@JvmOverloads
fun offset(facing: BlockFace, n: Int = 1): BlockPos {
return BlockPos(x + facing.getOffsetX() * n, y + facing.getOffsetY() * n, z + facing.getOffsetZ() * n)
}
fun distanceTo(other: BlockPos): Double {
val x = (mcValue.x - other.x).toDouble()
val y = (mcValue.y - other.y).toDouble()
val z = (mcValue.z - other.z).toDouble()
return sqrt(x * x + y * y + z * z)
}
fun toVec3d() = Vec3d(x.toDouble(), y.toDouble(), z.toDouble())
}
| 5 |
Kotlin
|
8
| 21 |
bdfe30c49f6812f8c1b09ab3cc32cd64836f736e
| 2,312 |
ctjs
|
MIT License
|
src/test/kotlin/com/geovannycode/apirestcoroutine/ApirestcoroutineApplicationTests.kt
|
Geovanny0401
| 638,744,570 | false | null |
package com.geovannycode.apirestcoroutine
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class ApirestcoroutineApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 |
Kotlin
|
0
| 3 |
57ab028a60981dff860678f3e09defd304dbce1e
| 231 |
api-rest-reactiva
|
Apache License 2.0
|
src/main/kotlin/me/friedfat/chiccenapi/bossbar/BossbarText.kt
|
friedFat
| 680,492,584 | false | null |
package me.friedfat.chiccenapi.bossbar
import net.axay.kspigot.extensions.onlinePlayers
import org.bukkit.Bukkit
import org.bukkit.NamespacedKey
import org.bukkit.boss.BarColor
import org.bukkit.boss.BarFlag
import org.bukkit.boss.BarStyle
import org.bukkit.entity.Player
import java.util.*
import kotlin.concurrent.thread
import kotlin.time.Duration
open class BossbarText(title: String?, barColor: BarColor, barStyle: BarStyle = BarStyle.SOLID, flags: Set<BarFlag> = setOf()) {
val bossbar = Bukkit.createBossBar(NamespacedKey.minecraft(UUID.randomUUID().toString()), title, barColor, barStyle)
init {
flags.forEach {
bossbar.addFlag(it)
}
}
fun show(players: Collection<Player> = onlinePlayers, duration: Duration? = null){
players.forEach {
bossbar.addPlayer(it)
}
if(duration!=null){
thread {
Thread.sleep(duration.inWholeMilliseconds)
bossbar.removeAll()
}
}
}
fun remove(){
bossbar.removeAll()
}
}
| 0 |
Kotlin
|
0
| 0 |
3fd0ede374a38bd834822acd15b61dcf1b7229cd
| 1,074 |
ChiccenAPI
|
Apache License 2.0
|
server/librarytest2/src/main/kotlin/managers/FileManager.kt
|
PlanetBuilder
| 429,193,558 | false | null |
package managers
import com.google.common.base.Charsets
import com.google.common.io.FileWriteMode
import com.google.common.io.Files
import java.io.File
import java.io.IOException
class FileManager {
fun addDataToFile(filePath: String, data: String) {
try {
Files.asCharSink(File(filePath), Charsets.UTF_8, FileWriteMode.APPEND).write(data)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
d1a58cde4ab3efe56af28d2f855b7c37f1862202
| 450 |
hypixel-api
|
MIT License
|
Yum-Client/app/src/main/java/com/anbui/yum/domain/model/Ingredient.kt
|
AnBuiii
| 608,489,464 | false | null |
package com.anbui.yum.domain.model
import kotlinx.serialization.Serializable
@Serializable
data class Ingredient(
val name: String = "Food",
val protein: Int = 0,
val carb: Int = 0,
val fat: Int = 0,
val cholesterol: Int = 0,
val sodium: Int = 0,
val potassium: Int = 0,
val calcium: Int = 0,
val iron: Int = 0,
val tag: String = "",
val id: String,
)
val nutritionFacts = listOf(
Triple("Calories", "460 cal", "35%"),
Triple("Calories from Fat", "130 cal", "12%"),
Triple("Calories from Carbs", "123 cal", "13%"),
Triple("Calories from Protein", "", "31%"),
Triple("Cholesterol", "123 mg", "23%"),
Triple("Sodium", "123", "%"),
Triple("Potassium", "123", "%"),
Triple("Calcium", "123", "%"),
Triple("Iron", "123", "23%"),
)
| 0 |
Kotlin
|
0
| 3 |
94a9344aeb57403214315191304b81d15d584863
| 810 |
Yum
|
MIT License
|
core/core-qrcode/src/main/java/qsos/core/qrcode/QRCodePointsOverlayView.kt
|
puyunfeng
| 210,260,355 | false |
{"Kotlin": 506821, "HTML": 4334}
|
package qsos.core.qrcode
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.view.View
class QRCodePointsOverlayView : View {
private var points: Array<PointF?>? = null
private var paint: Paint? = null
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
paint = Paint()
paint!!.color = Color.YELLOW
paint!!.style = Paint.Style.FILL
}
fun setPoints(points: Array<PointF?>) {
this.points = points
invalidate()
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
if (points != null) {
for (pointF in points!!) {
if (pointF != null) {
canvas.drawCircle(pointF.x, pointF.y, 10f, paint!!)
}
}
}
}
}
| 0 | null |
0
| 0 |
e6001d57db67e368777fda200dbd4f15290e4667
| 1,208 |
abcl
|
Apache License 2.0
|
src/main/java/org/runestar/tfudeob/FixInnerClasses.kt
|
RuneStar
| 173,670,344 | false | null |
package org.runestar.tfudeob
import org.objectweb.asm.Type
import org.objectweb.asm.tree.*
object FixInnerClasses : Transformer.Tree() {
override fun transform(klasses: List<ClassNode>): List<ClassNode> {
val classAccess = klasses.associate { it.name to it.access }
for (klass in klasses) {
val types = HashSet<Type>()
types.add(Type.getObjectType(klass.name))
types.add(Type.getObjectType(klass.superName))
klass.fields.mapTo(types) { Type.getType(it.desc) }
klass.methods.forEach { m ->
m.instructions.iterator().forEach { insn ->
when (insn) {
is FieldInsnNode -> types.add(Type.getType(insn.desc))
is MethodInsnNode -> types.add(Type.getType(insn.desc))
is TypeInsnNode -> types.add(Type.getObjectType(insn.desc))
is MultiANewArrayInsnNode -> types.add(Type.getType(insn.desc))
}
}
}
val classes = HashSet<Type>()
types.forEach { t ->
when (t.sort) {
Type.ARRAY -> classes.add(t.elementType)
Type.OBJECT -> classes.add(t)
}
}
val classNames = classes.map { it.internalName }
classNames.forEach { className ->
if (!className.contains('$')) return@forEach
val access = classAccess[className] ?: Class.forName(className.replace('/', '.')).modifiers
val outer = className.substringBeforeLast('$')
val simpleRaw = className.substringAfterLast('$')
val simple = if (simpleRaw.toIntOrNull() == null) simpleRaw else null
//klass.innerClasses.add(InnerClassNode(className, outer, simple, access))
}
// if (!klass.name.contains('$')) {
klass.outerClass = null
klass.outerMethod = null
klass.outerMethodDesc = null
// }
}
return klasses
}
}
| 0 |
Kotlin
|
4
| 5 |
cfdd37008262ddb673f3a848bbfc46b1fc05eb93
| 2,130 |
tfu-deob
|
ISC License
|
app/src/main/java/com/zwq65/unity/data/DataManager.kt
|
Izzamuzzic
| 95,655,850 | false |
{"Kotlin": 449365, "Java": 17918}
|
/*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zwq65.unity.data
import com.zwq65.unity.data.db.DbHelper
import com.zwq65.unity.data.network.ApiHelper
import com.zwq65.unity.data.prefs.PreferencesHelper
/**
* ================================================
* data model
*
* Created by NIRVANA on 2017/01/27.
* Contact with <<EMAIL>>
* ================================================
*/
interface DataManager : DbHelper, PreferencesHelper, ApiHelper {
/**
* 更新当前账号的token
*
* @param userId userId
* @param accessToken accessToken
*/
fun updateApiHeader(userId: Long?, accessToken: String?)
}
| 0 |
Kotlin
|
0
| 0 |
98a9ad7bb298d0b0cfd314825918a683d89bb9e8
| 1,248 |
Unity
|
Apache License 2.0
|
endlessRunnersGame/src/main/kotlin/cz/woitee/endlessRunners/game/actions/ApplyGameEffectAction.kt
|
woitee
| 219,872,458 | false | null |
package cz.woitee.endlessRunners.game.actions
import cz.woitee.endlessRunners.game.GameState
import cz.woitee.endlessRunners.game.actions.abstract.GameAction
import cz.woitee.endlessRunners.game.effects.UndoableGameEffect
import cz.woitee.endlessRunners.game.undoing.IUndo
/**
* An action that just applies a GameEffect.
*/
open class ApplyGameEffectAction(var gameEffect: UndoableGameEffect) : GameAction() {
override fun isApplicableOn(gameState: GameState): Boolean {
return true
}
override fun applyOn(gameState: GameState) {
gameEffect.applyOn(gameState)
}
override fun applyUndoablyOn(gameState: GameState): IUndo {
return gameEffect.applyUndoablyOn(gameState)
}
override fun toString(): String {
return "ApplyGameEffect($gameEffect)"
}
}
| 0 |
Kotlin
|
0
| 1 |
5c980f44397f0b4f122e7b2cb51b82cf1c0419df
| 816 |
endlessRunners
|
Apache License 2.0
|
src/main/kotlin/com/bh/planners/core/kether/game/ActionMutable.kt
|
postyizhan
| 754,476,430 | false |
{"Kotlin": 652703, "Java": 215}
|
package com.bh.planners.core.kether.game
import com.bh.planners.core.kether.common.CombinationKetherParser
import com.bh.planners.core.kether.common.KetherHelper
import com.bh.planners.core.kether.nextOptionalParsedAction
import com.bh.planners.core.pojo.chant.Mutable
import taboolib.common.util.random
import taboolib.module.kether.KetherParser
import taboolib.module.kether.combinationParser
import taboolib.module.kether.scriptParser
import taboolib.module.kether.switch
/**
* 创建模板可变文本
* mutabletext message with fill <space: action("")> <step: action(10)>
*/
@CombinationKetherParser.Used
fun mutabletext() = KetherHelper.simpleKetherParser<String> {
it.group(
text(),
text(),
text(),
command("space", then = text()).option().defaultsTo(""),
command("step", then = int()).option().defaultsTo(10),
command("with", then = double()).option().defaultsTo(random(0.0, 1.0))
).apply(it) { message, connect, fill, space, step, with ->
now { Mutable.Text(message, connect, fill, space, step).build(with) }
}
}
| 0 |
Kotlin
|
1
| 0 |
dea343908592d722cd03d9dbadbc659372131dfe
| 1,078 |
planners
|
Creative Commons Zero v1.0 Universal
|
library/src/main/java/com/michaelflisar/lumberjack/util/LabeledValueBuilder.kt
|
Allegion-Public
| 183,031,078 | false | null |
package com.michaelflisar.gallery.logs
class LabeledValueBuilder(val separator: String = "|", val equalSign: String = "=") {
var count: Int = 0
var data: String = ""
fun addPair(label: String, item: Any): LabeledValueBuilder {
data += "${if (count > 0) " $separator " else ""}$label $equalSign $item"
count++
return this
}
fun build(): String = data
}
| 1 | null |
1
| 1 |
4742f95b13d3e2710fd1bcc493a8241f9605e351
| 399 |
Lumberjack
|
Apache License 2.0
|
src/main/kotlin/me/ebonjaeger/novusbroadcast/commands/HelpCommand.kt
|
ChemistsMC
| 107,341,741 | false | null |
package me.ebonjaeger.novusbroadcast.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.CommandHelp
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.HelpCommand
import co.aikar.commands.annotation.Subcommand
import me.ebonjaeger.novusbroadcast.NovusBroadcast
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
@CommandAlias("novusbroadcast|nb")
class HelpCommand(private val plugin: NovusBroadcast) : BaseCommand()
{
@HelpCommand
fun onHelp(sender: CommandSender, help: CommandHelp)
{
sender.sendMessage("${ChatColor.GRAY}${ChatColor.STRIKETHROUGH}-----------------------------------------------------")
sender.sendMessage("${ChatColor.GRAY} [ ${ChatColor.BLUE}NovusBroadcast Commands${ChatColor.GRAY} ]\n\n")
help.showHelp()
sender.sendMessage("${ChatColor.GRAY}${ChatColor.STRIKETHROUGH}-----------------------------------------------------")
}
@Subcommand("version")
@CommandPermission("novusbroadcast.version")
@Description("View the installed version of NovusBroadcast")
fun onVersion(sender: CommandSender)
{
val version = plugin.description.version
val authors = plugin.description.authors
.toString()
.replace("[", "")
.replace("]", "")
sender.sendMessage("${ChatColor.BLUE}» ${ChatColor.GRAY}Version: ${ChatColor.BLUE}$version")
sender.sendMessage("${ChatColor.BLUE}» ${ChatColor.GRAY}Authors: ${ChatColor.BLUE}$authors")
}
}
| 0 |
Kotlin
|
0
| 2 |
fce7bc8230e9a4b9a674f1ab188e417fb035380e
| 1,681 |
NovusBroadcast
|
MIT License
|
weibolink/src/main/java/io/github/wangcheng/weibolink/MainActivity.kt
|
wangcheng
| 521,858,696 | false |
{"Kotlin": 31274, "Java": 6164}
|
package io.github.wangcheng.weibolink
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.action == Intent.ACTION_VIEW) {
openWeiboDetailPageFromUrl(intent.data.toString())
}
finish()
}
private fun startViewUrlActivity(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
private fun openWeiboDetailPage(weiboId: String) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "weiboId: $weiboId")
}
val weiboAppIntent =
Intent(Intent.ACTION_VIEW, Uri.parse("sinaweibo://detail?mblogid=$weiboId"))
weiboAppIntent.addCategory(Intent.CATEGORY_DEFAULT)
if (weiboAppIntent.resolveActivity(packageManager) != null) {
startActivity(weiboAppIntent)
} else {
startViewUrlActivity(WeiboLinkUtils.createWeiboCnUrl(weiboId))
}
}
private fun openWeiboDetailPageFromUrl(url: String) {
val weiboId = WeiboLinkUtils.getWeiboIdFromUrl(url)
if (weiboId != null) {
return openWeiboDetailPage(weiboId)
}
return startViewUrlActivity(url)
}
companion object {
private const val TAG = "MainActivity"
}
}
| 2 |
Kotlin
|
0
| 1 |
c1cc4130a213a1ed39f8bf708adc671daba9b164
| 1,479 |
android
|
MIT License
|
base/media/medialib/src/main/kotlin/com/flammky/common/media/audio/meta_tag/utils/EqualsUtil.kt
|
flammky
| 462,795,948 | false |
{"Kotlin": 5222947}
|
package com.flammky.musicplayer.common.media.audio.meta_tag.utils
/**
* Collected methods which allow easy implementation of `equals`.
*
* Example use case in a class called Car:
* <pre>
* public boolean equals(Object aThat){
* if ( this == aThat ) return true;
* if ( !(aThat instanceof Car) ) return false;
* Car that = (Car)aThat;
* return
* EqualsUtil.areEqual(this.fName, that.fName) &&
* EqualsUtil.areEqual(this.fNumDoors, that.fNumDoors) &&
* EqualsUtil.areEqual(this.fGasMileage, that.fGasMileage) &&
* EqualsUtil.areEqual(this.fColor, that.fColor) &&
* Arrays.equals(this.fMaintenanceChecks, that.fMaintenanceChecks); //array!
* }
</pre> *
*
* *Arrays are not handled by this class*.
* This is because the `Arrays.equals` methods should be used for
* array fields.
*/
object EqualsUtil {
fun areEqual(aThis: Boolean, aThat: Boolean): Boolean {
//System.out.println("boolean");
return aThis == aThat
}
fun areEqual(aThis: Char, aThat: Char): Boolean {
//System.out.println("char");
return aThis == aThat
}
fun areEqual(aThis: Long, aThat: Long): Boolean {
/*
* Implementation Note
* Note that byte, short, and int are handled by this method, through
* implicit conversion.
*/
//System.out.println("long");
return aThis == aThat
}
fun areEqual(aThis: Float, aThat: Float): Boolean {
//System.out.println("float");
return java.lang.Float.floatToIntBits(aThis) == java.lang.Float.floatToIntBits(aThat)
}
fun areEqual(aThis: Double, aThat: Double): Boolean {
//System.out.println("double");
return java.lang.Double.doubleToLongBits(aThis) == java.lang.Double.doubleToLongBits(aThat)
}
/**
* Possibly-null object field.
*
* Includes type-safe enumerations and collections, but does not include
* arrays. See class comment.
*/
@JvmStatic
fun areEqual(aThis: Any?, aThat: Any?): Boolean {
//System.out.println("Object");
return if (aThis == null) aThat == null else aThis == aThat
}
}
| 0 |
Kotlin
|
6
| 56 |
2b8b4affab4306e351cfc8721c15a5bc7ecba908
| 1,971 |
Music-Player
|
Apache License 2.0
|
lib/src/commonMain/kotlin/br/com/androidvip/snappier/data/models/NavigationItemDTO.kt
|
Lennoard
| 782,262,217 | false |
{"Kotlin": 106575, "TypeScript": 5377, "Ruby": 2165, "Swift": 594, "HTML": 593}
|
package br.com.androidvip.snappier.data.models
import kotlinx.serialization.Serializable
@Serializable
data class NavigationItemDTO(
val action: ActionDTO? = null,
val label: String? = null,
val enabled: Boolean = true,
val icon: IconDTO? = null,
val color: String? = "#000000"
)
| 0 |
Kotlin
|
0
| 0 |
6f4e9bfe9a88abe961816c55cc8992642265e1ba
| 302 |
Snappier
|
MIT License
|
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/ValidationStampFilterServiceExtensions.kt
|
nemerosa
| 19,351,480 | false |
{"Git Config": 1, "Gradle Kotlin DSL": 67, "Markdown": 46, "Ignore List": 22, "Java Properties": 3, "Shell": 9, "Text": 3, "Batchfile": 2, "Groovy": 145, "JSON": 31, "JavaScript": 792, "JSON with Comments": 4, "GraphQL": 79, "Kotlin": 3960, "Java": 649, "HTML": 269, "PlantUML": 25, "AsciiDoc": 288, "XML": 9, "YAML": 33, "INI": 4, "Dockerfile": 7, "Less": 31, "CSS": 13, "SQL": 43, "Dotenv": 1, "Maven POM": 1, "SVG": 4}
|
package net.nemerosa.ontrack.model.structure
import net.nemerosa.ontrack.model.security.GlobalSettings
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.security.ValidationStampFilterCreate
import net.nemerosa.ontrack.model.security.ValidationStampFilterMgt
/**
* Checks the authorization to update a validation stamp filter, depending on its scope.
*
* @receiver The security service to extend
* @param filter The filter to check
*/
fun SecurityService.checkUpdateAuthorisations(filter: ValidationStampFilter) {
filter.project?.let {
checkProjectFunction(it, ValidationStampFilterMgt::class.java)
} ?: filter.branch?.let {
checkProjectFunction(it, ValidationStampFilterCreate::class.java)
} ?: checkGlobalFunction(GlobalSettings::class.java)
}
/**
* Gets the authorization to update a validation stamp filter, depending on its scope.
*
* @receiver The security service to extend
* @param filter The filter to check
* @return If the current user is authorized
*/
fun SecurityService.isUpdateAuthorized(filter: ValidationStampFilter) =
filter.project?.let {
isProjectFunctionGranted(it, ValidationStampFilterMgt::class.java)
} ?: filter.branch?.let {
isProjectFunctionGranted(it, ValidationStampFilterCreate::class.java)
} ?: isGlobalFunctionGranted(GlobalSettings::class.java)
| 48 |
Kotlin
|
25
| 96 |
759f17484c9b507204e5a89524e07df871697e74
| 1,391 |
ontrack
|
MIT License
|
app/src/main/java/com/dreamsoftware/melodiqtv/domain/repository/IArtistRepository.kt
|
sergio11
| 201,446,449 | false |
{"Kotlin": 556766}
|
package com.dreamsoftware.melodiqtv.domain.repository
import com.dreamsoftware.melodiqtv.domain.exception.FetchArtistByIdException
import com.dreamsoftware.melodiqtv.domain.exception.FetchArtistsException
import com.dreamsoftware.melodiqtv.domain.model.ArtistBO
interface IArtistRepository {
@Throws(FetchArtistsException::class)
suspend fun getArtists(): List<ArtistBO>
@Throws(FetchArtistByIdException::class)
suspend fun getArtistById(id: String): ArtistBO
}
| 0 |
Kotlin
|
0
| 1 |
ad82e5cf46929cfb1c30608c89e717929939a8d2
| 481 |
melodiqtv_android
|
MIT License
|
app/src/main/java/com/seewo/brick/app/component/list/list/page/ComplexStatefulListPage.kt
|
robin8yeung
| 591,142,442 | false |
{"Kotlin": 517624, "Java": 4201}
|
package com.seewo.brick.app.component.list.list.page
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.seewo.brick.BrickPreview
import com.seewo.brick.app.R
import com.seewo.brick.app.widget.Markdown
import com.seewo.brick.ktx.*
import com.seewo.brick.params.CornerRadius
import com.seewo.brick.params.EdgeInsets
private class ComplexStatefulListPage(context: Context, attrs: AttributeSet? = null) :
BrickPreview(context, attrs) {
override fun preview(context: Context) {
view {
context.ComplexStatefulListPage()
}
}
}
fun Context.ComplexStatefulListPage() = column(
MATCH_PARENT, MATCH_PARENT,
) {
statefulList()
ShowMarkDown()
}
private fun LinearLayout.statefulList() {
val dataLiveData = listOf(
Person("老大"),
Person("老二"),
Person("老三"),
Person("老四"),
Person("老五"),
Person("老六"),
Person("老七"),
Person("老八"),
Person("老九"),
Person("老十"),
).live
liveRecyclerView(
MATCH_PARENT, 100.dp,
data = dataLiveData,
padding = EdgeInsets.symmetric(horizontal = 12.dp),
// 通过 viewTypeBuilder 传入viewType的创建规则(列表index与ViewType的映射关系。如果列表只存在一种ItemView可以不传)
// 通过viewBuilder 传入从viewType到view的mapper (ViewType与View的映射关系,这里的View将作为复用模板。ItemView模板必须用recyclerItem包裹,否则会抛异常)
viewBuilder = {
row(
MATCH_PARENT, 32.dp
) {
textView(
64.dp,
id = 0x111,
textColor = R.color.primary.color,
textSize = 12.dp,
maxLines = 1,
ellipsize = TextUtils.TruncateAt.END,
)
layoutParams(
margins = EdgeInsets.symmetric(horizontal = 8.dp),
weight = 1f,
) {
textView(
MATCH_PARENT,
id = 0x112,
textColor = Color.BLACK,
textSize = 14.dp,
)
}
textView(
id = 0x113,
text = "删除",
textColor = Color.RED,
textSize = 12.dp,
padding = EdgeInsets.symmetric(horizontal = 4.dp, vertical = 2.dp),
background = rectDrawable(
strokeColor = Color.RED,
strokeWidth = 1.dp,
corners = CornerRadius.all(4.dp)
)
)
}
}
) { data, index, view ->
// 通过dataBinder来把数据信息装填到View中,这里提供的一种思路是通过findViewById去拿到view,这就需要相关View都要设置id
val person = data[index]
view.findViewById<TextView>(0x111).text = person.id
view.findViewById<TextView>(0x112).text = person.name
view.findViewById<View>(0x113).setOnClickListener {
// 删除该项后更新LiveData即可自动更新列表
dataLiveData.data = dataLiveData.value?.toMutableList()?.apply {
remove(person)
}
}
}
}
private fun LinearLayout.ShowMarkDown() {
expand {
Markdown(
"""
## 代码展示
liveRecyclerView与liveSimpleRecyclerView类似,也是可通过LiveData<List<T: RecyclerItemData>>来驱动列表条目的增、删、改。
其内部基于DiffUtil.calculateDiff来实现,请按实际情况重写 areSameItem 和 equals 方法
不同点在于liveSimpleRecyclerView的使用更简介和优雅;liveRecyclerView更繁琐,如可能需要设置viewTypeBuilder,viewBuilder和dataBinder 3个构造函数,还需要给View设置id,并通过findViewById这种与声明式ui相悖的方式去更新ui,但它在实现上完全还原了RecyclerView的经典实现,所以性能是最优的。
总的来说,如果对性能不偏执的话,还是更推荐使用liveSimpleRecyclerView
```kotlin
private fun LinearLayout.statefulList() {
val dataLiveData = listOf(
Person("老大"),
Person("老二"),
Person("老三"),
Person("老四"),
Person("老五"),
Person("老六"),
Person("老七"),
Person("老八"),
Person("老九"),
Person("老十"),
).live
liveRecyclerView(
MATCH_PARENT, 100.dp,
data = dataLiveData,
padding = EdgeInsets.symmetric(horizontal = 12.dp),
// 通过 viewTypeBuilder 传入viewType的创建规则(列表index与ViewType的映射关系。如果列表只存在一种ItemView可以不传)
// 通过viewBuilder 传入从viewType到view的mapper (ViewType与View的映射关系,这里的View将作为复用模板。ItemView模板必须用recyclerItem包裹,否则会抛异常)
viewBuilder = {
row(
MATCH_PARENT, 32.dp
) {
textView(
64.dp,
id = 0x111,
textColor = R.color.primary.color,
textSize = 12.dp,
maxLines = 1,
ellipsize = TextUtils.TruncateAt.END,
)
layoutParams(
margins = EdgeInsets.symmetric(horizontal = 8.dp),
weight = 1f,
) {
textView(
MATCH_PARENT,
id = 0x112,
textColor = Color.BLACK,
textSize = 14.dp,
)
}
textView(
id = 0x113,
text = "删除",
textColor = Color.RED,
textSize = 12.dp,
padding = EdgeInsets.symmetric(horizontal = 4.dp, vertical = 2.dp),
background = rectDrawable(
strokeColor = Color.RED,
strokeWidth = 1.dp,
corners = CornerRadius.all(4.dp)
)
)
}
}
) { data, index, view ->
// 通过dataBinder来把数据信息装填到View中,这里提供的一种思路是通过findViewById去拿到view,这就需要相关View都要设置id
val person = data[index]
view.findViewById<TextView>(0x111).text = person.id
view.findViewById<TextView>(0x112).text = person.name
view.findViewById<View>(0x113).setOnClickListener {
// 删除该项后更新LiveData即可自动更新列表
dataLiveData.data = dataLiveData.value?.toMutableList()?.apply {
remove(person)
}
}
}
}
```
""".trimIndent()
)
}
}
| 0 |
Kotlin
|
4
| 75 |
7f8873e8a5cde58bcde3771880fc6b489bfcd4a5
| 6,347 |
BrickUI
|
Apache License 2.0
|
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec08.kt
|
elwaxoro
| 328,044,882 | false |
{"Kotlin": 376794}
|
package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.PuzzleDayTester
/**
* Seven Segment Search
*/
class Dec08 : PuzzleDayTester(8, 2021) {
/**
* Only care about the right side of the pipe
* Only care about unique length digits
*/
override fun part1(): Any = load().map { it.split(" | ").let { it[0] to it[1] } }
.sumOf { it.second.split(" ").filter { it.length in listOf(2, 3, 4, 7) }.size }
/**
* 1, 4, 7, 8 all have unique segment counts
* masking 1, 4, 7 against other numbers and counting the remaining segments yields a unique digit:
* Ex on 2 (5 segments)
* 2 masked by 1 = 4 segments remaining
* 2 masked by 4 = 3 segments remaining
* 2 masked by 7 = 3 segments remaining
* sum of remaining for each mask = 10
* Each 5 segment digit masks to a different sum, same with 6 segment digits (note 5 and 6 overlap so doing separately)
*/
override fun part2(): Any =
load().map { it.replace(" |", "").split(" ") }.map { it to it.buildMasks() }.map { (digits, masks) ->
digits.map { digit ->
when (digit.length) {
2 -> 1
3 -> 7
4 -> 4
7 -> 8
5 -> masks.apply(digit).to5SegmentDigit() //2, 3, 5
6 -> masks.apply(digit).to6SegmentDigit() //6, 9, 0
else -> throw IllegalStateException("Unknown digit with unsupported lit segments: $digit")
}
}.takeLast(4).joinToString("").toInt()
}.sum()
private fun List<String>.buildMasks(): List<Regex> = listOf(
Regex("[${first { it.length == 2 }}]+"), // 1
Regex("[${first { it.length == 4 }}]+"), // 4
Regex("[${first { it.length == 3 }}]+") // 7
)
private fun List<Regex>.apply(digit: String) = fold(0) { acc, mask -> acc + digit.replace(mask, "").length }
private fun Int.to5SegmentDigit(): Int =
when (this) {
10 -> 2
7 -> 3
9 -> 5
else -> throw IllegalStateException("Unknown 5 segment digit: $this")
}
private fun Int.to6SegmentDigit(): Int =
when (this) {
12 -> 6
9 -> 9
10 -> 0
else -> throw IllegalStateException("Unknown 6 segment digit: $this")
}
}
| 0 |
Kotlin
|
4
| 0 |
040ad52194b3995ca2c234147cb43b046c3b917b
| 2,382 |
advent-of-code
|
MIT License
|
plugin/runtime/src/main/java/com/jaynewstrom/jsonDelight/runtime/internal/FloatJsonAdapter.kt
|
JayNewstrom
| 75,886,858 | false | null |
package com.jaynewstrom.jsonDelight.runtime.internal
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.jaynewstrom.jsonDelight.runtime.JsonDeserializer
import com.jaynewstrom.jsonDelight.runtime.JsonDeserializerFactory
import com.jaynewstrom.jsonDelight.runtime.JsonRegistrable
import com.jaynewstrom.jsonDelight.runtime.JsonSerializer
import com.jaynewstrom.jsonDelight.runtime.JsonSerializerFactory
import java.io.IOException
object FloatJsonAdapter : JsonSerializer<Float>, JsonDeserializer<Float>, JsonRegistrable {
@Throws(IOException::class)
override fun serialize(value: Float, jg: JsonGenerator, serializerFactory: JsonSerializerFactory) = jg.writeNumber(value)
@Throws(IOException::class)
override fun deserialize(jp: JsonParser, deserializerFactory: JsonDeserializerFactory): Float = jp.floatValue
override fun modelClass(): Class<*> = Float::class.java
}
| 3 |
Kotlin
|
0
| 8 |
1da696ab89e496ba161a0d7bef7e5cd198788bd7
| 945 |
JsonDelight
|
Apache License 2.0
|
sample/src/main/java/com/parsuomash/affogato/app/screens/PagerScreen.kt
|
ghasemdev
| 510,960,043 | false |
{"Kotlin": 928739, "Shell": 3263}
|
package com.parsuomash.affogato.app.screens
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.parsuomash.affogato.pager.indicator.HorizontalPagerIndicator
import com.parsuomash.affogato.pager.indicator.VerticalPagerIndicator
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PagerScreen() {
val coroutineScope = rememberCoroutineScope()
val horizontalPagerState = rememberPagerState { 10 }
val verticalPagerState = rememberPagerState { 10 }
Column {
Box {
HorizontalPager(state = horizontalPagerState) {
Surface(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(.5f),
color = Color.LightGray
) {
Box {
Text(
modifier = Modifier.align(Alignment.Center),
text = "Page $it"
)
}
}
}
HorizontalPagerIndicator(
pagerState = horizontalPagerState,
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 8.dp),
onIndicatorClick = { page ->
coroutineScope.launch {
horizontalPagerState.animateScrollToPage(page)
}
}
)
}
Spacer(modifier = Modifier.height(8.dp))
Box {
VerticalPager(state = verticalPagerState) {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.LightGray
) {
Box {
Text(
modifier = Modifier.align(Alignment.Center),
text = "Page $it"
)
}
}
}
VerticalPagerIndicator(
pagerState = verticalPagerState,
modifier = Modifier
.align(Alignment.CenterStart)
.padding(start = 8.dp),
onIndicatorClick = { page ->
coroutineScope.launch {
verticalPagerState.animateScrollToPage(page)
}
}
)
}
}
}
| 1 |
Kotlin
|
1
| 12 |
8a00428e090788055be54471dfe4815627744065
| 2,891 |
affogato
|
MIT License
|
app/src/main/java/com/thkox/homeai/presentation/ui/components/TutorialCards.kt
|
thkox
| 782,208,937 | false |
{"Kotlin": 226354}
|
package com.thkox.homeai.presentation.ui.components
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.thkox.homeai.presentation.models.TutorialPage
import com.thkox.homeai.presentation.ui.theme.HomeAITheme
@Composable
fun TutorialCard(page: TutorialPage) {
Box(
modifier = Modifier
.fillMaxSize()
.background(
color = MaterialTheme.colorScheme.primaryContainer,
shape = RoundedCornerShape(16.dp)
),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
imageVector = page.icon,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = page.title,
fontSize = 24.sp,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
HorizontalDivider(
modifier = Modifier
.width(200.dp)
.padding(20.dp),
color = MaterialTheme.colorScheme.onPrimaryContainer
)
Text(
text = page.text,
fontSize = 15.sp,
color = MaterialTheme.colorScheme.onPrimaryContainer,
textAlign = TextAlign.Center
)
}
}
}
@Preview(
showBackground = true,
uiMode = Configuration.UI_MODE_NIGHT_NO,
name = "Light Mode"
)
@Composable
fun TutorialCardLightPreview() {
HomeAITheme {
TutorialCard(
page = TutorialPage(
title = "Welcome to Home AI",
text = "This is a brief introduction.",
icon = Icons.Default.Info
)
)
}
}
@Preview(
showBackground = true,
uiMode = Configuration.UI_MODE_NIGHT_YES,
name = "Dark Mode"
)
@Composable
fun TutorialCardDarkPreview() {
HomeAITheme {
TutorialCard(
page = TutorialPage(
title = "Welcome to Home AI",
text = "This is a brief introduction.",
icon = Icons.Default.Info
)
)
}
}
| 0 |
Kotlin
|
0
| 2 |
8a6f4239ed53e65f797f438d3326b383c40cc7c2
| 3,553 |
home-ai-client
|
MIT License
|
src/day09/Day09_Part1.kt
|
m-jaekel
| 570,582,194 | false | null |
package day09
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.size
}
val testInput = readInput("day09/test_input")
check(part1(testInput) == 0)
val input = readInput("day09/input")
println(part1(input))
}
| 0 |
Kotlin
|
0
| 1 |
07e015c2680b5623a16121e5314017ddcb40c06c
| 273 |
AOC-2022
|
Apache License 2.0
|
utils/src/main/java/ru/touchin/roboswag/components/utils/spans/PhoneSpan.kt
|
TouchInstinct
| 148,156,940 | false | null |
package ru.touchin.roboswag.components.utils.spans
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.view.View
/**
* Created by <NAME> on 14/11/2015.
* Span that is opening phone call intent.
*/
class PhoneSpan(phoneNumber: String) : URLSpanWithoutUnderline(phoneNumber) {
override fun onClick(widget: View) {
super.onClick(widget)
try {
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse(url)
widget.context.startActivity(intent)
} catch (exception: ActivityNotFoundException) {
// Do nothing
}
}
}
| 15 |
Java
|
6
| 21 |
3b35c16cde524bf4400ad29f34c71fde2001a2e2
| 675 |
RoboSwag
|
Apache License 2.0
|
app/src/main/java/com/example/noteapp/ui/navigation/NavigationBottomBar.kt
|
duygucalik
| 740,647,806 | false |
{"Kotlin": 51016}
|
package com.example.noteapp.ui.navigation
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material3.AlertDialogDefaults.containerColor
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalAbsoluteTonalElevation
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.noteapp.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NavigationBottomBar(
navController: NavHostController
) {
val list = listOf(
Destination.Home,
Destination.Done
)
val selectedIndex = rememberSaveable {
mutableIntStateOf(0)
}
NavigationBar(
modifier =Modifier.clip(RoundedCornerShape(15.dp, 15.dp, 15.dp, 15.dp)),
containerColor= colorResource(id = R.color.purples)
) {
list.forEachIndexed { index, destination ->
NavigationBarItem(
label = { Text(
text = destination.title,
color=Color.White,
fontSize = 16.sp
) },
selected = index == selectedIndex.value,
onClick = {
selectedIndex.value = index
navController.navigate(list[index].route) {
popUpTo(navController.graph.startDestinationId)
launchSingleTop = true
}
},
icon = {
Icon(
tint=Color.White,
imageVector = destination.icon,
contentDescription = destination.title
)
})
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ad8e8a9a6bea8f36a97d74373f02f1ee476b8b9b
| 3,146 |
NoteApp
|
MIT License
|
remote/src/main/java/com/ferelin/remote/webSocket/connector/WebSocketConnector.kt
|
sarath940
| 391,107,525 | true |
{"Kotlin": 768543}
|
package com.ferelin.remote.webSocket.connector
/*
* Copyright 2021 <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.
*/
import com.ferelin.remote.base.BaseResponse
import com.ferelin.remote.utils.Api
import com.ferelin.remote.webSocket.response.WebSocketResponse
import kotlinx.coroutines.flow.Flow
/**
* [WebSocketConnector] provides ability to open connection with server and
* get data about live-time stock's prices.
* */
interface WebSocketConnector {
/**
* Opens web socket and start returns responses on this flow
* */
fun openWebSocketConnection(token: String = Api.FINNHUB_TOKEN): Flow<BaseResponse<WebSocketResponse>>
fun closeWebSocketConnection()
/**
* Subscribes new item for live time updates.
* @param symbol is a company symbol that must be subscribed for updates
* @param previousPrice is a current price of stock that is used to calculate the price difference
* */
fun subscribeItemOnLiveTimeUpdates(symbol: String, previousPrice: Double)
/**
* Unsubscribes items from live time updates.
* @param symbol is a company symbol that must be unsubscribed from updates
* */
fun unsubscribeItemFromLiveTimeUpdates(symbol: String)
}
| 0 | null |
0
| 0 |
2c0e4b045786fdf4b4d51bf890a3dbf0cd8099d1
| 1,743 |
Android_Stock_Price
|
Apache License 2.0
|
app/src/main/java/fr/azhot/weatherapp/presentation/BaseFragment.kt
|
Azhot
| 353,679,211 | false | null |
package fr.azhot.weatherapp.presentation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
abstract class BaseFragment<B : ViewBinding>(val bindingFactory: (LayoutInflater) -> B) :
Fragment() {
protected lateinit var binding: B
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = bindingFactory(inflater)
return binding.root
}
}
| 0 |
Kotlin
|
0
| 0 |
d21a1f4fb91a9e402d664f18001c4111b2bf6d34
| 607 |
WeatherApp
|
MIT License
|
src/main/kotlin/be/arby/taffy/style/dimension/LengthPercentage.kt
|
adjabaev
| 839,569,114 | false |
{"Kotlin": 638630, "HTML": 558738, "JavaScript": 9416, "CSS": 2507, "Shell": 866}
|
package be.arby.taffy.style.dimension
import be.arby.taffy.lang.Option
sealed class LengthPercentage {
/**
* An absolute length in some abstract units. Users of Taffy may define what they correspond
* to in their application (pixels, logical pixels, mm, etc) as they see fit.
*/
data class Length(val f: Float = 0f) : LengthPercentage()
/**
* The dimension is stored in percentage relative to the parent item.
*/
data class Percent(val f: Float = 0f) : LengthPercentage()
fun maybeResolve(context: Option<Float>): Option<Float> {
return when (this) {
is Length -> Option.Some(this.f)
is Percent -> context.map { dim -> dim * this.f }
}
}
fun maybeResolve(context: Float): Option<Float> {
return maybeResolve(Option.Some(context))
}
/**
* Will return a default value of result is evaluated to `None`
*/
fun resolveOrZero(context: Option<Float>): Float {
return maybeResolve(context).unwrapOr(0f)
}
companion object {
val ZERO: LengthPercentage = Length(0f)
fun fromLength(points: Float): Length {
return Length(points)
}
fun fromPercent(percent: Float): Percent {
return Percent(percent)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
464b84e9bc323a43d349dc2b72c72319df359a87
| 1,309 |
TaffyKT
|
MIT License
|
Android/app/src/main/java/com/orange/ease/dan/ui/OtherAppsActivity.kt
|
Romain-Rs
| 469,795,451 | true |
{"HTML": 483317, "Kotlin": 274017, "Swift": 254750, "Java": 64410, "CSS": 16805}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.orange.ease.dan.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.orange.ease.dan.databinding.ActivityOtherAppsBinding
class OtherAppsActivity : AppCompatActivity() {
private lateinit var binding: ActivityOtherAppsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOtherAppsBinding.inflate(layoutInflater)
val view = binding.root
setupToolbar()
setContentView(view)
val webView = binding.webViewOtherApps
webView.settings.javaScriptEnabled = true;
webView.loadUrl("https://innovationfactory.orange.com/");
}
private fun setupToolbar() {
setSupportActionBar(binding.myToolbar)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
binding.myToolbar.setNavigationOnClickListener { _ -> onBackPressed() }
}
}
| 0 | null |
0
| 0 |
2bdb9b569772c6f9da9bd2b6035171b79b59251c
| 1,770 |
m-dan-2
|
Creative Commons Attribution 3.0 Unported
|
kotlin-mui-icons/src/main/generated/mui/icons/material/ElectricScooterSharp.kt
|
JetBrains
| 93,250,841 | false | null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ElectricScooterSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val ElectricScooterSharp: SvgIconComponent
| 12 |
Kotlin
|
145
| 983 |
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 222 |
kotlin-wrappers
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/ElectricScooterSharp.kt
|
JetBrains
| 93,250,841 | false | null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ElectricScooterSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val ElectricScooterSharp: SvgIconComponent
| 12 |
Kotlin
|
145
| 983 |
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 222 |
kotlin-wrappers
|
Apache License 2.0
|
litenet/src/main/java/com/aqrlei/litenet/transformer/AbstractTransformer.kt
|
AqrLei
| 288,324,186 | false | null |
package com.aqrlei.litenet.transformer
import android.util.Log
import com.aqrlei.litenet.IS_DEBUG
import com.aqrlei.litenet.ITransformer
/**
* created by AqrLei on 2020/4/21
*/
abstract class AbstractTransformer<T> : ITransformer<T> {
protected val tag = "Transformer"
protected fun log(message:String){
if (IS_DEBUG) {
Log.d(tag, message)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
9e95bf813060ec0e691fab7b274bf65bdeb005ed
| 391 |
LiteNet
|
Apache License 2.0
|
app/src/main/java/com/stocksexchange/android/ui/base/mvp/views/TradeView.kt
|
libertaria-project
| 183,030,087 | true |
{"Kotlin": 2210140}
|
package com.stocksexchange.android.ui.base.mvp.views
import com.stocksexchange.android.api.model.CurrencyMarket
import com.stocksexchange.android.api.model.OrderTradeTypes
import com.stocksexchange.android.api.model.User
import java.util.Locale
/**
* A base trading view to build views on.
*/
interface TradeView {
/**
* Shows a toast.
*
* @param message The toast message
*/
fun showToast(message: String)
/**
* Shows the progress bar.
*/
fun showProgressBar()
/**
* Hides the progress bar.
*/
fun hideProgressBar()
/**
* Enables the trade button.
*/
fun enableTradeButton()
/**
* Disables the trade button.
*/
fun disableTradeButton()
/**
* Sets an amount input error.
*
* @param error The error to set
*/
fun setAmountInputError(error: String)
/**
* Sets an at price input error.
*/
fun setAtPriceInputError(error: String)
/**
* Updates the user balance after the trade request has been sent.
*/
fun updateBalance()
/**
* Updates the trade details (fee, user deduction, user addition)
* with the passed information.
*
* @param amount The amount to trade
* @param price The price at which to trade
*/
fun updateTradeDetails(amount: Double, price: Double)
/**
* Updates the user.
*/
fun updateUser(user: User)
/**
* Calculates the trade amount.
*
* @return The amount to trade
*/
fun calculateAmount(): Double
/**
* Returns a raw amount from the input widget.
*
* @return The raw amount
*/
fun getAmountInput(): Double
/**
* Returns a raw price from the input widget.
*
* @return The raw price
*/
fun getAtPriceInput(): Double
/**
* Returns a user's base currency balance.
*
* @return The user's base currency balance
*/
fun getBaseCurrencyUserBalance(): Double
/**
* Returns a user's quote currency balance.
*
* @return The user's quote currency balance
*/
fun getQuoteCurrencyUserBalance(): Double
/**
* Returns a minimum order amount necessary for a trade.
*
* @return The minimum order amount
*/
fun getMinOrderAmount(): String
/**
* Returns an order trade type (either buy or sell).
*
* @return The order trade type
*/
fun getOrderTradeType(): OrderTradeTypes
/**
* Returns a signed in user.
*
* @return The signed in user
*/
fun getUser(): User
/**
* Returns a currency market a trade is about to be performed on.
*
* @return The currency market
*/
fun getCurrencyMarket(): CurrencyMarket
/**
* Returns a locale of the device
*
* @return The device's locale
*/
fun getLocale(): Locale
}
| 0 |
Kotlin
|
0
| 0 |
35a7f9a61f52f68ab3267da24da3c1d77d84e9c3
| 2,939 |
Android-app
|
MIT License
|
app/src/main/java/com/stocksexchange/android/ui/base/mvp/views/TradeView.kt
|
libertaria-project
| 183,030,087 | true |
{"Kotlin": 2210140}
|
package com.stocksexchange.android.ui.base.mvp.views
import com.stocksexchange.android.api.model.CurrencyMarket
import com.stocksexchange.android.api.model.OrderTradeTypes
import com.stocksexchange.android.api.model.User
import java.util.Locale
/**
* A base trading view to build views on.
*/
interface TradeView {
/**
* Shows a toast.
*
* @param message The toast message
*/
fun showToast(message: String)
/**
* Shows the progress bar.
*/
fun showProgressBar()
/**
* Hides the progress bar.
*/
fun hideProgressBar()
/**
* Enables the trade button.
*/
fun enableTradeButton()
/**
* Disables the trade button.
*/
fun disableTradeButton()
/**
* Sets an amount input error.
*
* @param error The error to set
*/
fun setAmountInputError(error: String)
/**
* Sets an at price input error.
*/
fun setAtPriceInputError(error: String)
/**
* Updates the user balance after the trade request has been sent.
*/
fun updateBalance()
/**
* Updates the trade details (fee, user deduction, user addition)
* with the passed information.
*
* @param amount The amount to trade
* @param price The price at which to trade
*/
fun updateTradeDetails(amount: Double, price: Double)
/**
* Updates the user.
*/
fun updateUser(user: User)
/**
* Calculates the trade amount.
*
* @return The amount to trade
*/
fun calculateAmount(): Double
/**
* Returns a raw amount from the input widget.
*
* @return The raw amount
*/
fun getAmountInput(): Double
/**
* Returns a raw price from the input widget.
*
* @return The raw price
*/
fun getAtPriceInput(): Double
/**
* Returns a user's base currency balance.
*
* @return The user's base currency balance
*/
fun getBaseCurrencyUserBalance(): Double
/**
* Returns a user's quote currency balance.
*
* @return The user's quote currency balance
*/
fun getQuoteCurrencyUserBalance(): Double
/**
* Returns a minimum order amount necessary for a trade.
*
* @return The minimum order amount
*/
fun getMinOrderAmount(): String
/**
* Returns an order trade type (either buy or sell).
*
* @return The order trade type
*/
fun getOrderTradeType(): OrderTradeTypes
/**
* Returns a signed in user.
*
* @return The signed in user
*/
fun getUser(): User
/**
* Returns a currency market a trade is about to be performed on.
*
* @return The currency market
*/
fun getCurrencyMarket(): CurrencyMarket
/**
* Returns a locale of the device
*
* @return The device's locale
*/
fun getLocale(): Locale
}
| 0 |
Kotlin
|
0
| 0 |
35a7f9a61f52f68ab3267da24da3c1d77d84e9c3
| 2,939 |
Android-app
|
MIT License
|
dhcamera/src/main/java/com/dhkim/dhcamera/model/SelectFontAlignElement.kt
|
kdh123
| 837,434,874 | false |
{"Kotlin": 123568}
|
package com.dhkim.dhcamera.model
import androidx.compose.runtime.Stable
data class SelectFontAlignElement(
val isSelected: Boolean = false,
val alignment: FontAlign = FontAlign.Center
)
@Stable
enum class FontAlign {
Center,
Left,
Right
}
| 0 |
Kotlin
|
0
| 0 |
e8315b5821e485abe7ba9961657fdd611001b528
| 262 |
DhCamera
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.