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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/jvmMain/kotlin/com/github/kitakkun/mirrorcomment/ui/TopToolBar.kt
|
kitakkun
| 669,828,470 | false | null |
package com.github.kitakkun.mirrorcomment.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun TopToolBar(
liveUrl: String,
onLiveUrlChange: (String) -> Unit,
onClickStart: () -> Unit,
onClickSettings: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
) {
TextField(
value = liveUrl,
onValueChange = onLiveUrlChange,
label = { Text("ใฉใคใ้
ไฟกใฎURL") },
modifier = Modifier.weight(1f),
)
Spacer(modifier = Modifier.width(16.dp))
Button(onClick = onClickStart) {
Text("ๅๅพ้ๅง")
}
IconButton(onClick = onClickSettings) {
Icon(Icons.Default.Settings, contentDescription = "่จญๅฎ")
}
}
}
| 0 |
Kotlin
|
0
| 0 |
cd791fb9f8c235c5c203cf4ff6a2b0bdbbb82e76
| 1,217 |
MirrorComment
|
MIT License
|
app/src/main/java/de/seemoo/at_tracking_detection/detection/ScanBluetoothWorker.kt
|
seemoo-lab
| 385,199,222 | false |
{"Kotlin": 491934, "Ruby": 1078}
|
package de.seemoo.at_tracking_detection.detection
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.location.Location
import android.os.Handler
import android.os.Looper
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import de.seemoo.at_tracking_detection.ATTrackingDetectionApplication
import de.seemoo.at_tracking_detection.BuildConfig
import de.seemoo.at_tracking_detection.database.models.Beacon
import de.seemoo.at_tracking_detection.database.models.Scan
import de.seemoo.at_tracking_detection.database.models.device.*
import de.seemoo.at_tracking_detection.database.models.device.types.SamsungDevice.Companion.getPublicKey
import de.seemoo.at_tracking_detection.database.models.Location as LocationModel
import de.seemoo.at_tracking_detection.database.repository.ScanRepository
import de.seemoo.at_tracking_detection.notifications.NotificationService
import de.seemoo.at_tracking_detection.util.SharedPrefs
import de.seemoo.at_tracking_detection.util.Utility
import de.seemoo.at_tracking_detection.util.ble.BLEScanCallback
import de.seemoo.at_tracking_detection.worker.BackgroundWorkScheduler
import de.seemoo.at_tracking_detection.detection.TrackingDetectorWorker.Companion.getLocation
import kotlinx.coroutines.delay
import timber.log.Timber
import java.time.LocalDateTime
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
@HiltWorker
class ScanBluetoothWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val scanRepository: ScanRepository,
private val locationProvider: LocationProvider,
private val notificationService: NotificationService,
var backgroundWorkScheduler: BackgroundWorkScheduler
) :
CoroutineWorker(appContext, workerParams) {
private lateinit var bluetoothAdapter: BluetoothAdapter
private var scanResultDictionary: HashMap<String, DiscoveredDevice> = HashMap()
var location: Location? = null
set(value) {
field = value
if (value != null) {
locationRetrievedCallback?.let { it() }
}
}
private var locationRetrievedCallback: (() -> Unit)? = null
override suspend fun doWork(): Result {
Timber.d("Bluetooth scanning worker started!")
val scanMode = getScanMode()
val scanId = scanRepository.insert(Scan(startDate = LocalDateTime.now(), isManual = false, scanMode = scanMode))
if (!Utility.checkBluetoothPermission()) {
Timber.d("Permission to perform bluetooth scan missing")
return Result.retry()
}
try {
val bluetoothManager =
applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothAdapter = bluetoothManager.adapter
} catch (e: Throwable) {
Timber.e("BluetoothAdapter not found!")
return Result.retry()
}
scanResultDictionary = HashMap()
val useLocation = SharedPrefs.useLocationInTrackingDetection
if (useLocation) {
// Returns the last known location if this matches our requirements or starts new location updates
location = locationProvider.lastKnownOrRequestLocationUpdates(locationRequester = locationRequester, timeoutMillis = 60_000L)
}
//Starting BLE Scan
Timber.d("Start Scanning for bluetooth le devices...")
val scanSettings =
ScanSettings.Builder().setScanMode(scanMode).build()
SharedPrefs.isScanningInBackground = true
BLEScanCallback.startScanning(bluetoothAdapter.bluetoothLeScanner, DeviceManager.scanFilter, scanSettings, leScanCallback)
val scanDuration: Long = getScanDuration()
delay(scanDuration)
BLEScanCallback.stopScanning(bluetoothAdapter.bluetoothLeScanner)
Timber.d("Scanning for bluetooth le devices stopped!. Discovered ${scanResultDictionary.size} devices")
//Waiting for updated location to come in
val fetchedLocation = waitForRequestedLocation()
Timber.d("Fetched location? $fetchedLocation")
if (location == null) {
// Get the last location no matter if the requirements match or not
location = locationProvider.getLastLocation(checkRequirements = false)
}
//Adding all scan results to the database after the scan has finished
scanResultDictionary.forEach { (_, discoveredDevice) ->
insertScanResult(
discoveredDevice.scanResult,
location?.latitude,
location?.longitude,
location?.accuracy,
discoveredDevice.discoveryDate,
)
}
SharedPrefs.lastScanDate = LocalDateTime.now()
SharedPrefs.isScanningInBackground = false
val scan = scanRepository.scanWithId(scanId.toInt())
if (scan != null) {
scan.endDate = LocalDateTime.now()
scan.duration = scanDuration.toInt() / 1000
scan.noDevicesFound = scanResultDictionary.size
scanRepository.update(scan)
}
Timber.d("Scheduling tracking detector worker")
backgroundWorkScheduler.scheduleTrackingDetector()
BackgroundWorkScheduler.scheduleAlarmWakeupIfScansFail()
return Result.success(
Data.Builder()
.putLong("duration", scanDuration)
.putInt("mode", scanMode)
.putInt("devicesFound", scanResultDictionary.size)
.build()
)
}
private val leScanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, scanResult: ScanResult) {
super.onScanResult(callbackType, scanResult)
//Checks if the device has been found already
if (!scanResultDictionary.containsKey(getPublicKey(scanResult))) {
Timber.d("Found ${scanResult.device.address} at ${LocalDateTime.now()}")
scanResultDictionary[getPublicKey(scanResult)] =
DiscoveredDevice(scanResult, LocalDateTime.now())
}
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Timber.e("Bluetooth scan failed $errorCode")
if (BuildConfig.DEBUG) {
notificationService.sendBLEErrorNotification()
}
}
}
private val locationRequester: LocationRequester = object : LocationRequester() {
override fun receivedAccurateLocationUpdate(location: Location) {
[email protected] = location
[email protected]?.let { it() }
}
}
private fun getScanMode(): Int {
val useLowPower = SharedPrefs.useLowPowerBLEScan
return if (useLowPower) {
ScanSettings.SCAN_MODE_LOW_POWER
} else {
ScanSettings.SCAN_MODE_LOW_LATENCY
}
}
private fun getScanDuration(): Long {
val useLowPower = SharedPrefs.useLowPowerBLEScan
return if (useLowPower) {
15000L
} else {
8000L
}
}
private suspend fun waitForRequestedLocation(): Boolean {
if (location != null || !SharedPrefs.useLocationInTrackingDetection) {
//Location already there. Just return
return true
}
return suspendCoroutine { cont ->
var coroutineFinished = false
val handler = Handler(Looper.getMainLooper())
val runnable = Runnable {
if (!coroutineFinished) {
coroutineFinished = true
locationRetrievedCallback = null
Timber.d("Could not get location update in time.")
cont.resume(false)
}
}
locationRetrievedCallback = {
if (!coroutineFinished) {
handler.removeCallbacks(runnable)
coroutineFinished = true
cont.resume(true)
}
}
// Fallback if no location is fetched in time
val maximumLocationDurationMillis = 60_000L
handler.postDelayed(runnable, maximumLocationDurationMillis)
}
}
class DiscoveredDevice(var scanResult: ScanResult, var discoveryDate: LocalDateTime)
companion object {
const val MAX_DISTANCE_UNTIL_NEW_LOCATION: Float = 150f // in meters
const val TIME_BETWEEN_BEACONS: Long = 15 // 15 minutes until the same beacon gets saved again in the db
suspend fun insertScanResult(
scanResult: ScanResult,
latitude: Double?,
longitude: Double?,
accuracy: Float?,
discoveryDate: LocalDateTime,
) {
saveDevice(scanResult, discoveryDate) ?: return // return when device does not qualify to be saved
// set locationId to null if gps location could not be retrieved
val locId: Int? = saveLocation(latitude, longitude, discoveryDate, accuracy)?.locationId
saveBeacon(scanResult, discoveryDate, locId)
}
private suspend fun saveBeacon(
scanResult: ScanResult,
discoveryDate: LocalDateTime,
locId: Int?
): Beacon? {
val beaconRepository = ATTrackingDetectionApplication.getCurrentApp()?.beaconRepository!!
val uuids = scanResult.scanRecord?.serviceUuids?.map { it.toString() }?.toList()
val uniqueIdentifier = getPublicKey(scanResult)
var beacon: Beacon? = null
val beacons = beaconRepository.getDeviceBeaconsSince(
deviceAddress = uniqueIdentifier,
since = discoveryDate.minusMinutes(TIME_BETWEEN_BEACONS)
) // sorted by newest first
if (beacons.isEmpty()) {
Timber.d("Add new Beacon to the database!")
beacon = if (BuildConfig.DEBUG) {
// Save the manufacturer data to the beacon
Beacon(
discoveryDate, scanResult.rssi, getPublicKey(scanResult), locId,
scanResult.scanRecord?.bytes, uuids
)
} else {
Beacon(
discoveryDate, scanResult.rssi, getPublicKey(scanResult), locId,
null, uuids
)
}
beaconRepository.insert(beacon)
} else if (beacons[0].locationId == null && locId != null && locId != 0){
// Update beacon within the last TIME_BETWEEN_BEACONS minutes with location
Timber.d("Beacon already in the database... Adding Location")
beacon = beacons[0]
beacon.locationId = locId
beaconRepository.update(beacon)
}
Timber.d("Beacon: $beacon")
return beacon
}
private suspend fun saveDevice(
scanResult: ScanResult,
discoveryDate: LocalDateTime
): BaseDevice? {
val deviceRepository = ATTrackingDetectionApplication.getCurrentApp()?.deviceRepository!!
val deviceAddress = getPublicKey(scanResult)
// Checks if Device already exists in device database
var device = deviceRepository.getDevice(deviceAddress)
if (device == null) {
// Do not Save Samsung Devices
device = BaseDevice(scanResult)
// Check if ConnectionState qualifies Device to be saved
// Only Save when Device is offline long enough
when(BaseDevice.getConnectionState(scanResult)){
ConnectionState.OVERMATURE_OFFLINE -> {}
// ConnectionState.OFFLINE -> {}
// ConnectionState.PREMATURE_OFFLINE -> {}
ConnectionState.UNKNOWN -> {}
else -> return null
}
Timber.d("Add new Device to the database!")
deviceRepository.insert(device)
} else {
Timber.d("Device already in the database... Updating the last seen date!")
device.lastSeen = discoveryDate
deviceRepository.update(device)
}
Timber.d("Device: $device")
return device
}
private suspend fun saveLocation(
latitude: Double?,
longitude: Double?,
discoveryDate: LocalDateTime,
accuracy: Float?
): LocationModel? {
val locationRepository = ATTrackingDetectionApplication.getCurrentApp()?.locationRepository!!
// set location to null if gps location could not be retrieved
var location: LocationModel? = null
if (latitude != null && longitude != null) {
// Get closest location from database
location = locationRepository.closestLocation(latitude, longitude)
var distanceBetweenLocations: Float = Float.MAX_VALUE
if (location != null) {
val locationA = getLocation(latitude, longitude)
val locationB = getLocation(location.latitude, location.longitude)
distanceBetweenLocations = locationA.distanceTo(locationB)
}
if (location == null || distanceBetweenLocations > MAX_DISTANCE_UNTIL_NEW_LOCATION) {
// Create new location entry
Timber.d("Add new Location to the database!")
location = LocationModel(discoveryDate, longitude, latitude, accuracy)
locationRepository.insert(location)
} else {
// If location is within the set limit, just use that location and update lastSeen
Timber.d("Location already in the database... Updating the last seen date!")
location.lastSeen = discoveryDate
locationRepository.update(location)
}
Timber.d("Location: $location")
}
return location
}
}
}
| 28 |
Kotlin
|
99
| 1,848 |
2b0e247158376e3169601e44eb286f7fbedae2de
| 14,742 |
AirGuard
|
Apache License 2.0
|
app/src/main/java/car/pace/cofu/core/util/FrameworkExtensions.kt
|
pace
| 383,417,951 | false | null |
package car.pace.cofu.core.util
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.IntentFilter
import android.graphics.Bitmap
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.core.location.LocationManagerCompat
import java.io.File
/**
* Checks whether the location is enabled or not.
*/
val Context.isLocationEnabled: Boolean
get() {
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return LocationManagerCompat.isLocationEnabled(lm)
}
/**
* Registers a receiver that will receive an update if the user enables or disables GPS
* remember to call [Activity.unregisterReceiver].
*/
fun Activity.listenForLocationEnabledChanges(receiver: BroadcastReceiver) {
registerReceiver(receiver, IntentFilter("android.location.PROVIDERS_CHANGED"))
}
/**
* Creates a file from a bitmap.
*/
fun Context.writeBitmap(bitmap: Bitmap): File {
val file = File(filesDir.absolutePath, "share.jpg")
if (!file.exists()) {
file.createNewFile()
}
file.outputStream().use { out ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)
out.flush()
}
return file
}
/**
* Checks whether the device is currently connected to a network.
*/
val Context.isOnline: Boolean
get() {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false
return arrayOf(
NetworkCapabilities.TRANSPORT_WIFI,
NetworkCapabilities.TRANSPORT_CELLULAR,
NetworkCapabilities.TRANSPORT_ETHERNET
).any { capabilities.hasTransport(it) }
}
| 3 |
Kotlin
|
0
| 2 |
97c184f5cc582125b7c72b4db5c13506844d83e5
| 1,821 |
connectedfueling-app-android
|
MIT License
|
src/template/template.kt
|
simpor
| 572,200,851 | false |
{"Kotlin": 80923}
|
package template
import AoCUtils.test
import java.io.File
fun main() {
fun part1(input: String, debug: Boolean = false): Long {
return 0
}
fun part2(input: String, debug: Boolean = false): Long {
return 0
}
val testInput = ""
val input =AoCUtils.readText( "Day05.txt")
part1(testInput) test Pair(0L, "test 1 part 1")
part1(input) test Pair(0L, "part 1")
part2(testInput) test Pair(0L, "test 2 part 2")
part2(input) test Pair(0L, "part 2")
}
| 0 |
Kotlin
|
0
| 0 |
631cbd22ca7bdfc8a5218c306402c19efd65330b
| 511 |
aoc-2022-kotlin
|
Apache License 2.0
|
react-router-dom-kotlin/src/main/kotlin/react/router/stripBasename.kt
|
karakum-team
| 393,199,102 | false | null |
// Automatically generated - do not modify!
@file:JsModule("react-router")
@file:JsNonModule
package react.router
external fun stripBasename(
pathname: String,
basename: String,
): String?
| 0 | null |
5
| 18 |
e71c43c0b93113ea0394025c3f40268cb7c66ca9
| 200 |
types-kotlin
|
Apache License 2.0
|
example/src/main/java/co/chocolatebiscuit/cartographer/example/ui/view/ScreenMain.kt
|
lewisevans
| 672,204,211 | false | null |
package co.chocolatebiscuit.cartographer.example.ui.view
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.rememberNavController
import co.chocolatebiscuit.cartographer.AppNavHost
import co.chocolatebiscuit.cartographer.example.ui.event.AppClickEvent
import co.chocolatebiscuit.cartographer.example.ui.theme.CartographerTheme
import co.chocolatebiscuit.cartographer.navigateToScreenBlue
import co.chocolatebiscuit.cartographer.navigateToScreenGreen
import co.chocolatebiscuit.cartographer.navigateToScreenRed
import co.chocolatebiscuit.cartographer.navigateToScreenSettings
@Composable
fun ScreenMain() {
val navController = rememberNavController()
Scaffold(
topBar = {
MainTopAppBar {
navController.navigateToScreenSettings()
}
},
bottomBar = {
MainBottomNavigation { appNavIem ->
when(appNavIem){
AppClickEvent.Blue -> navController.navigateToScreenBlue()
AppClickEvent.Green -> navController.navigateToScreenGreen("Green. This " +
"field is set using Cartographers generated" +
" NavController.navigateToScreenGreen('Hello World') method")
AppClickEvent.Red -> navController.navigateToScreenRed()
else -> {}
}
}
}
) {
AppNavHost(
modifier = Modifier.padding(it),
startDestination = "ScreenRed",
navController = navController
)
}
}
@Preview
@Composable
fun PreviewScreenMain() {
CartographerTheme {
ScreenMain()
}
}
| 0 |
Kotlin
|
0
| 2 |
6915196f894d4a35244e6e7ce21ac3a061bf6fcd
| 1,876 |
cartographer
|
Apache License 2.0
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/diagnosiskeys/download/KeyPackageSyncSettings.kt
|
grnet
| 314,517,742 | true |
{"Kotlin": 1737253, "HTML": 255998}
|
package de.rki.coronawarnapp.diagnosiskeys.download
import android.annotation.SuppressLint
import android.content.Context
import com.google.gson.Gson
import de.rki.coronawarnapp.util.di.AppContext
import de.rki.coronawarnapp.util.preferences.FlowPreference
import de.rki.coronawarnapp.util.preferences.clearAndNotify
import de.rki.coronawarnapp.util.serialization.BaseGson
import org.joda.time.Instant
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class KeyPackageSyncSettings @Inject constructor(
@AppContext private val context: Context,
@BaseGson private val gson: Gson
) {
private val prefs by lazy {
context.getSharedPreferences("keysync_localdata", Context.MODE_PRIVATE)
}
val lastDownloadDays = FlowPreference(
preferences = prefs,
key = "download.last.days",
reader = FlowPreference.gsonReader<LastDownload?>(gson, null),
writer = FlowPreference.gsonWriter(gson)
)
val lastDownloadHours = FlowPreference(
preferences = prefs,
key = "download.last.hours",
reader = FlowPreference.gsonReader<LastDownload?>(gson, null),
writer = FlowPreference.gsonWriter(gson)
)
@SuppressLint("ApplySharedPref")
fun clear() {
prefs.clearAndNotify()
}
data class LastDownload(
val startedAt: Instant,
val finishedAt: Instant? = null,
val successful: Boolean = false,
val newData: Boolean = false
)
}
| 0 |
Kotlin
|
0
| 0 |
7549397240489c860470dd780ecb96aa73a6c4d4
| 1,481 |
exo-app-android
|
Apache License 2.0
|
leitnerbox/view/splash/SplashFragment.kt
|
morync
| 198,999,267 | false | null |
package com.kecsot.leitnerbox.view.splash
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.kecsot.basekecsot.view.AbstractFragment
import com.kecsot.basekecsot.view.AbstractViewModel
import com.kecsot.leitnerbox.R
class SplashFragment : AbstractFragment() {
private lateinit var viewModel: SplashViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = AbstractViewModel.get(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_splash, container, false)
}
override fun onSubscribeViewModelObservables() {
viewModel.run {
onSplashLoadedPublishSubject.observe(this@SplashFragment, Observer {
navigateToMain()
})
}
}
private fun navigateToMain() {
val direction = SplashFragmentDirections.actionSplashFragmentToMainFragment()
navigation.navigate(direction)
}
override fun onStart() {
super.onStart()
hideActionBar()
viewModel.loadSplash()
}
}
| 0 |
Kotlin
|
0
| 0 |
7a05fb782936ec6d4832add38c6026b43762c373
| 1,288 |
Leitner-Box-Flashcard
|
MIT License
|
src/main/kotlin/net/polvott/etagtest/CountryService.kt
|
jankb
| 697,650,015 | false |
{"Kotlin": 8467, "JavaScript": 1715, "HTML": 567}
|
package net.polvott.etagtest
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
@Component
@Transactional
class CountryService {
fun findCountry(name: String): Country? {
return CountryEntity.select { CountryEntity.name eq name }.firstOrNull()?.let {
Country(
id = it[CountryEntity.id].value,
name = it[CountryEntity.name],
population = it[CountryEntity.population],)
}
}
fun getAllCountries(): List<Country>
{
return CountryEntity.selectAll().map {
Country(
id = it[CountryEntity.id].value,
name = it[CountryEntity.name],
population = it[CountryEntity.population]
)
}
}
fun create(request: CountryCreateRequest): Int
{
val id = CountryEntity.insertAndGetId {
it[name] = request.name
it[population] = request.population
}
return id.value
}
fun createCountries(request: CountriesCreateRequest): List<Country>
{
val countries = mutableListOf<Country>()
request.countries.forEach {
val id = create(it)
countries.add(Country(id, it.name, it.population))
}
return countries
}
}
data class CountryCreateRequest(
val name: String,
val population: Int
)
data class CountriesCreateRequest(
val countries: List<CountryCreateRequest>
)
| 0 |
Kotlin
|
0
| 0 |
531c1b25ecc13e86629a76a0109389eb0b66301d
| 1,689 |
etagtest
|
MIT License
|
src/main/kotlin/org/randomcat/agorabot/irc/IrcListener.kt
|
randomnetcat
| 291,139,813 | false |
{"Kotlin": 762592, "Nix": 17514}
|
package org.randomcat.agorabot.irc
import net.engio.mbassy.listener.Handler
import org.kitteh.irc.client.library.event.channel.ChannelCtcpEvent
import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent
interface IrcMessageHandler {
fun onMessage(event: ChannelMessageEvent) {}
fun onCtcpMessage(event: ChannelCtcpEvent) {}
}
class IrcListener(private val messageHandler: IrcMessageHandler) {
@Handler
fun onMessageReceived(event: ChannelMessageEvent) {
if (event.isSelfEvent()) return
messageHandler.onMessage(event)
}
@Handler
fun onCtcpMessageReceiver(event: ChannelCtcpEvent) {
if (event.isSelfEvent()) return
messageHandler.onCtcpMessage(event)
}
}
| 0 |
Kotlin
|
3
| 6 |
65fe511ebbe9ac5e76aa5ea88039f4e2454d3c66
| 734 |
AgoraBot
|
MIT License
|
src/main/kotlin/com/melonbase/microquark/microstream/StorageType.kt
|
belu
| 338,376,918 | false | null |
package com.melonbase.microquark.microstream
const val MEM = "mem"
const val FILESYSTEM = "filesystem"
const val JDBC = "jdbc"
const val MONGODB = "mongodb"
| 0 |
Kotlin
|
1
| 8 |
e358258e4024acbdca7d60ad3ee0990124045897
| 157 |
microquark
|
Apache License 2.0
|
src/main/kotlin/org/urielserv/uriel/packets/outgoing/rooms/user_unit/chat/RoomUnitChatWhisperPacket.kt
|
UrielHabboServer
| 729,131,075 | false |
{"Kotlin": 295010}
|
package org.urielserv.uriel.packets.outgoing.rooms.user_unit.chat
import org.urielserv.uriel.game.rooms.chat.RoomChatMessage
import org.urielserv.uriel.packets.outgoing.Outgoing
import org.urielserv.uriel.packets.outgoing.Packet
class RoomUnitChatPacket(
private val roomChatMessage: RoomChatMessage
) : Packet() {
override val packetId = Outgoing.RoomUnitChat
override suspend fun construct() {
appendInt(roomChatMessage.habbo.roomUnit!!.id)
appendString(roomChatMessage.message)
appendInt(roomChatMessage.emotionId)
appendInt(roomChatMessage.bubble.nitroStyleId)
appendInt(0)
appendInt(roomChatMessage.message.length)
}
}
| 0 |
Kotlin
|
0
| 7 |
cf1cac139d001d3ccce34d633b5f9040280281e8
| 692 |
Uriel
|
MIT License
|
android/app/src/main/java/com/kaelesty/audionautica/data/local/daos/TrackDao.kt
|
Kaelesty
| 698,507,418 | false |
{"Kotlin": 148860, "Python": 28535, "JavaScript": 12919, "CSS": 4730, "HTML": 231}
|
package com.kaelesty.audionautica.data.local.daos
import androidx.lifecycle.LiveData
import androidx.media3.extractor.mp4.Track
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.kaelesty.audionautica.data.local.dbmodels.TrackDbModel
import com.kaelesty.audionautica.domain.entities.Playlist
import kotlinx.coroutines.flow.SharedFlow
import java.util.concurrent.Flow
@Dao
interface TrackDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun createTrack(track: TrackDbModel)
@Query("SELECT * FROM `tracks-`")
fun getAll(): LiveData<List<TrackDbModel>>
@Query("SELECT * FROM `tracks-` WHERE id IN (:ids)")
fun getById(ids: List<Int>): List<TrackDbModel>
@Query("DELETE FROM `tracks-`WHERE id = :id")
fun deleteTrack(id: Int)
}
| 0 |
Kotlin
|
1
| 0 |
51d50889933385c42958ac89d6a9938d482cb7a1
| 822 |
project-audionautica
|
The Unlicense
|
app/src/main/java/com/example/meetexpress/TakePartEventsFragment.kt
|
micwiccode
| 217,919,016 | false | null |
package com.example.meetexpress
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.QuerySnapshot
import kotlinx.android.synthetic.main.fragment_find_event.*
import kotlinx.android.synthetic.main.fragment_take_part_events.*
class TakePartEventsFragment : Fragment() {
val db = FirebaseFirestore.getInstance()
lateinit var recyclerView: RecyclerView
lateinit var adapter: TakePartRecycleAdapter
private lateinit var auth: FirebaseAuth
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val layout = inflater.inflate(R.layout.fragment_take_part_events, container, false)
auth = FirebaseAuth.getInstance()
recyclerView = layout.findViewById(R.id.recycleView)
recyclerView.layoutManager = LinearLayoutManager(activity?.applicationContext, RecyclerView.VERTICAL, false)
fetch()
return layout
}
private fun fetch() {
val query = db.collection("events").whereArrayContains("profiles", auth.currentUser!!.uid)
query.addSnapshotListener(object: EventListener<QuerySnapshot> {
override fun onEvent(p0: QuerySnapshot?, p1: FirebaseFirestoreException?) {
if(p0!=null){
if(spin_kit_take_part!=null){
spin_kit_take_part.visibility = View.GONE
}
if(p0.isEmpty){
if(empty_take_part!=null){
empty_take_part.visibility = View.VISIBLE
}
recyclerView.visibility = View.GONE
}
else{
if(empty_take_part!=null){
empty_take_part.visibility = View.GONE
}
recyclerView.visibility = View.VISIBLE
}
}
}
})
val options = FirestoreRecyclerOptions.Builder<Event>()
.setQuery(
query, Event::class.java)
.build()
adapter = TakePartRecycleAdapter(options)
recyclerView.adapter = adapter
}
override fun onStart() {
super.onStart()
adapter.startListening()
}
override fun onStop() {
super.onStop()
adapter.stopListening()
}
}
| 1 |
Kotlin
|
0
| 0 |
ca6fb02e6c832950169fabb470463fc56dcf7f73
| 2,923 |
meetexpress_android_app
|
MIT License
|
relateddigital-android/src/main/java/com/relateddigital/relateddigital_android/model/GeofenceListReponse.kt
|
relateddigital
| 379,568,070 | false | null |
package com.relateddigital.relateddigital_google.model
import com.google.gson.annotations.SerializedName
class GeofenceListResponse {
@SerializedName("actid")
var actId: Int? = null
@SerializedName("dis")
var distance: Int? = null
@SerializedName("geo")
private var mGeofences: List<Geofence>? = null
@SerializedName("trgevt")
var trgevt: String? = null
var geofences: List<Geofence>?
get() = mGeofences
set(geofences) {
mGeofences = geofences
}
}
| 0 | null |
2
| 6 |
0a697cc61923fabc4833d8e4cee5f00af951bfe6
| 525 |
relateddigital-android
|
Amazon Digital Services License
|
app/src/main/java/com/harunkor/motionmonitorapp/di/SensorModule.kt
|
harunkor
| 507,013,101 | false | null |
package com.harunkor.motionmonitorapp.di
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import com.harunkor.motionmonitorapp.domain.usecase.SensorUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.FragmentComponent
import dagger.hilt.android.qualifiers.ActivityContext
import dagger.hilt.android.scopes.FragmentScoped
@InstallIn(FragmentComponent::class)
@Module
class SensorModule {
@Provides
@FragmentScoped
fun provideSensorManager(@ActivityContext context: Context): SensorManager {
return context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
@Provides
@FragmentScoped
fun provideSensor(sensorManager: SensorManager): Sensor {
return sensorManager.getDefaultSensor(Sensor.TYPE_ALL)
}
@Provides
@FragmentScoped
fun provideSensorEventListener(sensorManager: SensorManager, sensor: Sensor): SensorUseCase {
return SensorUseCase(sensor, sensorManager)
}
}
| 0 |
Kotlin
|
0
| 1 |
1fc0c8ff860a8f6ce40febe0235ddf4fb33c8877
| 1,073 |
MotionMonitorIceHockeyApp
|
The Unlicense
|
src/main/java/moe/taiho/minijaba/ast/AssignStmt.kt
|
swordfeng
| 115,345,822 | false | null |
package moe.taiho.minijaba.ast
class AssignStmt(var ident: String, var value: Exp) : Stmt()
| 0 |
Kotlin
|
1
| 4 |
0ba472f11ef99d8711a039be359c787a87d4e13d
| 93 |
MiniJaba
|
Do What The F*ck You Want To Public License
|
pensjon-brevbaker-api-model/src/main/kotlin/no/nav/pensjon/brev/api/model/maler/ForhaandsvarselEtteroppgjoerUfoeretrygd.kt
|
navikt
| 375,334,697 | false | null |
package no.nav.pensjon.brev.api.model.maler
import no.nav.pensjon.brev.api.model.vedlegg.OpplysningerOmEtteroppgjoeretDto
import no.nav.pensjon.brev.api.model.vedlegg.OrienteringOmRettigheterUfoereDto
import no.nav.pensjon.brevbaker.api.model.Kroner
@Suppress("unused")
data class ForhaandsvarselEtteroppgjoerUfoeretrygdDto(
val erNyttEtteroppgjoer: Boolean,
val oppjustertInntektFoerUfoerhet: Kroner,
val harTjentOver80prosentAvOIFU: Boolean,
val kanSoekeOmNyInntektsgrense: Boolean,
val opplysningerOmEtteroppgjoret: OpplysningerOmEtteroppgjoeretDto,
val orienteringOmRettigheterUfoereDto: OrienteringOmRettigheterUfoereDto,
)
| 9 | null |
3
| 1 |
30b5f694339e4ce121ffaacee4666b88f644867c
| 654 |
pensjonsbrev
|
MIT License
|
app/src/main/java/com/otsembo/kimondo/ui/auth/register/RegisterFragment.kt
|
otsembo
| 537,159,931 | false |
{"Kotlin": 44986}
|
package com.otsembo.kimondo.ui.auth.register
class RegisterFragment {
}
| 0 |
Kotlin
|
0
| 0 |
5bd277ab8f88c432589528b78d233746947771e8
| 72 |
Kimondo
|
Apache License 1.1
|
src/main/kotlin/me/rafaelldi/aspire/sessionHost/SessionLauncher.kt
|
rafaelldi
| 723,084,178 | false |
{"Kotlin": 230225, "C#": 125486}
|
package me.rafaelldi.aspire.sessionHost
import com.intellij.execution.DefaultExecutionResult
import com.intellij.execution.process.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.jetbrains.rd.framework.*
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.isNotAlive
import com.jetbrains.rd.util.put
import com.jetbrains.rd.util.threading.coroutines.nextTrueValueAsync
import com.jetbrains.rdclient.protocol.RdDispatcher
import com.jetbrains.rider.RiderEnvironment.createRunCmdForLauncherInfo
import com.jetbrains.rider.debugger.DebuggerWorkerProcessHandler
import com.jetbrains.rider.debugger.RiderDebuggerWorkerModelManager
import com.jetbrains.rider.debugger.createAndStartSession
import com.jetbrains.rider.debugger.targets.DEBUGGER_WORKER_LAUNCHER
import com.jetbrains.rider.model.debuggerWorker.*
import com.jetbrains.rider.model.debuggerWorkerConnectionHelperModel
import com.jetbrains.rider.projectView.solution
import com.jetbrains.rider.run.*
import com.jetbrains.rider.run.configurations.RunnableProjectKinds
import com.jetbrains.rider.runtime.DotNetExecutable
import com.jetbrains.rider.runtime.DotNetRuntime
import com.jetbrains.rider.runtime.RiderDotNetActiveRuntimeHost
import com.jetbrains.rider.runtime.dotNetCore.DotNetCoreRuntime
import com.jetbrains.rider.util.NetUtils
import icons.RiderIcons
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.withContext
import me.rafaelldi.aspire.generated.SessionModel
import me.rafaelldi.aspire.generated.SessionUpsertResult
import me.rafaelldi.aspire.util.decodeAnsiCommandsToString
import org.jetbrains.annotations.Nls
import kotlin.io.path.Path
import kotlin.io.path.nameWithoutExtension
@Service(Service.Level.PROJECT)
class AspireSessionLauncher(private val project: Project) {
companion object {
fun getInstance(project: Project) = project.service<AspireSessionLauncher>()
private val LOG = logger<AspireSessionLauncher>()
}
suspend fun launchSession(
sessionId: String,
sessionModel: SessionModel,
sessionLifetime: Lifetime,
sessionEvents: MutableSharedFlow<AspireSessionEvent>,
isHostDebug: Boolean,
openTelemetryPort: Int
): SessionUpsertResult? {
LOG.info("Starting a session for the project ${sessionModel.projectPath}")
if (sessionLifetime.isNotAlive) {
LOG.warn("Unable to run project ${sessionModel.projectPath} because lifetimes are not alive")
return null
}
val factory = SessionExecutableFactory.getInstance(project)
val executable = factory.createExecutable(sessionModel, openTelemetryPort)
if (executable == null) {
LOG.warn("Unable to create executable for $sessionId (project: ${sessionModel.projectPath})")
return null
}
val runtime = DotNetRuntime.detectRuntimeForProject(
project,
RunnableProjectKinds.DotNetCore,
RiderDotNetActiveRuntimeHost.getInstance(project),
executable.runtimeType,
executable.exePath,
executable.projectTfm
)?.runtime as? DotNetCoreRuntime
if (runtime == null) {
LOG.warn("Unable to detect runtime for $sessionId (project: ${sessionModel.projectPath})")
return null
}
val isDebug = isHostDebug || sessionModel.debug
if (isDebug) {
launchDebugSession(
sessionId,
Path(sessionModel.projectPath).nameWithoutExtension,
executable,
runtime,
sessionLifetime,
sessionEvents
)
} else {
launchRunSession(
sessionId,
executable,
runtime,
sessionLifetime,
sessionEvents
)
}
return SessionUpsertResult(sessionId)
}
private fun launchRunSession(
sessionId: String,
executable: DotNetExecutable,
runtime: DotNetCoreRuntime,
sessionLifetime: Lifetime,
sessionEvents: MutableSharedFlow<AspireSessionEvent>
) {
val commandLine = executable.createRunCommandLine(runtime)
val handler = KillableProcessHandler(commandLine)
subscribeToSessionEvents(sessionId, handler, sessionEvents)
sessionLifetime.onTermination {
if (!handler.isProcessTerminating && !handler.isProcessTerminated) {
LOG.trace("Killing session process (id: $sessionId)")
handler.destroyProcess()
}
}
handler.startNotify()
}
private suspend fun launchDebugSession(
sessionId: String,
@Nls sessionName: String,
executable: DotNetExecutable,
runtime: DotNetCoreRuntime,
sessionLifetime: Lifetime,
sessionEvents: MutableSharedFlow<AspireSessionEvent>
) {
val startInfo = DotNetCoreExeStartInfo(
DotNetCoreInfo(runtime.cliExePath),
executable.projectTfm?.let { EncInfo(it) },
executable.exePath,
executable.workingDirectory,
executable.programParameterString,
executable.environmentVariables.toModelMap,
executable.runtimeArguments,
executable.executeAsIs,
executable.useExternalConsole
)
withContext(Dispatchers.EDT) {
createAndStartDebugSession(
sessionId,
sessionName,
startInfo,
sessionEvents,
sessionLifetime
)
}
}
private suspend fun createAndStartDebugSession(
sessionId: String,
@Nls sessionName: String,
startInfo: DebuggerStartInfoBase,
sessionEvents: MutableSharedFlow<AspireSessionEvent>,
lifetime: Lifetime
) {
val frontendToDebuggerPort = NetUtils.findFreePort(67700)
val backendToDebuggerPort = NetUtils.findFreePort(87700)
val lifetimeDefinition = lifetime.createNested()
val dispatcher = RdDispatcher(lifetimeDefinition)
val wire = SocketWire.Server(
lifetimeDefinition,
dispatcher,
port = frontendToDebuggerPort,
optId = "FrontendToDebugWorker"
)
val protocol = Protocol(
"FrontendToDebuggerWorker",
Serializers(),
Identities(IdKind.Client),
dispatcher,
wire,
lifetimeDefinition
)
val workerModel = RiderDebuggerWorkerModelManager.createDebuggerModel(lifetimeDefinition, protocol)
val debuggerWorkerProcessHandler = createDebuggerWorkerProcessHandler(
sessionId,
frontendToDebuggerPort,
backendToDebuggerPort,
workerModel,
lifetimeDefinition.lifetime
)
subscribeToSessionEvents(
sessionId,
debuggerWorkerProcessHandler.debuggerWorkerRealHandler,
sessionEvents
)
val debuggerSessionId = ExecutionEnvironment.getNextUnusedExecutionId()
project.solution.debuggerWorkerConnectionHelperModel.ports.put(
lifetimeDefinition,
debuggerSessionId,
backendToDebuggerPort
)
wire.connected.nextTrueValueAsync(lifetimeDefinition.lifetime).await()
val sessionModel = DotNetDebuggerSessionModel(startInfo)
sessionModel.sessionProperties.bindToSettings(lifetimeDefinition, project).apply {
debugKind.set(DebugKind.Live)
remoteDebug.set(false)
enableHeuristicPathResolve.set(false)
editAndContinueEnabled.set(true)
}
workerModel.activeSession.set(sessionModel)
val console = createConsole(
ConsoleKind.Normal,
debuggerWorkerProcessHandler.debuggerWorkerRealHandler,
project
)
val executionResult = DefaultExecutionResult(console, debuggerWorkerProcessHandler)
createAndStartSession(
executionResult.executionConsole,
null,
project,
lifetimeDefinition.lifetime,
executionResult.processHandler,
protocol,
sessionModel,
object : IDebuggerOutputListener {},
debuggerSessionId
) { xDebuggerManager, xDebugProcessStarter ->
xDebuggerManager.startSessionAndShowTab(
sessionName,
RiderIcons.RunConfigurations.DotNetProject,
null,
false,
xDebugProcessStarter
)
}
}
private fun createDebuggerWorkerProcessHandler(
sessionId: String,
frontendToDebuggerPort: Int,
backendToDebuggerPort: Int,
workerModel: DebuggerWorkerModel,
sessionLifetime: Lifetime
): DebuggerWorkerProcessHandler {
val launcher = DEBUGGER_WORKER_LAUNCHER.getLauncher()
val commandLine = createRunCmdForLauncherInfo(
launcher,
"--mode=client",
"--frontend-port=${frontendToDebuggerPort}",
"--backend-port=${backendToDebuggerPort}"
)
val handler = TerminalProcessHandler(project, commandLine, commandLine.commandLineString, false)
sessionLifetime.onTermination {
if (!handler.isProcessTerminating && !handler.isProcessTerminated) {
LOG.trace("Killing session process (id: $sessionId)")
handler.killProcess()
}
}
val debuggerWorkerProcessHandler = DebuggerWorkerProcessHandler(
handler,
workerModel,
false,
commandLine.commandLineString,
sessionLifetime
)
return debuggerWorkerProcessHandler
}
private fun subscribeToSessionEvents(
sessionId: String,
handler: ProcessHandler,
sessionEvents: MutableSharedFlow<AspireSessionEvent>
) {
handler.addProcessListener(object : ProcessAdapter() {
override fun startNotified(event: ProcessEvent) {
LOG.info("Aspire session process started (id: $sessionId)")
val pid = when (event.processHandler) {
is KillableProcessHandler -> event.processHandler.pid()
else -> null
}
if (pid == null) {
LOG.warn("Unable to determine process id for the session $sessionId")
sessionEvents.tryEmit(AspireSessionTerminated(sessionId, -1))
} else {
sessionEvents.tryEmit(AspireSessionStarted(sessionId, pid))
}
}
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
val text = decodeAnsiCommandsToString(event.text, outputType)
val isStdErr = outputType == ProcessOutputType.STDERR
sessionEvents.tryEmit(AspireSessionLogReceived(sessionId, isStdErr, text))
}
override fun processTerminated(event: ProcessEvent) {
LOG.info("Aspire session process terminated (id: $sessionId)")
sessionEvents.tryEmit(AspireSessionTerminated(sessionId, event.exitCode))
}
override fun processNotStarted() {
LOG.warn("Aspire session process is not started")
sessionEvents.tryEmit(AspireSessionTerminated(sessionId, -1))
}
})
}
}
| 8 |
Kotlin
|
1
| 43 |
4287a80ce6dda39b1bb501cc9d38b9c70b27bf7a
| 11,964 |
aspire-plugin
|
MIT License
|
reaktive/src/commonTest/kotlin/com/badoo/reaktive/observable/TakeObservableTests.kt
|
badoo
| 174,194,386 | false | null |
package com.badoo.reaktive.observable
import com.badoo.reaktive.test.base.assertError
import com.badoo.reaktive.test.observable.TestObservable
import com.badoo.reaktive.test.observable.assertComplete
import com.badoo.reaktive.test.observable.assertNotComplete
import com.badoo.reaktive.test.observable.assertValue
import com.badoo.reaktive.test.observable.assertValues
import com.badoo.reaktive.test.observable.onNext
import com.badoo.reaktive.test.observable.test
import kotlin.test.Test
import kotlin.test.assertFailsWith
class TakeObservableTests :
ObservableToObservableTests by ObservableToObservableTests<Unit>({ take(1) }) {
private val upstream = TestObservable<Int?>()
private val observer = upstream.take(10).test()
@Test
fun completes_WHEN_limit_of_0_is_reached() {
val observer = upstream.take(0).test()
observer.assertComplete()
}
@Test
fun completes_WHEN_limit_of_1_is_reached() {
val observer = upstream.take(1).test()
upstream.onNext(42)
observer.assertComplete()
}
@Test
fun completes_WHEN_limit_of_2_is_reached() {
val observer = upstream.take(2).test()
upstream.onNext(42)
upstream.onNext(84)
observer.assertComplete()
}
@Test
fun does_not_complete_until_take_limit_is_reached() {
val observer = upstream.take(2).test()
upstream.onNext(42)
observer.assertNotComplete()
upstream.onNext(84)
observer.assertComplete()
}
@Test
fun completes_WHEN_upstream_completed() {
upstream.onComplete()
observer.assertComplete()
}
@Test
fun produces_same_error_WHEN_upstream_produced_error() {
val error = Exception()
upstream.onError(error)
observer.assertError(error)
}
@Test
fun produces_values_in_correct_order_from_upstream() {
upstream.onNext(42, null, 84, null)
observer.assertValues(42, null, 84, null)
}
@Test
fun counts_recursive_invocations() {
val observer = upstream
.take(1)
.let { source ->
observableUnsafe<Int?> { observer ->
source.subscribe(
object : ObservableObserver<Int?> by observer {
override fun onNext(value: Int?) {
upstream.onNext(48)
observer.onNext(value)
}
}
)
}
}
.test()
upstream.onNext(42)
observer.assertValue(42)
}
@Test
fun throws_error_when_take_is_called_with_a_limit_less_than_0() {
assertFailsWith<IllegalArgumentException> {
upstream.take(-2)
}
}
}
| 8 | null |
49
| 956 |
c712c70be2493956e7057f0f30199994571b3670
| 2,847 |
Reaktive
|
Apache License 2.0
|
graphql-dgs-codegen-core/src/integTest/kotlin/com/netflix/graphql/dgs/codegen/cases/dataClassWithMappedTypes/expected/client/EntityProjection.kt
|
Netflix
| 317,379,776 | false |
{"Kotlin": 1149646, "Python": 7680, "Java": 5969, "Makefile": 982, "Dockerfile": 246}
|
package com.netflix.graphql.dgs.codegen.cases.dataClassWithMappedTypes.expected.client
import com.netflix.graphql.dgs.codegen.GraphQLProjection
public class EntityProjection : GraphQLProjection() {
public val long: EntityProjection
get() {
field("long")
return this
}
public val dateTime: EntityProjection
get() {
field("dateTime")
return this
}
}
| 81 |
Kotlin
|
90
| 167 |
9161bc9ea648b96eae509ce62d32d7c66034647a
| 395 |
dgs-codegen
|
Apache License 2.0
|
app/src/main/java/com/suyash/creditmanager/domain/use_case/credit_card/AddCreditCard.kt
|
suyash01
| 732,788,266 | false |
{"Kotlin": 282293}
|
package com.suyash.creditmanager.domain.use_case.credit_card
import com.suyash.creditmanager.domain.model.CreditCard
import com.suyash.creditmanager.domain.repository.CreditCardRepository
class AddCreditCard(private val repository: CreditCardRepository) {
suspend operator fun invoke(creditCard: CreditCard): Long {
return repository.upsertCreditCard(creditCard)
}
}
| 0 |
Kotlin
|
0
| 0 |
ea4bcd5c53d1b66c54ba144d0772378c5b4f566e
| 385 |
credit-manager
|
Apache License 2.0
|
packages/graalvm/src/main/kotlin/elide/runtime/gvm/cfg/GuestIOConfiguration.kt
|
elide-dev
| 506,113,888 | false | null |
package elide.runtime.gvm.cfg
import elide.runtime.gvm.cfg.GuestIOConfiguration.Mode
import elide.runtime.gvm.internals.vfs.AbstractBaseVFS
import elide.runtime.gvm.internals.vfs.GuestVFSPolicy
import io.micronaut.context.annotation.ConfigurationProperties
import io.micronaut.core.util.Toggleable
/**
* Micronaut configuration for the guest VM virtual file-system (VFS).
*
* @param enabled Whether to enable I/O support for guest VMs at all.
* @param bundle Path to the VFS bundle to use for guest VMs, as applicable.
* @param policy Security policies to apply to guest I/O operations. If none is provided, sensible defaults are used.
* @param mode Base operating mode for I/O - options are [Mode.GUEST] (virtualized), [Mode.CLASSPATH] (guest + access to
* host app classpath), or [Mode.HOST] (full access to host machine I/O).
* @param caseSensitive Whether to treat the file-system as case sensitive. Defaults to `true`.
* @param symlinks Whether to enable (or expect) symbolic link support. Defaults to `true`.
* @param root Root path for the file-system. Defaults to `/`.
* @param workingDirectory Working directory to initialize the VFS with, as applicable. Defaults to `/`.
*/
@Suppress("MemberVisibilityCanBePrivate")
@ConfigurationProperties("elide.gvm.vfs")
internal class GuestIOConfiguration(
var enabled: Boolean = DEFAULT_ENABLED,
var bundle: String? = null,
var policy: GuestVFSPolicy = DEFAULT_POLICY,
var mode: Mode? = DEFAULT_MODE,
var caseSensitive: Boolean = DEFAULT_CASE_SENSITIVE,
var symlinks: Boolean = DEFAULT_SYMLINKS,
var root: String = DEFAULT_ROOT,
var workingDirectory: String = DEFAULT_WORKING_DIRECTORY,
) : Toggleable {
/** Enumerates supported operating modes for VM guest I/O. */
@Suppress("unused") public enum class Mode {
/** Virtualized I/O operations via a guest file-system. */
GUEST,
/** Access to resources from the host app classpath. */
CLASSPATH,
/** Access to host I/O (i.e. regular I/O on the host machine). */
HOST,
}
internal companion object {
/** Default enablement status. */
const val DEFAULT_ENABLED: Boolean = true
/** Default case-sensitivity status. */
const val DEFAULT_CASE_SENSITIVE: Boolean = true
/** Default symbolic links enablement status. */
const val DEFAULT_SYMLINKS: Boolean = true
/** Default root path. */
const val DEFAULT_ROOT: String = AbstractBaseVFS.ROOT_SYSTEM_DEFAULT
/** Default working directory path. */
const val DEFAULT_WORKING_DIRECTORY: String = AbstractBaseVFS.DEFAULT_CWD
/** Default policy to apply if none is specified. */
val DEFAULT_POLICY = GuestVFSPolicy.DEFAULTS
/** Default operating mode. */
val DEFAULT_MODE: Mode = Mode.GUEST
}
}
| 36 |
Kotlin
|
4
| 33 |
91800dbbf291e65a91d451ed50c9673d82efd174
| 2,760 |
elide
|
MIT License
|
app/src/main/java/top/xjunz/tasker/ui/task/selector/AppletOptionClickHandler.kt
|
xjunz
| 651,527,105 | false |
{"Kotlin": 1063774, "Java": 386865, "HTML": 67262, "C": 29461, "JavaScript": 16670, "C++": 12159, "AIDL": 4190, "CMake": 1764}
|
/*
* Copyright (c) 2022 xjunz. All rights reserved.
*/
package top.xjunz.tasker.ui.task.selector
import androidx.fragment.app.FragmentManager
import top.xjunz.tasker.engine.applet.base.Applet
import top.xjunz.tasker.engine.applet.criterion.Criterion
import top.xjunz.tasker.engine.applet.util.isAttached
import top.xjunz.tasker.ktx.show
import top.xjunz.tasker.task.applet.option.AppletOption
import top.xjunz.tasker.task.applet.option.AppletOptionFactory
import top.xjunz.tasker.ui.task.selector.argument.ArgumentsEditorDialog
/**
* @author xjunz 2022/10/08
*/
open class AppletOptionClickHandler(private val fragmentManager: FragmentManager) {
private val factory = AppletOptionFactory
fun onClick(applet: Applet, onCompleted: () -> Unit) {
onClick(applet, factory.requireOption(applet), onCompleted)
}
open fun onClick(applet: Applet, option: AppletOption, onCompleted: () -> Unit) {
when {
option.arguments.isNotEmpty() -> ArgumentsEditorDialog()
.setAppletOption(applet, option)
.doOnCompletion(onCompleted).show(fragmentManager)
applet is Criterion<*, *> -> {
if (applet.isAttached && applet.isInvertible) applet.toggleInversion()
onCompleted()
}
else -> onCompleted()
}
}
}
| 0 |
Kotlin
|
6
| 23 |
82893d0db2b13e12d8bee86b4cae0f16abd0e2f4
| 1,348 |
AutoTask
|
Apache License 2.0
|
app/src/main/java/com/fridaytech/dex/data/manager/fee/FeeRateProvider.kt
|
5daytech
| 198,758,400 | false | null |
package com.fridaytech.dex.data.manager.fee
import android.content.Context
import com.fridaytech.dex.core.IAppConfiguration
import com.fridaytech.dex.data.adapter.FeeRatePriority
import com.fridaytech.dex.data.adapter.FeeRatePriority.*
import io.horizontalsystems.feeratekit.Coin
import io.horizontalsystems.feeratekit.FeeRate
import io.horizontalsystems.feeratekit.FeeRateKit
import java.util.*
class FeeRateProvider(
context: Context,
appConfiguration: IAppConfiguration
) : IFeeRateProvider, FeeRateKit.Listener {
private val feeRateKit = FeeRateKit(
appConfiguration.infuraProjectId,
appConfiguration.infuraProjectSecret,
context,
this
).apply { refresh() }
private val etherFeeRates = FeeRate(
Coin.ETHEREUM,
4_000_000_000,
60 * 30,
8_000_000_000,
60 * 5,
20_000_000_000,
60 * 2,
date = Date().time)
override fun ethereumGasPrice(priority: FeeRatePriority): Long = feeRate(etherFeeRates, priority)
override fun onRefresh(rates: List<FeeRate>) {
}
private fun feeRate(feeRate: FeeRate, priority: FeeRatePriority): Long = when (priority) {
LOWEST -> feeRate.lowPriority
LOW -> (feeRate.lowPriority + feeRate.mediumPriority) / 2
MEDIUM -> feeRate.mediumPriority
HIGH -> (feeRate.mediumPriority + feeRate.highPriority) / 2
HIGHEST -> feeRate.highPriority
}
}
| 0 |
Kotlin
|
13
| 21 |
50200c97a9a7a456b588cf132fdb901141efb1d1
| 1,444 |
udex-app-android
|
MIT License
|
features/networking/networking-panes/src/commonMain/kotlin/com/paligot/confily/networking/panes/EmptyContactsScreen.kt
|
GerardPaligot
| 444,230,272 | false |
{"Kotlin": 897920, "Swift": 126158, "Shell": 1148, "Dockerfile": 576, "HTML": 338, "CSS": 102}
|
package com.paligot.confily.networking.panes
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.paligot.confily.resources.Resource
import com.paligot.confily.resources.text_empty_contacts
import org.jetbrains.compose.resources.stringResource
@Composable
fun EmptyContactsScreen(modifier: Modifier = Modifier) {
Column(
modifier = modifier
.fillMaxSize()
.padding(vertical = 24.dp, horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(24.dp)
) {
Text(
text = stringResource(Resource.string.text_empty_contacts)
)
}
}
| 9 |
Kotlin
|
6
| 143 |
8c0985b73422d6b388012d79c7ab33c054dc55c1
| 929 |
Confily
|
Apache License 2.0
|
transport-eta-android/data-sharedpreferences/src/test/java/com/joaquimley/transporteta/sharedpreferences/factory/SharedPrefTransportFactory.kt
|
JoaquimLey
| 93,657,822 | false | null |
package com.joaquimley.transporteta.sharedpreferences.factory
import com.joaquimley.transporteta.sharedpreferences.factory.SharedPrefDataFactory.Factory.randomInt
import com.joaquimley.transporteta.sharedpreferences.factory.SharedPrefDataFactory.Factory.randomUuid
import com.joaquimley.transporteta.data.model.TransportEntity
import com.joaquimley.transporteta.sharedpreferences.FrameworkLocalStorageImpl
import com.joaquimley.transporteta.sharedpreferences.model.SharedPrefTransport
/**
* Factory class for [SharedPrefTransport] related instances
*/
class SharedPrefTransportFactory {
companion object Factory {
fun makeSharedPrefTransportList(count: Int, isFavorite: Boolean = false, type: String = randomUuid()): List<SharedPrefTransport> {
val transports = mutableListOf<SharedPrefTransport>()
repeat(count) {
transports.add(makeSharedPrefTransport(isFavorite, type))
}
return transports
}
fun makeSharedPrefTransport(isFavorite: Boolean = false, type: String = "bus", code: Int = randomInt(), id: String = randomUuid(), slot: FrameworkLocalStorageImpl.Slot = FrameworkLocalStorageImpl.Slot.SAVE_SLOT_ONE): SharedPrefTransport {
return SharedPrefTransport(id, randomUuid(), code, randomUuid(), isFavorite, type, randomUuid(), slot)
}
fun makeSharedPrefTransportString(id: String = randomUuid(), transportName: String = randomUuid(), code: Int = randomInt(), latestEta: String = randomUuid(), isFavorite: Boolean = true, type: String = "bus", lastUpdated: String = randomUuid(), slot: String = FrameworkLocalStorageImpl.Slot.SAVE_SLOT_ONE.name): String {
return "{\"id\":\"$id\",\"name\":\"$transportName\",\"code\":$code,\"latestEta\":\"$latestEta\",\"isFavorite\":$isFavorite,\"type\":\"$type\",\"lastUpdated\":\"$lastUpdated\",\"slot\":\"$slot\"}"
}
fun makeTransportEntityList(count: Int, isFavorite: Boolean = false, type: String = randomUuid()): List<TransportEntity> {
val transports = mutableListOf<TransportEntity>()
repeat(count) {
transports.add(makeTransportEntity(isFavorite, type))
}
return transports
}
fun makeTransportEntity(isFavorite: Boolean = false, type: String = randomUuid(), code: Int = randomInt(), id: String = randomUuid()): TransportEntity {
return TransportEntity(id, randomUuid(), code, randomUuid(), isFavorite, type)
}
}
}
| 34 |
Kotlin
|
45
| 224 |
7c841a3b4e7f296e5b5e53eab6c7a9e84c2b3c61
| 2,531 |
transport-eta
|
Apache License 2.0
|
shared/src/commonMain/kotlin/datasource/PokemonDataSource.kt
|
ThomasBerthier
| 753,705,683 | false |
{"Kotlin": 28769, "Swift": 580, "Shell": 228}
|
package datasource
import androidx.compose.ui.graphics.ImageBitmap
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
import network.data.Limit
import network.data.Pokemon
class PokemonDataSource {
private val httpClient = HttpClient {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json, // because Github is not returning an 'application/json' header
json = Json {
ignoreUnknownKeys = true
useAlternativeNames = false
prettyPrint = true
})
}
}
suspend fun getAllPokemons(): Limit {
return httpClient.get("https://pokeapi.co/api/v2/pokemon/?limit=25").body<Limit>()
}
suspend fun getOnePokemon(pokemonName:String): Pokemon {
return httpClient.get("https://pokeapi.co/api/v2/pokemon/${pokemonName}").body<Pokemon>()
}
}
| 0 |
Kotlin
|
0
| 0 |
514e92c0c3068eed03229e73e716c9ea5af270b0
| 1,161 |
Kotlin
|
Apache License 2.0
|
core/src/main/kotlin/dev/sanmer/pi/bundle/SplitConfig.kt
|
SanmerApps
| 720,492,308 | false | null |
package dev.sanmer.pi.bundle
import android.content.pm.PackageParser
import android.os.Parcelable
import android.text.format.Formatter
import dev.sanmer.pi.ContextCompat
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import java.io.File
import java.util.Locale
sealed class SplitConfig : Parcelable {
abstract val file: File
abstract val name: String
abstract val configForSplit: String?
abstract val isRequired: Boolean
abstract val isDisabled: Boolean
abstract val isRecommended: Boolean
val displaySize: String
get() = Formatter.formatFileSize(ContextCompat.getContext(), file.length())
val isConfigForSplit: Boolean
inline get() = !configForSplit.isNullOrEmpty()
override fun toString(): String {
return "name = ${name}, " +
"required = ${isRequired}, " +
"disabled = ${isDisabled}, " +
"recommended = $isRecommended"
}
@Parcelize
data class Target(
val abi: ABI,
override val configForSplit: String?,
override val file: File
) : SplitConfig() {
@IgnoredOnParcel
override val name by lazy { abi.displayName }
@IgnoredOnParcel
override val isRequired by lazy { abi.isRequired }
@IgnoredOnParcel
override val isDisabled by lazy { !abi.isEnabled }
override val isRecommended get() = isRequired
}
@Parcelize
data class Density(
val dpi: DPI,
override val configForSplit: String?,
override val file: File
) : SplitConfig() {
override val name get() = dpi.displayName
@IgnoredOnParcel
override val isRequired by lazy { dpi.isRequired }
override val isDisabled get() = false
override val isRecommended get() = isRequired
}
@Parcelize
data class Language(
val locale: Locale,
override val configForSplit: String?,
override val file: File
) : SplitConfig() {
override val name get() = locale.localizedDisplayName
@IgnoredOnParcel
override val isRequired by lazy { locale.language == Locale.getDefault().language }
@IgnoredOnParcel
override val isDisabled by lazy { locale !in Locale.getAvailableLocales() }
override val isRecommended get() = isRequired
}
@Parcelize
data class Feature(
override val name: String,
override val file: File,
) : SplitConfig() {
override val configForSplit get() = null
override val isRequired get() = false
override val isDisabled get() = false
override val isRecommended get() = true
}
@Parcelize
data class Unspecified(
override val configForSplit: String?,
override val file: File,
) : SplitConfig() {
override val name get() = file.name
override val isRequired get() = false
override val isDisabled get() = false
override val isRecommended get() = true
}
companion object Default {
private val Locale.localizedDisplayName: String
inline get() = getDisplayName(this)
.replaceFirstChar {
if (it.isLowerCase()) {
it.titlecase(this)
} else {
it.toString()
}
}
private fun PackageParser.ApkLite.splitName(): String {
val splitName = splitName.removeSurrounding("${configForSplit}.", "")
return splitName.removeSurrounding("config.", "")
}
fun parse(apk: PackageParser.ApkLite, file: File): SplitConfig {
if (apk.isFeatureSplit) {
return Feature(
name = apk.splitName,
file = file
)
}
val value = apk.splitName()
val abi = ABI.valueOfOrNull(value.uppercase())
if (abi != null) {
return Target(
abi = abi,
configForSplit = apk.configForSplit,
file = file
)
}
val dpi = DPI.valueOfOrNull(value.uppercase())
if (dpi != null) {
return Density(
dpi = dpi,
configForSplit = apk.configForSplit,
file = file
)
}
val locale = Locale.forLanguageTag(value)
if (locale.language.isNotEmpty()) {
return Language(
locale = locale,
configForSplit = apk.configForSplit,
file = file
)
}
return Unspecified(
configForSplit = apk.configForSplit,
file = file
)
}
}
}
| 1 | null |
8
| 461 |
dd6a88cb343bbdd109d66b5227d721d8e12d1c13
| 4,895 |
PI
|
MIT License
|
core/src/main/kotlin/dev/sanmer/pi/bundle/SplitConfig.kt
|
SanmerApps
| 720,492,308 | false | null |
package dev.sanmer.pi.bundle
import android.content.pm.PackageParser
import android.os.Parcelable
import android.text.format.Formatter
import dev.sanmer.pi.ContextCompat
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import java.io.File
import java.util.Locale
sealed class SplitConfig : Parcelable {
abstract val file: File
abstract val name: String
abstract val configForSplit: String?
abstract val isRequired: Boolean
abstract val isDisabled: Boolean
abstract val isRecommended: Boolean
val displaySize: String
get() = Formatter.formatFileSize(ContextCompat.getContext(), file.length())
val isConfigForSplit: Boolean
inline get() = !configForSplit.isNullOrEmpty()
override fun toString(): String {
return "name = ${name}, " +
"required = ${isRequired}, " +
"disabled = ${isDisabled}, " +
"recommended = $isRecommended"
}
@Parcelize
data class Target(
val abi: ABI,
override val configForSplit: String?,
override val file: File
) : SplitConfig() {
@IgnoredOnParcel
override val name by lazy { abi.displayName }
@IgnoredOnParcel
override val isRequired by lazy { abi.isRequired }
@IgnoredOnParcel
override val isDisabled by lazy { !abi.isEnabled }
override val isRecommended get() = isRequired
}
@Parcelize
data class Density(
val dpi: DPI,
override val configForSplit: String?,
override val file: File
) : SplitConfig() {
override val name get() = dpi.displayName
@IgnoredOnParcel
override val isRequired by lazy { dpi.isRequired }
override val isDisabled get() = false
override val isRecommended get() = isRequired
}
@Parcelize
data class Language(
val locale: Locale,
override val configForSplit: String?,
override val file: File
) : SplitConfig() {
override val name get() = locale.localizedDisplayName
@IgnoredOnParcel
override val isRequired by lazy { locale.language == Locale.getDefault().language }
@IgnoredOnParcel
override val isDisabled by lazy { locale !in Locale.getAvailableLocales() }
override val isRecommended get() = isRequired
}
@Parcelize
data class Feature(
override val name: String,
override val file: File,
) : SplitConfig() {
override val configForSplit get() = null
override val isRequired get() = false
override val isDisabled get() = false
override val isRecommended get() = true
}
@Parcelize
data class Unspecified(
override val configForSplit: String?,
override val file: File,
) : SplitConfig() {
override val name get() = file.name
override val isRequired get() = false
override val isDisabled get() = false
override val isRecommended get() = true
}
companion object Default {
private val Locale.localizedDisplayName: String
inline get() = getDisplayName(this)
.replaceFirstChar {
if (it.isLowerCase()) {
it.titlecase(this)
} else {
it.toString()
}
}
private fun PackageParser.ApkLite.splitName(): String {
val splitName = splitName.removeSurrounding("${configForSplit}.", "")
return splitName.removeSurrounding("config.", "")
}
fun parse(apk: PackageParser.ApkLite, file: File): SplitConfig {
if (apk.isFeatureSplit) {
return Feature(
name = apk.splitName,
file = file
)
}
val value = apk.splitName()
val abi = ABI.valueOfOrNull(value.uppercase())
if (abi != null) {
return Target(
abi = abi,
configForSplit = apk.configForSplit,
file = file
)
}
val dpi = DPI.valueOfOrNull(value.uppercase())
if (dpi != null) {
return Density(
dpi = dpi,
configForSplit = apk.configForSplit,
file = file
)
}
val locale = Locale.forLanguageTag(value)
if (locale.language.isNotEmpty()) {
return Language(
locale = locale,
configForSplit = apk.configForSplit,
file = file
)
}
return Unspecified(
configForSplit = apk.configForSplit,
file = file
)
}
}
}
| 1 | null |
8
| 461 |
dd6a88cb343bbdd109d66b5227d721d8e12d1c13
| 4,895 |
PI
|
MIT License
|
app/src/main/java/com/vipulasri/jetinstagram/ui/profile/ProfilePage.kt
|
ra-janani
| 630,366,451 | false | null |
package com.vipulasri.jetinstagram.ui.profile
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.vipulasri.jetinstagram.R
import com.vipulasri.jetinstagram.data.ImageWithText
@Composable
fun ProfilePage(){
var selectedTabIndex by remember{
mutableStateOf(0)
}
Column(modifier= Modifier.fillMaxSize()){
TopBar(name = "<NAME>",modifier=Modifier.padding(20.dp))
Spacer(modifier=Modifier.height(4.dp))
ProfileSection()
ProfileDesc(displayName = "Janani", description = "Lives in London")
Spacer(modifier=Modifier.height(25.dp))
ButtonSection(modifier=Modifier.fillMaxWidth())
Spacer(modifier=Modifier.height(25.dp))
HighLightSection(highlights = listOf(
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab1_inversions),
text="Inversions"
),
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab2_quick_yoga),
text="YOGA"
),
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab3_stretching),
text="Stretch"
),
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab4_tabata),
text="Tabata"
),
),
modifier= Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
)
Spacer(modifier=Modifier.height(10.dp))
PostTabView(
imageWithTexts = listOf(
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ic_grid),
text="Posts"
),
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ic_grid),
text="Posts"
),
ImageWithText(
image= painterResource(id =com.vipulasri.jetinstagram. R.drawable.ic_grid),
text="Posts"
),
ImageWithText(
image= painterResource(id = com.vipulasri.jetinstagram.R.drawable.ic_grid),
text="Posts"
),
)
) {
selectedTabIndex=it
}
when(selectedTabIndex){
0-> PostSection(
posts = listOf(
painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab1_inversions),
painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab2_quick_yoga),
painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab3_stretching),
painterResource(id =com.vipulasri.jetinstagram. R.drawable.ab4_tabata),
painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab1_inversions),
painterResource(id = com.vipulasri.jetinstagram.R.drawable.ab2_quick_yoga),
),
modifier=Modifier.fillMaxWidth()
)
}
}
}
@Composable
fun TopBar(
name:String,
modifier:Modifier=Modifier
){
Row(verticalAlignment = Alignment.CenterVertically,
horizontalArrangement =Arrangement.SpaceAround,
modifier=Modifier.fillMaxWidth()
){
Icon(imageVector= Icons.Default.ArrowBack,
contentDescription="Back",
tint= Color.Black,
modifier=Modifier.size(24.dp)
)
Text(
text=name,
overflow=TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
Icon(
painter=painterResource(id=com.vipulasri.jetinstagram.R.drawable.ic_bell),
contentDescription="Back",
tint= Color.Black,
modifier=Modifier.size(24.dp)
)
Icon(
painter=painterResource(id=com.vipulasri.jetinstagram.R.drawable.ic_menu),
contentDescription="Back",
tint= Color.Black,
modifier=Modifier.size(24.dp)
)
}
}
@Composable
fun ProfileSection(
modifier:Modifier=Modifier
){
Column(modifier=modifier.fillMaxWidth()){
Row(verticalAlignment = Alignment.CenterVertically,
modifier= Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp))
{
RoundImage(
image = painterResource(id=com.vipulasri.jetinstagram.R.drawable.profile_img),
modifier = Modifier
.size(100.dp)
.weight(3f)
)
Spacer(modifier=Modifier.width(16.dp))
Status(modifier=Modifier.weight(7f))
}
}
}
@Composable
fun RoundImage(
image: Painter,
modifier:Modifier=Modifier
){
Image(
painter=image,
contentDescription=null,
contentScale=ContentScale.FillBounds,
modifier= modifier
//.aspectRatio(1f, matchHeightConstraintsFirst = true)
//.aspectRatio(default)
.border(
width = 1.dp,
color = Color.LightGray,
//shape = CircleShape
)
.padding(3.dp)
// .clip(CircleShape)
//.fillMaxSize(1f)
)
}
@Composable
fun Status(modifier:Modifier=Modifier){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
modifier=modifier
){
ProfileStatus(numberText = "5", text = "Posts")
ProfileStatus(numberText = "0", text ="Followers" )
ProfileStatus(numberText = "0", text = "Following")
}
}
@Composable
fun ProfileStatus(
numberText:String,
text:String,
modifier:Modifier=Modifier
){
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier=modifier
){
Text(
text=numberText,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
Spacer(modifier=Modifier.height(4.dp))
Text(text=text)
}
}
@Composable
fun ProfileDesc(
displayName:String,
description:String
){
val letterSpacing=0.5.sp
val lineHeight=20.sp
Column(
modifier= Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
){
Text(
text=displayName,
fontWeight = FontWeight.Bold,
letterSpacing=letterSpacing,
lineHeight=lineHeight
)
Text(
text=description,
letterSpacing=letterSpacing,
lineHeight=lineHeight
)
}
}
@Composable
fun ButtonSection(
modifier:Modifier=Modifier
){
val minWidth=95.dp
val height=30.dp
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier=modifier
){
ActionButton(
text="Follow",
icon=Icons.Default.KeyboardArrowDown,
modifier= Modifier
.defaultMinSize(minWidth = minWidth)
.height(height)
)
ActionButton(
text="Message",
modifier= Modifier
.defaultMinSize(minWidth = minWidth)
.height(height)
)
ActionButton(
text="Email",
modifier= Modifier
.defaultMinSize(minWidth = minWidth)
.height(height)
)
}
}
@Composable
fun ActionButton(
modifier:Modifier=Modifier,
text:String?=null,
icon:ImageVector?=null
){
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier= modifier
.border(
width = 1.dp,
color = Color.LightGray,
shape = RoundedCornerShape(5.dp)
)
.padding(6.dp)
){
if(text!=null){
Text(
text=text,
fontWeight = FontWeight.SemiBold,
fontSize=14.sp
)
}
if(icon!=null){
Icon(
imageVector=icon,
contentDescription = null,
tint=Color.Black
)
}
}
}
@Composable
fun HighLightSection(modifier:Modifier=Modifier,
highlights:List<com.vipulasri.jetinstagram.data.ImageWithText>){
LazyRow(modifier=Modifier){
items(highlights.size){
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.padding(end=15.dp)
){
RoundImage(
image = highlights[it].image,
modifier =Modifier.size(70.dp)
)
Text(
text=highlights[it].text,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center
)
}
}
}
}
@Composable
fun PostTabView(modifier:Modifier=Modifier,
imageWithTexts:List<ImageWithText>,
onTabSelected:(selectedIndex:Int)->Unit) {
var selectedTabIndex by remember {
mutableStateOf(0)
}
val inactiveColor = Color(0xFF777777)
TabRow(
selectedTabIndex = selectedTabIndex,
backgroundColor = Color.Transparent,
contentColor = Color.Black,
modifier = modifier
) {
imageWithTexts.forEachIndexed { index, item ->
Tab(
selected = selectedTabIndex == index,
selectedContentColor = Color.Black,
unselectedContentColor = inactiveColor,
onClick = {
selectedTabIndex = index
onTabSelected(index)
}
)
{
Icon(
painter = item.image,
contentDescription = item.text,
tint = if (selectedTabIndex == 0) Color.Black else inactiveColor,
modifier = Modifier
.padding(10.dp)
.size(20.dp)
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PostSection(
posts:List<Painter>,
modifier:Modifier=Modifier
){
LazyVerticalGrid(cells = GridCells.Fixed(3),
modifier=modifier.scale(1.01f)
){
items(posts.size){
Image(
painter=posts[it],
contentDescription = null,
contentScale=ContentScale.Crop,
modifier= Modifier
.aspectRatio(1f)
.border(
width = 1.dp,
color = Color.White
)
)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
0807fe5d48757e5a8ab438baf03da992de9e9b5a
| 12,577 |
JetInstagram
|
Apache License 2.0
|
app/src/main/java/com/example/todoapp/di/RepositoryModule.kt
|
tyrnor
| 738,167,970 | false |
{"Kotlin": 36025}
|
package com.example.todoapp.di
import com.example.todoapp.data.local.TaskDao
import com.example.todoapp.data.repository.TaskRepository
import com.example.todoapp.domain.mappers.TaskMapper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {
@Singleton
@Provides
fun provideTaskRepository(taskDao: TaskDao, mapper: TaskMapper): TaskRepository {
return TaskRepository(taskDao, mapper)
}
}
| 0 |
Kotlin
|
0
| 0 |
83b42968bf15fd6e0649c503e332a85d7f8be01f
| 584 |
NotesApp
|
MIT License
|
Android/Podium/app/src/main/java/xyz/thisisjames/boulevard/android/podium/room/PreferenceViewModel.kt
|
JamesNjong
| 652,773,723 | false |
{"Kotlin": 76766, "JavaScript": 13790}
|
package xyz.thisisjames.boulevard.android.podium.room
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class PreferenceViewModel (private val application: Application) : AndroidViewModel(application) {
val status : String
val repository : PreferenceRepository
init {
val dao = PreferenceRoomDataBase.getDatabase(application).preferenceDao()
repository = PreferenceRepository(dao)
status = repository.userStatus.value?.get(0)?.prefvalue ?: "Unknown"
}
fun update(status:Preferences) = viewModelScope.launch {
repository.update(status)
}
}
| 0 |
Kotlin
|
0
| 0 |
0d843d3045de6b0cd9eff085f2f289fc4a653488
| 813 |
Podium
|
Creative Commons Zero v1.0 Universal
|
Android/Podium/app/src/main/java/xyz/thisisjames/boulevard/android/podium/room/PreferenceViewModel.kt
|
JamesNjong
| 652,773,723 | false |
{"Kotlin": 76766, "JavaScript": 13790}
|
package xyz.thisisjames.boulevard.android.podium.room
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class PreferenceViewModel (private val application: Application) : AndroidViewModel(application) {
val status : String
val repository : PreferenceRepository
init {
val dao = PreferenceRoomDataBase.getDatabase(application).preferenceDao()
repository = PreferenceRepository(dao)
status = repository.userStatus.value?.get(0)?.prefvalue ?: "Unknown"
}
fun update(status:Preferences) = viewModelScope.launch {
repository.update(status)
}
}
| 0 |
Kotlin
|
0
| 0 |
0d843d3045de6b0cd9eff085f2f289fc4a653488
| 813 |
Podium
|
Creative Commons Zero v1.0 Universal
|
app/src/main/kotlin/org/eduardoleolim/organizadorpec660/app/shared/router/Router.kt
|
eduardoleolim
| 673,214,659 | false |
{"Kotlin": 811069}
|
package org.eduardoleolim.organizadorpec660.app.shared.router
import androidx.compose.runtime.Composable
import cafe.adriel.voyager.core.registry.ScreenRegistry
import cafe.adriel.voyager.navigator.Navigator
import org.eduardoleolim.organizadorpec660.app.agency.views.AgencyScreen
import org.eduardoleolim.organizadorpec660.app.auth.views.AuthScreen
import org.eduardoleolim.organizadorpec660.app.federalEntity.views.FederalEntityScreen
import org.eduardoleolim.organizadorpec660.app.home.views.HomeScreen
import org.eduardoleolim.organizadorpec660.app.instrument.views.InstrumentScreen
import org.eduardoleolim.organizadorpec660.app.instrument.views.SaveInstrumentScreen
import org.eduardoleolim.organizadorpec660.app.instrument.views.ShowInstrumentDetailsScreen
import org.eduardoleolim.organizadorpec660.app.municipality.views.MunicipalityScreen
import org.eduardoleolim.organizadorpec660.app.statisticType.views.StatisticTypeScreen
import org.eduardoleolim.organizadorpec660.core.shared.domain.bus.command.CommandBus
import org.eduardoleolim.organizadorpec660.core.shared.domain.bus.query.QueryBus
@Composable
fun Router(commandBus: CommandBus, queryBus: QueryBus, tempDirectory: String) {
ScreenRegistry {
register<MainProvider.AuthScreen> { AuthScreen(queryBus) }
register<MainProvider.HomeScreen> { provider ->
HomeScreen(provider.user)
}
register<HomeProvider.FederalEntityScreen> { FederalEntityScreen(queryBus, commandBus) }
register<HomeProvider.MunicipalityScreen> { MunicipalityScreen(queryBus, commandBus) }
register<HomeProvider.StatisticTypeScreen> { StatisticTypeScreen(queryBus, commandBus) }
register<HomeProvider.InstrumentScreen> { InstrumentScreen(queryBus, commandBus, tempDirectory) }
register<HomeProvider.SaveInstrumentScreen> { provider ->
SaveInstrumentScreen(provider.instrumentId, queryBus, commandBus, tempDirectory)
}
register<HomeProvider.ShowInstrumentDetailsScreen> { provider ->
ShowInstrumentDetailsScreen(provider.instrumentId, queryBus, tempDirectory)
}
register<HomeProvider.AgencyScreen> { AgencyScreen(queryBus, commandBus) }
}
Navigator(ScreenRegistry.get(MainProvider.AuthScreen))
}
| 0 |
Kotlin
|
0
| 0 |
bfe0cdaa736579f86d96e77503bdb8dca57685e8
| 2,274 |
organizador-pec-660
|
Creative Commons Attribution 4.0 International
|
app/src/main/kotlin/com/unhappychoice/droidflyer/presentation/presenter/core/Loadable.kt
|
unhappychoice
| 101,175,014 | false | null |
package com.unhappychoice.norimaki.presentation.presenter.core
import com.unhappychoice.norimaki.extension.Variable
import io.reactivex.Observable
interface Loadable {
val isLoading: Variable<Boolean>
fun <T> io.reactivex.Observable<T>.startLoading(): Observable<T> {
isLoading.value = true
return this
.doOnError { isLoading.value = false }
.doOnComplete { isLoading.value = false }
}
}
| 6 | null |
3
| 9 |
97b0f9e89b525e9a1a3292b15635fcb95956f64c
| 442 |
DroidFlyer
|
Apache License 2.0
|
generator/src/main/kotlin/com/patxi/poetimizely/generator/optimizely/OptimizelyServices.kt
|
patxibocos
| 245,565,952 | false | null |
package com.patxi.poetimizely.generator.optimizely
import retrofit2.http.GET
import retrofit2.http.Query
internal data class OptimizelyExperiment(val key: String, val variations: List<OptimizelyVariation>)
internal data class OptimizelyVariation(val key: String)
internal interface ExperimentsService {
@GET("experiments")
suspend fun listExperiments(@Query("project_id") projectId: Long): List<OptimizelyExperiment>
}
internal data class Feature(val key: String, val variables: Collection<Variable> = emptyList())
internal data class Variable(val key: String, val type: String)
internal interface FeaturesService {
@GET("features")
suspend fun listFeatures(@Query("project_id") projectId: Long): List<Feature>
}
| 3 |
Kotlin
|
1
| 18 |
c72491ca9b73e6e83958ea04302335f30f353662
| 734 |
poetimizely
|
MIT License
|
jacodb-core/src/main/kotlin/org/jacodb/impl/bytecode/Conversions.kt
|
UnitTestBot
| 491,176,077 | false | null |
/*
* Copyright 2022 UnitTestBot contributors (utbot.org)
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 org.jacodb.impl.bytecode
import org.jacodb.api.ClassSource
import org.jacodb.api.JcClassOrInterface
import org.jacodb.api.JcClasspath
import org.jacodb.api.JcClasspathFeature
import org.jacodb.api.JcMethod
import org.jacodb.impl.types.MethodInfo
import org.jacodb.impl.vfs.ClassVfsItem
fun JcClasspath.toJcClass(item: ClassVfsItem?): JcClassOrInterface? {
item ?: return null
return toJcClass(item.source)
}
fun JcClassOrInterface.toJcMethod(methodInfo: MethodInfo, source: ClassSource, features: List<JcClasspathFeature>?): JcMethod {
return JcMethodImpl(methodInfo, source, features, this)
}
| 10 |
Kotlin
|
3
| 7 |
e3df0f19858d502ea974d97be9ec7b93aed9207a
| 1,255 |
jacodb
|
Apache License 2.0
|
presentation/src/main/java/com/thetestcompany/presentation/mappers/ReceiptEntityToReceiptMapper.kt
|
LjungErik
| 166,547,194 | false | null |
package com.thetestcompany.presentation.mappers
import com.thetestcompany.domain.Mapper
import com.thetestcompany.domain.entities.ReceiptEntity
import com.thetestcompany.presentation.entities.Receipt
import javax.inject.Inject
class ReceiptEntityToReceiptMapper @Inject constructor(): Mapper<ReceiptEntity, Receipt>() {
override fun mapFrom(from: ReceiptEntity): Receipt {
return Receipt(
id = from.id,
name = from.name,
location = from.location
)
}
}
| 0 |
Kotlin
|
0
| 0 |
a1e5a595183e7199130e0dbc1c8e32a07c011661
| 529 |
AndroidShoppingApp
|
MIT License
|
Common/src/test/java/ram/talia/spellcore/api/softphysics/IcosphereGeneratorTest.kt
|
Talia-12
| 637,058,547 | false |
{"Kotlin": 42347, "Java": 27855}
|
package ram.talia.spellcore.api.softphysics
import com.google.common.math.IntMath.pow
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import ram.talia.spellcore.api.softphysics.IcosphereGenerator.icosphere
class IcosphereGeneratorTest {
@Test
fun icosphere() {
println(icosphere(0))
println(icosphere(1))
println(icosphere(2))
repeat(8) {
println(it)
val (vertices, edges, triangles) = icosphere(it)
assertEquals(20 * pow(4, it) - 8, vertices.size)
assertEquals(15 * pow(4, it) + if (it == 0) 15 else 0, edges.size)
assertEquals(20 * pow(4, it), triangles.size)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
bf7653377c86acb751aaad2f9dd6b06819e0870e
| 723 |
Spellcore
|
MIT License
|
src/main/kotlin/database/migrations/2019_05_12_023040_create_users_table.kt
|
GideonBrimleaf
| 272,957,278 | false |
{"CSS": 1885652, "JavaScript": 475833, "Kotlin": 31875, "HTML": 14495, "Shell": 5706, "Vue": 4669, "Less": 402}
|
package com.alpaca.fireplace.database.migrations
import com.alpaca.fireplace.entities.Users
import dev.alpas.auth.PasswordResetTokens
import dev.alpas.ozone.migration.Migration
// https://alpas.dev/docs/migrations
class CreateUsersTable : Migration() {
override fun up() {
createTable(Users)
createTable(PasswordResetTokens)
}
override fun down() {
dropTable(Users)
dropTable(PasswordResetTokens)
}
}
| 18 |
CSS
|
0
| 0 |
5529fe018d3668fa5f4fbb0355875915b1ee90f8
| 452 |
alpacaFireplace
|
MIT License
|
android/features/dashboard/dashboard-impl/src/main/java/jobajob/feature/dashboard/presentation/vacancies/adapter/base/ItemWithIdDiffUtilCallback.kt
|
Twinsen81
| 208,475,234 | false | null |
package jobajob.feature.dashboard.presentation.vacancies.adapter.base
import androidx.recyclerview.widget.DiffUtil
/**
* Simple DiffUtil for simple items
*/
internal class ItemWithIdDiffUtilCallback : DiffUtil.ItemCallback<ItemWithId>() {
override fun areItemsTheSame(oldItem: ItemWithId, newItem: ItemWithId): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: ItemWithId, newItem: ItemWithId) = true
override fun getChangePayload(oldItem: ItemWithId, newItem: ItemWithId): Any? = Any()
}
| 0 |
Kotlin
|
0
| 1 |
f0c17aa5798d5341d5e99857af6687d5cdc566f3
| 553 |
JobAJob
|
Apache License 2.0
|
android/features/dashboard/dashboard-impl/src/main/java/jobajob/feature/dashboard/presentation/vacancies/adapter/base/ItemWithIdDiffUtilCallback.kt
|
Twinsen81
| 208,475,234 | false | null |
package jobajob.feature.dashboard.presentation.vacancies.adapter.base
import androidx.recyclerview.widget.DiffUtil
/**
* Simple DiffUtil for simple items
*/
internal class ItemWithIdDiffUtilCallback : DiffUtil.ItemCallback<ItemWithId>() {
override fun areItemsTheSame(oldItem: ItemWithId, newItem: ItemWithId): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: ItemWithId, newItem: ItemWithId) = true
override fun getChangePayload(oldItem: ItemWithId, newItem: ItemWithId): Any? = Any()
}
| 0 |
Kotlin
|
0
| 1 |
f0c17aa5798d5341d5e99857af6687d5cdc566f3
| 553 |
JobAJob
|
Apache License 2.0
|
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/BannerInflater.kt
|
hwki
| 8,993,387 | false | null |
package com.brentpanther.bitcoinwidget.ui
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.core.content.edit
import androidx.core.view.isVisible
import com.brentpanther.bitcoinwidget.BuildConfig
import com.brentpanther.bitcoinwidget.R
class BannerInflater {
fun inflate(layoutInflater: LayoutInflater, viewGroup: ViewGroup) {
val context = viewGroup.context
viewGroup.removeAllViews()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!context.packageManager.isAutoRevokeWhitelisted &&
!isDismissed(context, "hibernate")) {
addBanner(layoutInflater, viewGroup, "hibernate", R.string.warning_hibernation,
R.string.button_settings) {
context.startActivity(Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:${BuildConfig.APPLICATION_ID}"))
)
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val restrictBackgroundStatus = connectivityManager.restrictBackgroundStatus
if (restrictBackgroundStatus == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED &&
!isDismissed(context, "data")) {
addBanner(layoutInflater, viewGroup, "data", R.string.warning_data_saver, R.string.button_settings) {
context.startActivity(Intent(
Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS,
Uri.parse("package:${BuildConfig.APPLICATION_ID}"))
)
}
}
}
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
if (powerManager.isPowerSaveMode && !powerManager.isIgnoringBatteryOptimizations(context.packageName) &&
!isDismissed(context, "battery")) {
addBanner(layoutInflater, viewGroup, "battery", R.string.warning_battery_saver)
}
}
private fun addBanner(layoutInflater: LayoutInflater, viewGroup: ViewGroup, key: String, @StringRes text: Int,
@StringRes buttonText: Int? = null, onClick: ((View) -> Unit)? = null) {
layoutInflater.inflate(R.layout.view_banner, viewGroup, false).apply {
findViewById<TextView>(R.id.text_warning).setText(text)
val openButton = findViewById<Button>(R.id.button_banner_open)
openButton.isVisible = buttonText != null
buttonText?.let {
openButton.setText(it)
openButton.setOnClickListener(onClick)
}
findViewById<Button>(R.id.button_dismiss).setOnClickListener {
this.isVisible = false
setDismiss(context, key)
}
viewGroup.addView(this)
}
}
private fun isDismissed(context: Context, key: String): Boolean {
return context.getSharedPreferences("widget", Context.MODE_PRIVATE).getLong(key, 0) > System.currentTimeMillis()
}
private fun setDismiss(context: Context, key: String) {
context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit {
putLong(key, System.currentTimeMillis() + dismissTime)
}
}
companion object {
// const val dismissTime: Long = 86400000L
const val dismissTime: Long = 60000L
}
}
| 4 |
Kotlin
|
52
| 79 |
b375b94494cb9ef9b2bda5fea89248dd4fe5e2d3
| 3,931 |
SimpleBitcoinWidget
|
MIT License
|
app/src/main/java/com/yj/constraintlayout20/barrier/BarrierActivity.kt
|
Cmahjong
| 197,549,627 | false | null |
package com.yj.constraintlayout20.barrier
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.yj.constraintlayout20.R
class BarrierActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_barrier)
}
}
| 0 |
Kotlin
|
0
| 1 |
3bdfcde74feb1fdb1c065a7acf0af207f3fcb7f5
| 357 |
ConstaintLayout
|
Apache License 2.0
|
app/src/main/java/com/dev/james/sayariproject/data/local/datastore/DataStoreManager.kt
|
JayExtra
| 426,628,122 | false | null |
package com.dev.james.sayariproject.data.local.datastore
import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.dataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import com.dev.james.sayariproject.data.local.datastore.DatastorePreferenceKeys.IS_DARK_MODE_ENABLED
import com.dev.james.sayariproject.data.local.datastore.DatastorePreferenceKeys.IS_FIFTEEN_MIN_ENABLED
import com.dev.james.sayariproject.data.local.datastore.DatastorePreferenceKeys.IS_FIVE_MIN_ENABLED
import com.dev.james.sayariproject.data.local.datastore.DatastorePreferenceKeys.IS_FROM_FAVOURITE_AGENCIES_ENABLED
import com.dev.james.sayariproject.data.local.datastore.DatastorePreferenceKeys.IS_THIRTY_MIN_ENABLED
import com.dev.james.sayariproject.data.local.datastore.DatastorePreferenceKeys.STORE_NAME
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.*
import java.io.IOException
import javax.inject.Inject
class DataStoreManager @Inject constructor(
@ApplicationContext private val context : Context
){
companion object{
private val Context.dataStore : DataStore<Preferences> by preferencesDataStore(name = STORE_NAME)
}
//store any boolean value in the datastore with its desired key
suspend fun storeBooleanValue(key : Preferences.Key<Boolean> , value : Boolean){
context.dataStore.edit {
it[key] = value
}
}
//read any boolean value from datastore using its key , returns a flow
//of boolean value
fun readBooleanValue(key : Preferences.Key<Boolean>) : Flow<Boolean> {
return context.dataStore.data.map {
it[key]?:false
}.catch { exception ->
if(exception is IOException){
Log.e("DatastoreManager", "readBooleanValue: error reading exception", exception)
emit(false)
}
}
}
suspend fun readBooleanValueOnce(key : Preferences.Key<Boolean>) =
context.dataStore.data.first()[key] ?: false
val settingsPreferencesFlow = context.dataStore.data.catch { exception ->
if(exception is IOException){
Log.e("DatastoreManager", "Error:error fetching preferences ", exception )
emit(emptyPreferences())
}else{
throw exception
}
}.map { preferences ->
val dayNightModeValue = preferences[IS_DARK_MODE_ENABLED] ?: false
val favouriteAgenciesValue = preferences[IS_FROM_FAVOURITE_AGENCIES_ENABLED] ?: false
val thirtyMinutesValue = preferences[IS_THIRTY_MIN_ENABLED] ?: true
val fifteenMinutesValue = preferences[IS_FIFTEEN_MIN_ENABLED] ?: false
val fiveMinutesValue = preferences[IS_FIVE_MIN_ENABLED] ?: true
AllPreferences(dayNightModeValue , favouriteAgenciesValue ,
thirtyMinutesValue , fifteenMinutesValue , fiveMinutesValue)
}
}
data class AllPreferences(
val nightDarkStatus : Boolean,
val favouriteAgencies : Boolean,
val thirtyMinStatus : Boolean,
val fifteenMinStatus : Boolean,
val fiveMinStatus : Boolean
)
| 4 |
Kotlin
|
0
| 0 |
cea83c93bbfa286ee473910c1f00abe076ef1344
| 3,338 |
Sayari_Project
|
Apache License 2.0
|
src/jvmMain/kotlin/org/mifek/wfc/adapters/options/AnimationOptions.kt
|
JakubMifek
| 326,496,922 | false | null |
package org.mifek.wfc.adapters.options
/**
* Animation options
*
* @property outputPath
* @property fileName
* @property outputScale
* @property events
* @property useEvery
* @property fps
* @property loop
* @constructor Create empty Animation options
*/
data class AnimationOptions(
val outputPath: String,
val fileName: String,
val outputScale: Int = 1,
val events: Array<EventType> = arrayOf(EventType.STEP),
val useEvery: Int = 1,
val fps: Int = 10,
val loop: Boolean = false,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AnimationOptions
if (outputPath != other.outputPath) return false
if (fileName != other.fileName) return false
if (outputScale != other.outputScale) return false
if (!events.contentEquals(other.events)) return false
if (useEvery != other.useEvery) return false
if (fps != other.fps) return false
if (loop != other.loop) return false
return true
}
override fun hashCode(): Int {
var result = outputPath.hashCode()
result = 31 * result + fileName.hashCode()
result = 31 * result + outputScale
result = 31 * result + events.contentHashCode()
result = 31 * result + useEvery
result = 31 * result + fps
result = 31 * result + loop.hashCode()
return result
}
}
| 1 |
Kotlin
|
1
| 2 |
4f034f6253fdea64f8a2c10e987d7e6975449ba7
| 1,484 |
WFC-Kotlin
|
MIT License
|
src/main/kotlin/me/amol/crab/ActiveCookieCommand.kt
|
amolrv
| 599,656,113 | false | null |
package me.amol.crab
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.convert
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.types.file
import java.io.File
import java.time.LocalDate
import java.time.OffsetDateTime
import java.time.ZoneOffset.UTC
import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE
class ActiveCookieCommand(
private val csvCookieFileReader: CookieFileReader,
private val activeCookieCalculator: ActiveCookieCalculator
) :
CliktCommand(name = "cookie") {
private val file: File by option("-f", help = "cookie file path")
.file(mustExist = true, canBeDir = false, mustBeReadable = true)
.required()
private val date: OffsetDateTime by option("-d", help = "date in yyyy-MM-dd format")
.convert { offsetDateTime(it) }.required()
companion object {
private fun offsetDateTime(it: String): OffsetDateTime =
OffsetDateTime.of(LocalDate.parse(it, ISO_LOCAL_DATE).atStartOfDay(), UTC)
}
override fun run() {
with(csvCookieFileReader) {
readLogsOfTheDay(file, date)
.let { activeCookieCalculator.activeCookies(it) }
.forEach { println(it) }
}
}
}
| 0 |
Kotlin
|
0
| 0 |
a2a7f94112f4467716d88c138694d4a79a1ee74e
| 1,361 |
crab
|
MIT License
|
cloud3-common/src/main/kotlin/top/daozhang/config/RsaConfig.kt
|
qiudaozhang
| 606,390,562 | false | null |
package top.daozhang.config
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@Component
@ConfigurationProperties(prefix = "rsa")
@ConditionalOnProperty(name = ["rsa.enable"], havingValue = "true")
class RsaConfig {
var pubKey:String?=null
var priKey:String?=null
var enable: Boolean?=null
}
| 0 |
Kotlin
|
0
| 1 |
d3e8d183650921792ba737f34f4b4d15448efc95
| 457 |
cloud3
|
Apache License 2.0
|
domain/src/test/java/com/thomas/domain/usecases/GetUsersUseCaseTest.kt
|
thomasmarquesbr
| 807,823,363 | false |
{"Kotlin": 108941}
|
package com.thomas.domain.usecases
import app.cash.turbine.test
import com.thomas.domain.GithubRepository
import com.thomas.domain.UserStubs
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import junit.framework.Assert
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.junit.Test
import kotlin.time.ExperimentalTime
@ExperimentalTime
internal class GetUsersUseCaseTest {
private val repository: GithubRepository = mockk()
@Test
fun `When useCase is Should return correct object`() = runBlocking {
// Given
val expectItem = UserStubs.listUsers
coEvery { repository.getUsers() } returns flowOf(expectItem)
// When
val result = GetUsersUseCase(repository).invoke()
// Then
coVerify { repository.getUsers() }
result.test {
Assert.assertEquals(expectItem(), expectItem)
expectComplete()
}
}
@Test
fun `When useCase is Should return a error`() = runBlocking {
// Given
val error = Throwable("Generic error")
coEvery { repository.getUsers() } returns flow { throw error }
// When
val result = GetUsersUseCase(repository).invoke()
// Then
coVerify { repository.getUsers() }
result.test {
Assert.assertEquals(expectError(), error)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
c72724f8d69ea40cca0287d9d1724b86a9d48328
| 1,439 |
github_android_app
|
The Unlicense
|
domain/src/test/java/com/thomas/domain/usecases/GetUsersUseCaseTest.kt
|
thomasmarquesbr
| 807,823,363 | false |
{"Kotlin": 108941}
|
package com.thomas.domain.usecases
import app.cash.turbine.test
import com.thomas.domain.GithubRepository
import com.thomas.domain.UserStubs
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import junit.framework.Assert
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.junit.Test
import kotlin.time.ExperimentalTime
@ExperimentalTime
internal class GetUsersUseCaseTest {
private val repository: GithubRepository = mockk()
@Test
fun `When useCase is Should return correct object`() = runBlocking {
// Given
val expectItem = UserStubs.listUsers
coEvery { repository.getUsers() } returns flowOf(expectItem)
// When
val result = GetUsersUseCase(repository).invoke()
// Then
coVerify { repository.getUsers() }
result.test {
Assert.assertEquals(expectItem(), expectItem)
expectComplete()
}
}
@Test
fun `When useCase is Should return a error`() = runBlocking {
// Given
val error = Throwable("Generic error")
coEvery { repository.getUsers() } returns flow { throw error }
// When
val result = GetUsersUseCase(repository).invoke()
// Then
coVerify { repository.getUsers() }
result.test {
Assert.assertEquals(expectError(), error)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
c72724f8d69ea40cca0287d9d1724b86a9d48328
| 1,439 |
github_android_app
|
The Unlicense
|
src/main/java/eu/nimakro/tornadofx/material/Test.kt
|
abhinayagarwal
| 120,909,273 | true |
{"Kotlin": 30923}
|
package eu.nimakro.tornadofx.material
import eu.nimakro.tornadofx.material.style.MaterialStyle
import javafx.application.Application
import tornadofx.*
/**
* Created by amish on 6/19/17.
*/
class Main: App(MainView::class, MaterialStyle::class)
class MainView: View("Test") {
override val root = vbox {
button("TEST")
}
}
fun main(args: Array<String>) {
Application.launch(Main::class.java, *args)
}
| 0 |
Kotlin
|
0
| 0 |
17659126ea1dd5d122850480408721262be6e1de
| 428 |
tornadofx-material
|
Apache License 2.0
|
app/src/main/java/gps/x/an3000qiapplication/view/interfaces/MainView.kt
|
gpsx
| 206,620,682 | false | null |
package gps.x.an3000qiapplication.view.interfaces
import gps.x.an3000qiapplication.model.Character
interface MainView{
fun swapLoadingToList(characters : MutableList<Character>)
fun showErr(text : String?)
fun onFirstLoadError()
fun swapLoadingToSearchList(characters : MutableList<Character>)
}
| 0 |
Kotlin
|
0
| 0 |
2dc5a20e3b89106ba95dcd2d1781cb035ccd7b3f
| 316 |
An-3000IQ-Application
|
MIT License
|
src/main/kotlin/org/world/util.kt
|
oserban
| 244,951,190 | false | null |
package org.world
import com.beust.jcommander.internal.Console
import com.google.gson.GsonBuilder
import com.google.gson.JsonIOException
import org.apache.logging.log4j.Logger
import javax.naming.OperationNotSupportedException
private val gson = GsonBuilder().create()
fun toJson(element: Map<*, *>?, logger: Logger): String? {
return if (element == null || element.isEmpty()) {
null
} else try {
gson.toJson(element)
} catch (e: JsonIOException) {
logger.error("Error while converting to json", e)
null
}
}
class LoggerConsole(private val logger: Logger) : Console {
override fun print(msg: String?) {
logger.info(msg)
}
override fun println(msg: String?) {
logger.info(msg)
}
override fun readPassword(echoInput: Boolean): CharArray {
throw OperationNotSupportedException()
}
}
| 11 |
Kotlin
|
0
| 0 |
0e30adb5665de4940e1611705535ffd582d9d4fd
| 881 |
twitter-krawler
|
MIT License
|
kotlin-examples/src/main/kotlin/top/viclau/magicbox/kotlin/examples/sdk/Whatsnew13.kt
|
xingyuli
| 578,005,859 | false | null |
/*
* Copyright (c) 2022 <NAME>
*
* Distributed under MIT license.
* See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package top.viclau.magicbox.kotlin.examples.sdk
fun main() {
/* ***** Contracts ***** */
foo("hello")
bar()
baz("abc")
/* ***** Standard library ***** */
// ifEmpty and ifBlank functions
println("".ifEmpty { "nothing" })
println(" ".ifBlank { "nothing again" })
// Sealed classes in reflection
println(Shape::class.sealedSubclasses)
}
fun foo(s: String?) {
require(s is String)
println(s.length)
}
object MyLock
fun bar() {
val x: Int
synchronized(MyLock) {
x = 42
}
println(x)
}
fun baz(x: String?) {
if (!x.isNullOrEmpty()) {
println("length of '$x' is ${x.length}")
}
}
sealed class Shape(val name: String) {
class Circle(name: String) : Shape(name)
class Triangle(name: String) : Shape(name)
class Square(name: String) : Shape(name)
}
| 0 |
Kotlin
|
0
| 0 |
b1c702f3cfd1c64ccd37a3465a8ce42b3f346ba3
| 1,002 |
magicbox
|
MIT License
|
app/src/test/kotlin/com/jpaya/englishisfun/idioms/ui/model/IdiomItemTest.kt
|
mvvm-android
| 300,814,816 | true |
{"Kotlin": 536323, "Shell": 734}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jpaya.englishisfun.idioms.ui.model
import org.junit.Assert.*
import org.junit.Test
class IdiomItemTest {
@Test
fun `Init should initialise properly`() {
val id: Long = 1
val idiom = "Idiom"
val description = "Description"
val item = IdiomItem(id, idiom, description)
assertEquals(id, item.id)
assertEquals(idiom, item.idiom)
assertEquals(description, item.description)
}
@Test
fun `Check that comparator works properly`() {
// Different data
val item1 = IdiomItem(1, "Idiom 1", "Description 1")
val item2 = IdiomItem(2, "Idiom 2", "Description 2")
assertFalse(item1.isSameItemAs(item2))
assertFalse(item1.hasSameContentsAs(item2))
// Same Id
val item3 = IdiomItem(1, "Idiom 3", "Description 3")
assertTrue(item1.isSameItemAs(item3))
assertFalse(item1.hasSameContentsAs(item3))
// Same data
val item4 = IdiomItem(1, "Idiom 1", "Description 1")
assertTrue(item1.isSameItemAs(item4))
assertTrue(item1.hasSameContentsAs(item4))
}
}
| 0 | null |
0
| 0 |
92e79fad0c2ac3f4c1663b4e33aa345bee110231
| 1,723 |
englishisfun
|
Apache License 2.0
|
projector-client-web/src/main/kotlin/org/jetbrains/projector/client/web/ClipboardHandler.kt
|
JetBrains
| 267,844,825 | false | null |
/*
* MIT License
*
* Copyright (c) 2019-2021 JetBrains s.r.o.
*
* 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 org.jetbrains.projector.client.web
import kotlinx.browser.document
import kotlinx.browser.window
import org.jetbrains.projector.client.web.misc.isDefined
import org.jetbrains.projector.client.web.misc.isElectron
import org.jetbrains.projector.client.web.misc.isGecko
import org.jetbrains.projector.common.protocol.toServer.ClientNotificationEvent
import org.jetbrains.projector.common.protocol.toServer.ClientNotificationType
import org.jetbrains.projector.util.logging.Logger
import org.w3c.dom.HTMLTextAreaElement
/**
* First try to copy via `window.navigator.clipboard`. If this method fails or is not available,
* then try to copy via `document.execCommand` (deprecated, but still supported by firefox).
* If this also fails, then fallback to asking user to copy manually.
*/
class ClipboardHandler(private val onCopyFailed: (ClientNotificationEvent) -> Unit) {
private val logger = Logger<ClipboardHandler>()
fun copyText(text: String) {
if (isDefined(window.navigator.clipboard)) {
window.navigator.clipboard.writeText(text)
.catch {
logger.error(it) { "Error writing clipboard: $it" }
fallbackCopy(text, it.message ?: "Unknown error")
}
}
else {
fallbackCopy(text, "Clipboard API is not available")
}
}
private fun fallbackCopy(textToCopy: String, reason: String) {
val execCommandReason = tryCopyTextViaExecCommand(textToCopy)
if (execCommandReason != null) {
askUserToCopyClipboardManually(textToCopy, reason, execCommandReason)
}
}
/**
* Tries to automatically copy text to clipboard via Document.execCommand
*
* @return null if copy successful, string describing fail reason otherwise
*/
private fun tryCopyTextViaExecCommand(textToCopy: String): String? {
when {
!isDefined(js("document.execCommand")) -> return "Document.execCommand is not available"
// Chrome only allows Document.execCommand from event callbacks
!isGecko() -> return "Copying using Document.execCommand works only in Firefox"
}
val textArea = document.createElement("textarea") as HTMLTextAreaElement
textArea.id = "copyArea"
textArea.value = textToCopy
textArea.style.display = "hidden"
document.body!!.appendChild(textArea)
textArea.focus()
textArea.select()
var isCopied = false
try {
isCopied = document.execCommand("copy")
}
catch (t: Throwable) { // May throw SecurityError https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#the-copy-command
logger.error(t) { "Error while running 'document.execCommand(\"copy\")'" }
}
finally {
textArea.remove()
}
return if (isCopied) null else "Document.execCommand failed, check console for info from browser"
}
private fun askUserToCopyClipboardManually(textToCopy: String, vararg reasons: String) {
val message = "A clipboard change on the server detected but can't synchronize your clipboard with it automatically " +
"(reasons: ${reasons.joinToString("; ")}). Please copy text on next line manually:"
if (isElectron()) { // TODO window.prompt is not available in electron
val title = "Copying failed"
val notificationMessage = "Copying is not currently supported in insecure context in Projector launcher"
val type = ClientNotificationType.ERROR
onCopyFailed(ClientNotificationEvent(title, notificationMessage, type))
}
else {
window.prompt(message, textToCopy)
}
}
}
| 20 | null |
94
| 815 |
0f1e08a68f01c417a7ce8a58afe77d63603e22db
| 4,661 |
projector-client
|
MIT License
|
app/src/main/java/com/test/project/data/repo/NewsRepo.kt
|
Petrov-Daniil
| 568,047,081 | false | null |
package com.test.project.data.repo
import com.test.project.data.dataSource.SibgutiHerokuRemoteDataSource
import com.test.project.data.dataSource.database.NewsDatabase
import com.test.project.data.remote.entity.FavoriteNews
import com.test.project.data.remote.entity.toApiNewsDatabase
import com.test.project.data.remote.entity.toNews
import com.test.project.domain.RequestResult
import com.test.project.domain.entity.News
import com.test.project.domain.repo.INewsRepo
class NewsRepo(
private val dataSource: SibgutiHerokuRemoteDataSource,
private val database: NewsDatabase
) : INewsRepo {
override suspend fun getNews(): RequestResult<List<News>> {
return when (val result = dataSource.getNews()) {
is RequestResult.Success -> {
database.newsDao().deleteAll()
RequestResult.Success(
result.data.map {
with(database.newsDao()) {
if (size() < 3)
insert(it.toApiNewsDatabase())
}
it.toNews()
}
)
}
is RequestResult.Error -> {
RequestResult.Error(
result.exception
)
}
}
}
override suspend fun getNewsFromDatabase(): List<News> {
return database.newsDao().getAll().map {
it.toNews()
}
}
override suspend fun insertToFavorite(favoriteNews: FavoriteNews) {
database.newsDao().insertIntoFavorite(favoriteNews)
}
override suspend fun deleteFromFavoriteById(id: Int) {
database.newsDao().deleteFromFavoriteById(id)
}
override suspend fun getFavoriteNewsFromDatabase(): List<FavoriteNews> {
return database.newsDao().getAllFromFavorite()
}
}
| 0 |
Kotlin
|
0
| 0 |
f5d994d4082da014021d6c4923d84b0eb0321907
| 1,878 |
Events
|
MIT License
|
src/main/kotlin/ru/yandex/money/tools/grafana/dsl/panels/RowBuilder.kt
|
arodrime
| 176,972,313 | true |
{"Kotlin": 92104, "Shell": 5947, "Batchfile": 2183, "Groovy": 25}
|
package ru.yandex.money.tools.grafana.dsl.panels
/**
* Builder for a string, containing panels.
*
* @author <NAME> (<EMAIL>)
* @since 7/21/18
*/
class RowBuilder(title: String) : PanelContainerBuilder {
override val panels = mutableListOf<Panel>(
Row(BasePanel(id = idGenerator++, title = title, position = nextPosition(24, 1)))
)
internal fun createRow() = panels.toList()
}
| 0 |
Kotlin
|
0
| 0 |
0eca3e89a579da88fe1ccd4f4794ff114fef7f3d
| 408 |
grafana-dashboard-dsl
|
MIT License
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/imagebuilder/CfnImagePipelinePropsDsl.kt
|
F43nd1r
| 643,016,506 | false | null |
package com.faendir.awscdkkt.generated.services.imagebuilder
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.imagebuilder.CfnImagePipelineProps
@Generated
public fun buildCfnImagePipelineProps(initializer: @AwsCdkDsl
CfnImagePipelineProps.Builder.() -> Unit): CfnImagePipelineProps =
CfnImagePipelineProps.Builder().apply(initializer).build()
| 1 |
Kotlin
|
0
| 0 |
e9a0ff020b0db2b99e176059efdb124bf822d754
| 437 |
aws-cdk-kt
|
Apache License 2.0
|
feature/legal/src/main/kotlin/dev/pott/abonity/feature/legal/consent/ConsentDestination.kt
|
JohannesPtaszyk
| 695,929,733 | false |
{"Kotlin": 511937}
|
package dev.pott.abonity.feature.legal.consent
import androidx.navigation.NavController
import dev.pott.abonity.navigation.destination.Destination
object ConsentDestination : Destination {
override val route: String = "consent"
}
fun NavController.navigateToConsentDialog() {
navigate(ConsentDestination.route)
}
| 9 |
Kotlin
|
0
| 2 |
0f8a977adbcb282f9803f2abc413a9d507f8e98b
| 324 |
Abonity
|
Apache License 2.0
|
app/src/main/java/ca/warp7/android/scouting/ui/field/CheckboxField.kt
|
Team865
| 119,227,423 | false | null |
package ca.warp7.android.scouting.ui.field
import android.annotation.SuppressLint
import android.graphics.Typeface
import android.view.Gravity
import android.widget.CheckBox
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import ca.warp7.android.scouting.R
import ca.warp7.android.scouting.entry.DataPoint
@SuppressLint("ViewConstructor")
class CheckboxField internal constructor(private val data: FieldData) :
LinearLayout(data.context), BaseFieldWidget {
private val accent = ContextCompat.getColor(context, R.color.accent)
private val disabled = ContextCompat.getColor(context, R.color.buttonDisabled)
init {
setBackgroundResource(R.drawable.ripple_button)
background.mutate()
gravity = Gravity.CENTER
}
private val checkBox: CheckBox = CheckBox(data.context).apply {
layoutParams = LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
)
isAllCaps = false
textSize = 17f
setLines(2)
typeface = Typeface.SANS_SERIF
text = data.modifiedName
setOnClickListener {
onClick(data, this.isChecked)
}
addView(this)
}
init {
setOnClickListener {
val checked = !checkBox.isChecked
checkBox.isChecked = checked
onClick(data, checked)
}
updateControlState()
}
private fun onClick(data: FieldData, isChecked: Boolean) {
val activity = data.scoutingActivity
if (activity.isTimeEnabled()) {
activity.vibrateAction()
val entry = activity.entry
if (entry != null) {
entry.add(DataPoint(data.typeIndex, if (isChecked) 1 else 0, activity.getRelativeTime()))
updateControlState()
}
}
}
override fun updateControlState() {
if (data.scoutingActivity.isTimeEnabled()) {
checkBox.isEnabled = true
this.isEnabled = true
checkBox.setTextColor(accent)
val entry = data.scoutingActivity.entry
if (entry != null) {
val lastDP = entry.lastValue(data.typeIndex)
checkBox.isChecked = if (lastDP != null) lastDP.value == 1 else false
}
} else {
checkBox.isEnabled = false
this.isEnabled = false
checkBox.setTextColor(disabled)
}
}
}
| 0 |
Kotlin
|
2
| 3 |
a12652184637cd1f7beaa13ec618af2e16ee24d6
| 2,489 |
Android-Scouting-App
|
MIT License
|
src/main/kotlin/com/robotutor/iot/widgets/collectionOfButtons/services/CollectionOfButtonsService.kt
|
IOT-echo-system
| 768,195,181 | false |
{"Kotlin": 207075, "HTML": 428, "Shell": 151, "Dockerfile": 130}
|
package com.robotutor.iot.widgets.collectionOfButtons.services
import com.robotutor.iot.logging.logOnError
import com.robotutor.iot.logging.logOnSuccess
import com.robotutor.iot.mqtt.models.AuditEvent
import com.robotutor.iot.mqtt.services.MqttPublisher
import com.robotutor.iot.utils.audit.auditOnError
import com.robotutor.iot.utils.audit.auditOnSuccess
import com.robotutor.iot.utils.models.BoardAuthenticationData
import com.robotutor.iot.utils.models.UserAuthenticationData
import com.robotutor.iot.utils.models.UserBoardAuthenticationData
import com.robotutor.iot.utils.services.IdGeneratorService
import com.robotutor.iot.widgets.collectionOfButtons.controllers.views.AddButtonRequest
import com.robotutor.iot.widgets.collectionOfButtons.controllers.views.ButtonState
import com.robotutor.iot.widgets.collectionOfButtons.modals.CollectionOfButtons
import com.robotutor.iot.widgets.collectionOfButtons.repositories.CollectionOfButtonsRepository
import com.robotutor.iot.widgets.gateway.NodeBffGateway
import com.robotutor.iot.widgets.modals.IdType
import com.robotutor.iot.widgets.modals.Widget
import com.robotutor.iot.widgets.modals.WidgetId
import com.robotutor.iot.widgets.modals.WidgetType
import com.robotutor.iot.widgets.services.WidgetService
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service
class CollectionOfButtonsService(
private val collectionOfButtonsRepository: CollectionOfButtonsRepository,
private val idGeneratorService: IdGeneratorService,
private val widgetService: WidgetService,
private val mqttPublisher: MqttPublisher,
private val nodeBffGateway: NodeBffGateway
) {
fun addCollectionOfButtons(userBoardAuthenticationData: UserBoardAuthenticationData): Mono<CollectionOfButtons> {
return idGeneratorService.generateId(IdType.WIDGET_ID)
.flatMap { widgetId ->
widgetService.addWidget(
foreignWidgetId = widgetId,
accountId = userBoardAuthenticationData.accountId,
boardId = userBoardAuthenticationData.boardId,
widgetType = WidgetType.COLLECTION_OF_BUTTONS,
name = "Collection of Buttons",
)
}
.flatMap {
collectionOfButtonsRepository.save(CollectionOfButtons.from(it.widgetId, it.boardId, it.accountId))
}
.auditOnSuccess(mqttPublisher, AuditEvent.ADD_WIDGET)
.auditOnError(mqttPublisher, AuditEvent.ADD_WIDGET)
.logOnSuccess(message = "Successfully added Collection of buttons widget")
.logOnError(errorMessage = "Failed to add Collection of buttons widget")
}
fun getCollectionOfButtons(
userAuthenticationData: UserAuthenticationData,
widgetIds: List<WidgetId>
): Flux<CollectionOfButtons> {
return collectionOfButtonsRepository.findAllByWidgetIdInAndAccountId(
widgetIds,
userAuthenticationData.accountId
)
}
fun addButton(
widgetId: WidgetId,
addButtonRequest: AddButtonRequest,
userBoardAuthenticationData: UserBoardAuthenticationData
): Mono<CollectionOfButtons> {
return collectionOfButtonsRepository.findByWidgetIdAndAccountId(
widgetId,
userBoardAuthenticationData.accountId
)
.flatMap { collectionOfButtons ->
idGeneratorService.generateId(IdType.BUTTON_ID)
.map { buttonId -> collectionOfButtons.addButton(buttonId, addButtonRequest) }
}
.flatMap { collectionOfButtonsRepository.save(it) }
.auditOnSuccess(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_ADD_BUTTON)
.auditOnError(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_ADD_BUTTON)
.logOnSuccess(message = "Successfully added button in Collection of buttons widget")
.logOnError(errorMessage = "Failed to add button in Collection of buttons widget")
}
fun updateButton(
widgetId: WidgetId,
buttonId: String,
addButtonRequest: AddButtonRequest,
userBoardAuthenticationData: UserBoardAuthenticationData
): Mono<CollectionOfButtons> {
return collectionOfButtonsRepository.findByWidgetIdAndAccountId(
widgetId,
userBoardAuthenticationData.accountId
)
.map { it.updateButton(buttonId, addButtonRequest) }
.flatMap { collectionOfButtonsRepository.save(it) }
.auditOnSuccess(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_UPDATE_BUTTON)
.auditOnError(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_UPDATE_BUTTON)
.logOnSuccess(message = "Successfully updated button in Collection of buttons widget")
.logOnError(errorMessage = "Failed to update button in Collection of buttons widget")
}
fun deleteButton(
widgetId: WidgetId,
buttonId: String,
userBoardAuthenticationData: UserBoardAuthenticationData
): Mono<CollectionOfButtons> {
return collectionOfButtonsRepository.findByWidgetIdAndAccountId(
widgetId,
userBoardAuthenticationData.accountId
)
.map { it.deleteButton(buttonId) }
.flatMap { collectionOfButtonsRepository.save(it) }
.auditOnSuccess(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_DELETE_BUTTON)
.auditOnError(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_DELETE_BUTTON)
.logOnSuccess(message = "Successfully deleted button in Collection of buttons widget")
.logOnError(errorMessage = "Failed to delete button in Collection of buttons widget")
}
fun updateButtonValue(
widgetId: WidgetId,
buttonId: String,
value: Int,
userBoardAuthenticationData: UserBoardAuthenticationData
): Mono<CollectionOfButtons> {
return collectionOfButtonsRepository.findByWidgetIdAndAccountId(
widgetId,
userBoardAuthenticationData.accountId
)
.map { it.updateButtonValue(buttonId, value) }
.flatMap { collectionOfButtonsRepository.save(it) }
.flatMap { collectionOfButtons ->
val widget = Widget(
widgetId = collectionOfButtons.widgetId,
widgetType = WidgetType.COLLECTION_OF_BUTTONS,
accountId = collectionOfButtons.accountId,
boardId = collectionOfButtons.boardId
)
val buttonState = ButtonState.from(collectionOfButtons, buttonId)
nodeBffGateway.updateCollectionOfButtonsButtonStatus(widget, buttonState)
.map { collectionOfButtons }
}
.auditOnSuccess(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_UPDATE_BUTTON_VALUE)
.auditOnError(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_UPDATE_BUTTON_VALUE)
.logOnSuccess(message = "Successfully updated button value in Collection of buttons widget")
.logOnError(errorMessage = "Failed to update button value in Collection of buttons widget")
}
fun updateSensorValue(
widgetId: WidgetId,
buttonId: String,
value: Int,
boardAuthenticationData: BoardAuthenticationData
): Mono<CollectionOfButtons> {
return collectionOfButtonsRepository.findByWidgetIdAndAccountId(
widgetId,
boardAuthenticationData.accountId
)
.map { it.updateButtonValue(buttonId, value) }
.flatMap { collectionOfButtonsRepository.save(it) }
.auditOnSuccess(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_UPDATE_SENSOR_VALUE)
.auditOnError(mqttPublisher, AuditEvent.COLLECTION_OF_BUTTONS_UPDATE_SENSOR_VALUE)
.logOnSuccess(message = "Successfully updated sensor value in Collection of buttons widget")
.logOnError(errorMessage = "Failed to update sensor value in Collection of buttons widget")
}
}
| 0 |
Kotlin
|
0
| 0 |
c5586a177d6aa13b23171b261874960a05132401
| 8,142 |
cloud-backend-service
|
MIT License
|
src/main/kotlin/kotlinmud/io/factory/SyntaxFactory.kt
|
brandonlamb
| 275,313,206 | true |
{"Kotlin": 435931, "Dockerfile": 133, "Shell": 126}
|
package kotlinmud.io.factory
import kotlinmud.io.type.Syntax
fun command(): List<Syntax> {
return listOf(Syntax.COMMAND)
}
fun availableNoun(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.AVAILABLE_NOUN)
}
fun freeForm(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.FREE_FORM)
}
fun drink(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.AVAILABLE_DRINK)
}
fun recipe(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.RECIPE)
}
fun itemFromMerchant(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.ITEM_FROM_MERCHANT)
}
fun itemInInventory(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.ITEM_IN_INVENTORY)
}
fun availableInventoryAndItem(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.AVAILABLE_ITEM_INVENTORY, Syntax.ITEM_IN_INVENTORY)
}
fun itemInInventoryAndAvailableInventory(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.AVAILABLE_ITEM_INVENTORY, Syntax.ITEM_IN_AVAILABLE_INVENTORY)
}
fun itemInRoom(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.ITEM_IN_ROOM)
}
fun resourceInRoom(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.RESOURCE_IN_ROOM)
}
fun resource(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.RESOURCE_IN_ROOM)
}
fun foodInInventory(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.AVAILABLE_FOOD)
}
fun spellFromHealer(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.SPELL_FROM_HEALER)
}
fun doorInRoom(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.DOOR_IN_ROOM)
}
fun mobInRoom(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.MOB_IN_ROOM)
}
fun directionToExit(): List<Syntax> {
return listOf(Syntax.DIRECTION_TO_EXIT)
}
fun skillToPractice(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.SKILL_TO_PRACTICE)
}
fun equippedItem(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.EQUIPPED_ITEM)
}
fun trainable(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.TRAINABLE)
}
fun equipmentInInventory(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.EQUIPMENT_IN_INVENTORY)
}
fun playerFreeForm(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.PLAYER_MOB, Syntax.FREE_FORM)
}
fun optionalFurniture(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.OPTIONAL_FURNITURE)
}
fun subcommandWithFreeForm(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.SUBCOMMAND, Syntax.FREE_FORM)
}
fun subcommandDirectionNoExit(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.SUBCOMMAND, Syntax.DIRECTION_WITH_NO_EXIT)
}
fun subcommand(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.SUBCOMMAND)
}
fun subcommandPlayerMob(): List<Syntax> {
return listOf(Syntax.COMMAND, Syntax.SUBCOMMAND, Syntax.PLAYER_MOB)
}
| 0 | null |
0
| 0 |
fc03c6230b9b3b66cd63994e74ddd7897732d527
| 2,809 |
kotlinmud
|
MIT License
|
libs/action-manager/src/main/kotlin/mono/actionmanager/RetainableActionType.kt
|
tuanchauict
| 325,686,408 | false |
{"Kotlin": 614290, "SCSS": 33498, "Python": 1834, "Shell": 935, "HTML": 885, "CSS": 728}
|
/*
* Copyright (c) 2023, tuanchauict
*/
package mono.actionmanager
import mono.common.MouseCursor
/**
* An enum class which defines all action types which repeatedly have effects after triggered.
*/
enum class RetainableActionType(val mouseCursor: MouseCursor) {
IDLE(MouseCursor.DEFAULT),
ADD_RECTANGLE(MouseCursor.CROSSHAIR),
ADD_TEXT(MouseCursor.TEXT),
ADD_LINE(MouseCursor.CROSSHAIR)
}
| 15 |
Kotlin
|
9
| 376 |
fb4c99a23173768bf935992f09692715c908cdae
| 413 |
MonoSketch
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/RunningTrack.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.RunningTrack: ImageVector
get() {
if (_runningTrack != null) {
return _runningTrack!!
}
_runningTrack = Builder(name = "RunningTrack", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(16.0f, 4.0f)
horizontalLineToRelative(-8.0f)
curveTo(3.589f, 4.0f, 0.0f, 7.589f, 0.0f, 12.0f)
reflectiveCurveToRelative(3.589f, 8.0f, 8.0f, 8.0f)
horizontalLineToRelative(8.0f)
curveToRelative(4.411f, 0.0f, 8.0f, -3.589f, 8.0f, -8.0f)
reflectiveCurveToRelative(-3.589f, -8.0f, -8.0f, -8.0f)
close()
moveTo(16.0f, 17.0f)
horizontalLineToRelative(-8.0f)
curveToRelative(-2.757f, 0.0f, -5.0f, -2.243f, -5.0f, -5.0f)
reflectiveCurveToRelative(2.243f, -5.0f, 5.0f, -5.0f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-5.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
reflectiveCurveToRelative(1.346f, 3.0f, 3.0f, 3.0f)
horizontalLineToRelative(8.0f)
curveToRelative(1.654f, 0.0f, 3.0f, -1.346f, 3.0f, -3.0f)
reflectiveCurveToRelative(-1.346f, -3.0f, -3.0f, -3.0f)
verticalLineToRelative(-2.0f)
curveToRelative(2.757f, 0.0f, 5.0f, 2.243f, 5.0f, 5.0f)
reflectiveCurveToRelative(-2.243f, 5.0f, -5.0f, 5.0f)
close()
}
}
.build()
return _runningTrack!!
}
private var _runningTrack: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,594 |
icons
|
MIT License
|
library/bitshares-kit-old/src/main/java/bitshareskit/models/SocketCall.kt
|
huskcasaca
| 464,732,039 | false | null |
package bitshareskit.models
import bitshareskit.extensions.buildJsonArray
import bitshareskit.extensions.buildJsonObject
import bitshareskit.objects.JsonSerializable
import bitshareskit.chain.BlockchainAPI
import bitshareskit.chain.CallMethod
import org.java_json.JSONArray
import org.java_json.JSONObject
data class SocketCall(
val method: String = RPC_METHOD,
val api: BlockchainAPI,
val rpc: String,
val params: List<Any?> = emptyList(),
val jsonrpc: String = JSONRPC_VERSION,
val subscribe: Boolean = false
): JsonSerializable {
constructor(
method: CallMethod,
params: List<Any?> = emptyList(),
subscribe: Boolean = false
) : this(
api = method.api,
rpc = method.nameString,
params = params,
subscribe = subscribe
)
companion object {
const val KEY_CALLBACK_ID = "id"
const val KEY_METHOD = "method"
const val KEY_PARAMS = "params"
const val KEY_JSONRPC = "jsonrpc"
const val RPC_METHOD = "call"
const val JSONRPC_VERSION = "2.0"
}
var id: Int = -1
var apiId: Int = -1
// val timestamp = System.currentTimeMillis()
override fun toJsonElement(): JSONObject {
val ordered = if (subscribe)
buildJsonArray {
put(id)
putAll(JSONArray(params))
} else JSONArray(params)
val paramsArray = buildJsonArray {
put(apiId)
put(rpc)
put(ordered)
}
return buildJsonObject {
put(KEY_CALLBACK_ID, id)
put(KEY_JSONRPC, jsonrpc)
put(KEY_METHOD, method)
put(KEY_PARAMS, paramsArray)
}
}
override fun equals(other: Any?): Boolean {
return other is SocketCall && rpc == other.rpc && params == other.params
}
override fun hashCode(): Int {
var result = method.hashCode()
result = 31 * result + api.hashCode()
result = 31 * result + rpc.hashCode()
result = 31 * result + params.hashCode()
result = 31 * result + jsonrpc.hashCode()
result = 31 * result + subscribe.hashCode()
result = 31 * result + (id ?: 0)
result = 31 * result + (apiId ?: 0)
return result
}
}
| 0 | null |
4
| 5 |
2522ec7169a5fd295225caf936bae2edf09b157e
| 2,293 |
bitshares-oases-android
|
MIT License
|
lib/src/main/kotlin/kiinse/me/plugins/minecore/lib/commands/MineContext.kt
|
kiinse
| 618,554,549 | false | null |
package kiinse.me.plugins.minecore.lib.commands
import kiinse.me.plugins.minecore.api.commands.CommandContext
import kiinse.me.plugins.minecore.api.files.locale.MineLocale
import org.bukkit.command.CommandSender
class MineContext(override val sender: CommandSender, override val senderLocale: MineLocale, override val args: Array<String>) : CommandContext {
override fun equals(other: Any?): Boolean {
return other != null && other is CommandContext && other.hashCode() == hashCode()
}
override fun toString(): String {
return """
Sender: ${sender.name}
Locale: $senderLocale
Args: ${args.contentToString()}
""".trimIndent()
}
override fun hashCode(): Int {
return toString().hashCode()
}
}
| 0 |
Kotlin
|
0
| 0 |
879337b9ccf2aad3c5ebddfcb98b4a5484f36221
| 791 |
MineCore
|
MIT License
|
src/main/kotlin/com/github/atsumerudev/api/metron/model/ResponseResult.kt
|
AtsumeruDev
| 584,515,155 | false | null |
package com.github.atsumerudev.api.metron.model
import com.github.atsumerudev.api.metron.util.itemOrEmpty
import java.io.Serializable
class ResponseResult<T> : Serializable {
var count = 0
var next: String? = null
get() = itemOrEmpty(field)
var previous: String? = null
get() = itemOrEmpty(field)
var results: List<T>? = null
get() = if (field == null) ArrayList() else field
}
| 0 |
Kotlin
|
0
| 0 |
5df48fef47f17e3498765b26a2b4378264227036
| 423 |
MetronAPI
|
MIT License
|
proxy/src/main/kotlin/net/rsprox/proxy/server/ServerPacket.kt
|
blurite
| 822,339,098 | false |
{"Kotlin": 1453055}
|
package net.rsprox.proxy.server
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufAllocator
import net.rsprot.buffer.extensions.toJagByteBuf
import net.rsprot.protocol.Prot
@Suppress("DuplicatedCode")
public class ServerPacket<out T : Prot>(
public val prot: T,
private val cipherMod1: Int,
private val cipherMod2: Int,
private var _payload: ByteBuf,
) {
public val payload: ByteBuf
get() = _payload
private var start: Int = payload.readerIndex()
public fun copy(payload: ByteBuf): ServerPacket<T> {
return ServerPacket(
prot,
cipherMod1,
cipherMod2,
payload,
)
}
public fun encode(
allocator: ByteBufAllocator,
mod: Boolean = true,
): ByteBuf {
// Ensure we always transfer the data from the first byte that the packet began at
payload.readerIndex(start)
val actualSize = payload.readableBytes()
// Allocate a buffer that can handle payload + opcode + var-short size
val buf = allocator.buffer(actualSize + 3).toJagByteBuf()
if (prot.opcode < 0x80) {
val modToUse = if (mod) this.cipherMod1 else 0
buf.p1(prot.opcode + modToUse)
} else {
val mod1ToUse = if (mod) this.cipherMod1 else 0
buf.p1((prot.opcode ushr 8 or 0x80) + mod1ToUse)
val mod2ToUse = if (mod) this.cipherMod2 else 0
buf.p1((prot.opcode and 0xFF) + mod2ToUse)
}
val constantSize = prot.size
if (constantSize == Prot.VAR_BYTE) {
buf.p1(actualSize)
} else if (constantSize == Prot.VAR_SHORT) {
buf.p2(actualSize)
}
buf.pdata(payload)
return buf.buffer
}
public fun replacePayload(buf: ByteBuf) {
val old = this._payload
try {
this._payload = buf
this.start = buf.readerIndex()
} finally {
old.release()
}
}
override fun toString(): String {
return "Packet(" +
"prot=$prot, " +
"payload=$payload" +
")"
}
}
| 2 |
Kotlin
|
4
| 9 |
41535908e6ccb633c8f2564e8961efa771abd6de
| 2,156 |
rsprox
|
MIT License
|
app/src/main/java/com/peng/repo/FavouriteRepository.kt
|
abdulwahabhassan
| 516,570,722 | false |
{"Kotlin": 146808}
|
package com.peng.repo
import com.peng.db.CartItemEntity
import com.peng.db.CartItemLocalDao
import com.peng.db.FavouriteItemEntity
import com.peng.db.FavouriteItemLocalDao
import javax.inject.Inject
// Repository to manage cart items
class FavouriteRepository @Inject constructor(private val favouriteItemLocalDao: FavouriteItemLocalDao) {
suspend fun getAllFavouriteItems(): List<FavouriteItemEntity> {
return favouriteItemLocalDao.getAllFavouriteItems()
}
suspend fun getFavouriteItem(id: String): FavouriteItemEntity? {
return favouriteItemLocalDao.getFavouriteItem(id)
}
suspend fun updateFavouriteItem(item: FavouriteItemEntity) {
favouriteItemLocalDao.updateFavouriteItem(item)
}
suspend fun insertFavouriteItem(item: FavouriteItemEntity) {
favouriteItemLocalDao.insertFavouriteItem(item)
}
suspend fun removeFavouriteItem(item: FavouriteItemEntity) {
favouriteItemLocalDao.removeFavouriteItem(item)
}
}
| 0 |
Kotlin
|
0
| 1 |
a03b09a604dab4bcf20794096f9b35c8b26ca583
| 996 |
peng
|
Apache License 2.0
|
src/main/kotlin/tech/espero/gruber/fullstackchallenge/security/JwtRequestFilter.kt
|
danielgruber
| 458,578,234 | false |
{"Kotlin": 72512}
|
package tech.espero.gruber.fullstackchallenge.security
import io.jsonwebtoken.ExpiredJwtException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Component
class JwtRequestFilter: OncePerRequestFilter() {
@Autowired
private val jwtUserDetailsService: JwtUserDetailsService? = null
@Autowired
private val jwtTokenUtil: JwtTokenUtil? = null
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
val requestTokenHeader = request.getHeader("Authorization")
var username: String? = null
var jwtToken: String? = null
// JWT Token is in the form "Bearer token". Remove Bearer word and get
// only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7)
try {
username = jwtTokenUtil!!.getUsernameFromToken(jwtToken)
} catch (e: IllegalArgumentException) {
println("Unable to get JWT Token")
} catch (e: ExpiredJwtException) {
println("JWT Token has expired")
}
} else {
logger.warn("JWT Token does not begin with Bearer String")
}
// Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().authentication == null) {
val userDetails = jwtUserDetailsService!!.loadUserByUsername(username)
// if token is valid configure Spring Security to manually set
// authentication
if (jwtTokenUtil!!.validateToken(jwtToken!!, userDetails)) {
val usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.authorities
)
usernamePasswordAuthenticationToken.details = WebAuthenticationDetailsSource().buildDetails(request)
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the
// Spring Security Configurations successfully.
SecurityContextHolder.getContext().authentication = usernamePasswordAuthenticationToken
}
}
filterChain.doFilter(request, response)
}
}
| 0 |
Kotlin
|
0
| 0 |
87323a708956e9577d659ebd100005388043d717
| 2,890 |
Full-stack-challenge
|
Apache License 2.0
|
subprojects/core/src/main/kotlin/com/handtruth/mc/mcsman/server/util/KoinLogger.kt
|
handtruth
| 417,843,728 | false | null |
package com.handtruth.mc.mcsman.server.util
import com.handtruth.kommon.Log
import org.koin.core.logger.Level
import org.koin.core.logger.Logger
import org.koin.core.logger.MESSAGE
internal class KoinLogger(private val log: Log) : Logger() {
override fun log(level: Level, msg: MESSAGE) {
when (level) {
Level.DEBUG -> log.debug { msg }
Level.INFO -> log.info { msg }
Level.ERROR -> log.error { msg }
Level.NONE -> {}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
58b2d4bd0413522dbf1cbabc1c8bab78e1b1edfe
| 498 |
mcsman
|
Apache License 2.0
|
app/src/main/java/com/tink/link/providerlist/ProviderListFragment.kt
|
prabhumurthy
| 262,982,459 | false | null |
package com.tink.link.providerlist
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController
import com.tink.link.R
import com.tink.link.extensions.toArrayList
import com.tink.link.financialinstitution.FinancialInstitutionListFragment
import com.tink.link.providertree.ARG_PROVIDER_TOOLBAR_TITLE
import com.tink.link.providertree.ARG_PROVIDER_TREE
import com.tink.link.providertree.ProviderTreeNodeFragment
import com.tink.model.provider.Provider
import com.tink.model.provider.ProviderTreeNode
import com.tink.model.provider.toProviderTree
import kotlinx.android.synthetic.main.layout_provider_tree_node_list.*
/**
* Fragment responsible for displaying a list of financial institution groups.
* This is the root level of the tree.
*/
class ProviderListFragment : ProviderTreeNodeFragment(R.layout.layout_provider_tree_node_list) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
title.setText(R.string.provider_list_title)
}
/**
* Navigate to the [FinancialInstitutionListFragment].
*/
override fun navigateToNode(node: ProviderTreeNode) {
findNavController().navigate(
R.id.action_providerListFragment_to_financialInstitutionListFragment,
bundleOf(
ARG_PROVIDER_TREE to (node as ProviderTreeNode.FinancialInstitutionGroupNode).financialInstitutions.toArrayList(),
ARG_PROVIDER_TOOLBAR_TITLE to node.name
)
)
}
companion object {
/**
* Create an arguments bundle.
*
* This transforms the [providers] list into a list of [ProviderTreeNode] objects.
*/
fun getBundle(providers: List<Provider>) =
bundleOf(ARG_PROVIDER_TREE to providers.toProviderTree().toArrayList())
}
}
| 0 |
Kotlin
|
0
| 0 |
741ad32fd03fb3029e098080b3d568a77bacc1ee
| 1,927 |
Brilliantts_fuzec32pay_ICCB
|
MIT License
|
app/src/main/kotlin/ru/vt/android/ui/CommonEventHandler.kt
|
magic-goop
| 522,567,133 | false |
{"Kotlin": 484480, "Shell": 117}
|
package ru.vt.android.ui
import ru.vt.core.common.event.CommonEvent
import ru.vt.core.common.event.EventHandler
import ru.vt.core.ui.feedback.FeedbackEvent
import ru.vt.core.ui.feedback.FeedbackToastEvent
import ru.vt.core.ui.feedback.UiHost
import timber.log.Timber
internal class CommonEventHandler(
private val uiHost: UiHost
) : EventHandler {
override fun handleEvent(event: CommonEvent) {
when (event) {
is FeedbackEvent -> uiHost.handleFeedbackEvent(event = event)
}
}
override fun handleError(t: Throwable) {
Timber.e(t)
uiHost.handleFeedbackEvent(FeedbackToastEvent(message = t.message ?: t.toString()))
}
}
| 0 |
Kotlin
|
0
| 2 |
b7ff60f72cc67f43755a75b05ef4ba6a06d02315
| 685 |
vitals-tracker
|
Apache License 2.0
|
katalog/katalog-runtime/src/jsMain/kotlin/ui/Showcases.kt
|
mpetuska
| 430,798,310 | false | null |
package dev.petuska.katalog.runtime.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import app.softwork.routingcompose.HashRouter
import app.softwork.routingcompose.NavLink
import dev.petuska.katalog.runtime.UtilStyle
import dev.petuska.katalog.runtime.domain.Showcase
import dev.petuska.katalog.runtime.katalog
import org.jetbrains.compose.web.css.Color
import org.jetbrains.compose.web.css.DisplayStyle
import org.jetbrains.compose.web.css.FlexDirection
import org.jetbrains.compose.web.css.LineStyle
import org.jetbrains.compose.web.css.Style
import org.jetbrains.compose.web.css.StyleSheet
import org.jetbrains.compose.web.css.backgroundColor
import org.jetbrains.compose.web.css.border
import org.jetbrains.compose.web.css.borderRadius
import org.jetbrains.compose.web.css.cursor
import org.jetbrains.compose.web.css.display
import org.jetbrains.compose.web.css.em
import org.jetbrains.compose.web.css.flexDirection
import org.jetbrains.compose.web.css.height
import org.jetbrains.compose.web.css.margin
import org.jetbrains.compose.web.css.marginRight
import org.jetbrains.compose.web.css.padding
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.css.value
import org.jetbrains.compose.web.css.width
import org.jetbrains.compose.web.dom.Div
private object ShowcasesStyle : StyleSheet() {
val container by style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Row)
margin(1.em)
}
val sideBar by style {
height(100.percent)
marginRight(1.em)
}
val content by style {
height(100.percent)
width(100.percent)
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Column)
}
val navLink by style {
cursor("pointer")
universal style {
margin(0.em)
padding(0.25.em)
property("transition-property", "background-color,border-color")
property("transition-duration", ".25s")
property("transition-timing-function", "ease-in-out")
borderRadius(0.25.em)
border(color = Color.transparent, width = 0.1.em, style = LineStyle.Solid)
self + hover style {
property("border-color", KatalogThemeVariables.highlightColor.value())
}
}
}
val navLinkSelected by style {
universal style {
backgroundColor(KatalogThemeVariables.highlightColor.value())
}
}
}
@Composable
internal fun Showcases() {
Style(ShowcasesStyle)
HashRouter(initPath = "") {
Div(attrs = {
classes(ShowcasesStyle.container)
}) {
val katalog = katalog
val showcases = remember { katalog.showcases.associateBy(Showcase::id) }
string { id ->
val showcase = showcases[id]
SideBar(showcase)
Content(showcase)
}
noMatch {
SideBar(null)
}
}
}
}
@Composable
private fun SideBar(selected: Showcase?) {
val theme = katalog.theme
Div(attrs = {
classes(ShowcasesStyle.sideBar, UtilStyle.roundedBoxShadow)
}) {
katalog.showcases.forEach { showcase ->
NavLink("/${showcase.id}", attrs = {
classes(ShowcasesStyle.navLink)
showcase.description?.let {
title(it)
}
if (selected == showcase) classes(ShowcasesStyle.navLinkSelected)
}) {
theme.navTitleRender(showcase.title, selected == showcase)
}
}
}
}
@Composable
private fun Content(showcase: Showcase?) {
Div(attrs = {
classes(ShowcasesStyle.content, UtilStyle.roundedBoxShadow)
}) {
if (showcase != null) {
ShowcaseBox(showcase)
}
}
}
| 9 |
Kotlin
|
13
| 99 |
c1ba9cf15d091916f1e253c4c37cc9f9c643f5e3
| 3,548 |
kmdc
|
Apache License 2.0
|
unboks/src/main/kotlin/unboks/FlowGraph.kt
|
flababah
| 420,456,365 | false |
{"Kotlin": 267652, "Java": 2338, "Shell": 156}
|
package unboks
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import unboks.internal.FlowGraphVisitor
import unboks.internal.MethodDescriptor
import unboks.internal.NameRegistry
import unboks.internal.codegen.generate
import unboks.pass.Pass
import unboks.pass.PassType
import unboks.pass.builtin.createConsistencyCheckPass
import java.lang.reflect.Modifier
import java.util.function.Consumer
/**
* Entry point into the API.
*/
class FlowGraph(vararg parameterTypes: Thing) : PassType {
private val constantMap = mutableMapOf<Any, Constant<*>>() // TODO WeakReference
private val _blocks = mutableSetOf<Block>()
private var _root: BasicBlock? = null
internal val nameRegistry = NameRegistry()
/**
* Set of basic/handler blocks in this flow.
*/
val blocks: Set<Block> get() = _blocks
/**
* NULL-literal.
*/
val nullConst = NullConst(this)
/**
* Gives the set of constants in use in the given [FlowGraph].
*/
val constants: Set<Constant<*>> get() = constantMap.values.asSequence()
.filter { it.uses.count > 0 }
.toSet()
/**
* Root/entry block of this flow. The first basic block added automatically becomes the root.
*/
var root: BasicBlock
get() = _root ?: throw IllegalStateException("No root")
set(value) {
if (value.graph !== this)
throw IllegalArgumentException("Foreign flow") // XXX ext function
_root = value
}
val parameters: List<Parameter> = parameterTypes.map { Parameter(this, it) }
/**
* Creates and adds a new basic block to this control flow graph.
*
* @param name of the new block, see [Nameable]. If empty, a generic name is used
*/
fun newBasicBlock(name: String = ""): BasicBlock {
val block = BasicBlock(this)
_blocks += block
if (_root == null)
_root = block
if (name.isNotEmpty())
block.name = name
return block
}
/**
* Creates and adds a new handler block to this control flow graph.
*
* @param defType of the exception def. Used as a hint -- does not dictate which exceptions
* are caught since multiple blocks with different handled type can be caught by the same
* handler. See [Block.exceptions] for actual types. TODO remove hint altogether?
* @param name of the new block, see [Nameable]. If empty, a generic name is used
*/
fun newHandlerBlock(defType: Reference? = null, name: String = ""): HandlerBlock {
val block = HandlerBlock(this, defType)
_blocks += block
if (name.isNotEmpty())
block.name = name
return block
}
/**
* Execute a pass on this flow.
*/
fun <R> execute(pass: Pass<R>): Pass<R> = pass.execute(this) {
it.visit(this)
constants.forEach { c -> it.visit(c) }
parameters.forEach { p -> it.visit(p) } // Not possible to mutate for now, so no need for copy.
_blocks.toTypedArray().forEach { block -> block.executeInitial(it) }
}
/**
* Compile the CFG for the method and emit it into an ASM [MethodVisitor].
*
* Calls the visit methods starting with [MethodVisitor.visitCode] and ends with [MethodVisitor.visitEnd].
* Will output 1.7+ compatible bytecode. For now, the receiving visitor must compute stack frames.
*/
fun generate(receiver: MethodVisitor) {
execute(createConsistencyCheckPass(this))
generate(this, receiver)
}
/**
* Returns a method visitor that uses visit calls from [MethodVisitor.visitCode] until (and including)
* [MethodVisitor.visitEnd]. These calls are not invoked on the delegate. All other calls are passed
* through to the delegate.
*
* @param completion is invoked after [MethodVisitor.visitEnd] has been invoked and the graph has been built
*
* @see Companion.visitMethod
*/
fun visitMethod(delegate: MethodVisitor?, completion: () -> Unit): MethodVisitor {
return FlowGraphVisitor(this, delegate, completion)
}
fun compactNames() {
nameRegistry.prune()
}
fun constant(value: Int): IntConst = reuseConstant(IntConst(this, value))
fun constant(value: Long): LongConst = reuseConstant(LongConst(this, value))
fun constant(value: Float): FloatConst = reuseConstant(FloatConst(this, value))
fun constant(value: Double): DoubleConst = reuseConstant(DoubleConst(this, value))
fun constant(value: String): StringConst = reuseConstant(StringConst(this, value))
fun constant(value: Thing): TypeConst = reuseConstant(TypeConst(this, value))
/**
* Prints simple text representation of the flow.
*/
fun summary(out: Appendable = System.out) {
for (block in blocks) {
out.append("$block\n")
for (ir in block.opcodes)
out.append("- $ir\n")
}
}
internal fun detachBlock(block: Block) = _blocks.remove(block)
@Suppress("UNCHECKED_CAST")
private fun <C : Constant<*>> reuseConstant(const: C) = constantMap.computeIfAbsent(const.value) { const } as C
companion object {
/**
* Convenience-method for doing transformations in [ClassVisitor.visitMethod].
*
* @param typeName internal name of the type this method is defined in (from [ClassVisitor.visit])
* @param delegate delegate class visitor (super) [ClassVisitor.cv]
* @param access see [ClassVisitor.visitMethod]
* @param name see [ClassVisitor.visitMethod]
* @param descriptor see [ClassVisitor.visitMethod]
* @param signature see [ClassVisitor.visitMethod]
* @param exceptions see [ClassVisitor.visitMethod]
* @param transformation call back allowing modifications to the graph before emitting code
* @return transforming visitor or [ClassVisitor.cv].visitMethod(...) if abstract or native
*/
fun visitMethod(
typeName: String,
delegate: ClassVisitor?,
access: Int,
name: String,
descriptor: String,
signature: String?,
exceptions: Array<out String>?,
transformation: (FlowGraph) -> Unit): MethodVisitor? {
val type = Reference.create(typeName)
val delegateMv = delegate?.visitMethod(access, name, descriptor, signature, exceptions)
if (Modifier.isAbstract(access) || Modifier.isNative(access))
return delegateMv
val ms = MethodDescriptor(descriptor)
val parameterTypes =
if (Modifier.isStatic(access)) ms.parameters
else listOf(type) + ms.parameters
val graph = FlowGraph(*parameterTypes.toTypedArray())
return graph.visitMethod(delegateMv) {
transformation(graph)
if (delegateMv != null)
graph.generate(delegateMv)
}
}
/**
* Convenience method for Java usage.
*
* @see visitMethod
*/
@JvmStatic
fun visitMethod(
typeName: String,
delegate: ClassVisitor?,
access: Int,
name: String,
descriptor: String,
signature: String?,
exceptions: Array<out String>?,
transformation: Consumer<FlowGraph>): MethodVisitor? {
return visitMethod(typeName, delegate, access, name, descriptor, signature, exceptions) {
transformation.accept(it)
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
44460c67e8bc806a2c12ea3b96670ad1eb45a569
| 6,780 |
unboks
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/animations/PropertyIndexedKeyframes.kt
|
karakum-team
| 393,199,102 | false | null |
// Automatically generated - do not modify!
package web.animations
import js.array.ReadonlyArray
sealed external interface PropertyIndexedKeyframes {
var composite: ReadonlyArray<CompositeOperationOrAuto> /* | CompositeOperationOrAuto */?
var easing: Any /* string | string[] */?
var offset: ReadonlyArray<Double?> /* | Double */?
// [property: string]: string | string[] | number | null | (number | null)[] | undefined
}
| 0 | null |
8
| 36 |
95b065622a9445caf058ad2581f4c91f9e2b0d91
| 441 |
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/jin/businfo_gumi/util/LocationUtil.kt
|
JinSagong
| 366,760,371 | false | null |
package com.jin.businfo_gumi.util
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.LocationManager
import android.net.Uri
import android.os.Looper
import android.provider.Settings
import androidx.core.content.ContextCompat
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
import com.gun0912.tedonactivityresult.TedOnActivityResult
import com.jin.businfo_gumi.R
import com.jin.businfo_gumi.widget.MsgBottomSheetDialog
import com.jin.businfo_gumi.widget.PermissionDialog
import com.jin.businfo_gumi.widget.Toasty
import kotlin.math.*
@Suppress("UNUSED")
class LocationUtil(private val activity: Activity, private val distance: Float = DEFAULT_DISTANCE) {
private val locationClient by lazy { LocationServices.getFusedLocationProviderClient(activity) }
private val locationManager by lazy { activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager }
private val locationRequest by lazy {
LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
interval = 5000
}
}
var hasRequested = false
private set
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) {
result?.let {
val lat = it.lastLocation.latitude.toFloat()
val lng = it.lastLocation.longitude.toFloat()
Debug.i("Location(lat:$lat, lng:$lng)")
trackBoundary(lat, lng)
}
}
override fun onLocationAvailability(availability: LocationAvailability?) {
if (availability?.isLocationAvailable != true) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// turn on the gps function
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
val client = LocationServices.getSettingsClient(activity)
client.checkLocationSettings(builder.build())
.addOnFailureListener {
if (it is ResolvableApiException) {
try {
it.startResolutionForResult(activity, REQUEST_LOCATION)
} catch (sendEx: IntentSender.SendIntentException) {
Debug.e("sendIntentException:${sendEx.message}")
cancelTracking()
}
}
}
} else {
cancelTracking(flag = false)
}
}
}
}
private var onUpdateLocationListener: ((Float, Float, Float) -> Unit)? = null
private var onFailureListener: ((Boolean) -> Unit)? = null
fun doOnUpdateLocation(l: (Float, Float, Float) -> Unit) =
apply { onUpdateLocationListener = l }
fun doOnFailure(l: (Boolean) -> Unit) = apply { onFailureListener = l }
fun startTracking() {
PermissionDialog.with(activity)
.setPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.doOnGranted { executeTracking() }
.doOnDenied {
MsgBottomSheetDialog.withTwoBtn(activity)
.setMessage(R.string.toPermissionSetting)
.setOnDoneListener {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", activity.packageName, null)
intent.data = uri
TedOnActivityResult.with(activity)
.setIntent(intent)
.setListener { _, _ ->
val isGranted = ContextCompat.checkSelfPermission(
activity, Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
if (isGranted) executeTracking() else {
onFailureListener?.invoke(true)
Toasty.alert(R.string.noPermission)
}
}
.startActivityForResult()
}
.setOnCancelListener {
onFailureListener?.invoke(true)
Toasty.alert(R.string.noPermission)
}
.show()
}
.check()
}
@SuppressLint("MissingPermission")
private fun executeTracking() {
try {
hasRequested = true
locationClient.requestLocationUpdates(
locationRequest, locationCallback, Looper.myLooper()!!
)
} catch (e: Exception) {
cancelTracking()
}
}
fun cancelTracking(doListener: Boolean = true, flag: Boolean = true) {
if (hasRequested) {
if (doListener) onFailureListener?.invoke(flag)
locationClient.removeLocationUpdates(locationCallback)
}
hasRequested = false
}
private fun trackBoundary(lat: Float, lng: Float) {
onUpdateLocationListener?.invoke(lat, lng, getRadius(distance))
}
companion object {
const val REQUEST_LOCATION = 213
const val RESPONSE_LOCATION_OK = -1
const val RESPONSE_LOCATION_CANCEL = 0
private const val DEFAULT_DISTANCE = 2000f // 2km
fun getDistance(lat1: Double, lng1: Double, lat2: Float, lng2: Float): Double {
return 1.609344 * 1000 * 60 * 1.1515 * 180 / PI * acos(
sin(lat1 * PI / 180) * sin(lat2 * PI / 180)
+ cos(lat1 * PI / 180) * cos(lat2 * PI / 180) * cos((lng2 - lng1) * PI / 180)
)
}
fun getRadius(distance: Float = DEFAULT_DISTANCE) =
distance / (1.609344f * 1000f * 60f * 1.1515f)
fun getDistanceText(distance: Double) =
if (distance < 1000) "${distance.roundToInt()}m"
else "${(distance / 10).roundToInt().toFloat() / 100}km"
}
}
| 0 |
Kotlin
|
0
| 1 |
30fde56859de44467730a202b0f74208f1a73d64
| 6,534 |
GumiBusInfo
|
Intel Open Source License
|
app/src/main/java/com/digitaldealsolution/tweeklabstask/ui/news/NewsFragment.kt
|
harshdigi
| 525,768,464 | false | null |
package com.digitaldealsolution.tweeklabstask.ui.news
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.digitaldealsolution.tweeklabstask.R
import com.digitaldealsolution.tweeklabstask.databinding.FragmentMyKitsBinding
import com.digitaldealsolution.tweeklabstask.databinding.FragmentNewsBinding
import com.digitaldealsolution.tweeklabstask.ui.mykits.MyKitsViewModel
class NewsFragment : Fragment() {
private var _binding: FragmentNewsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val newsViewModel =
ViewModelProvider(this).get(NewsViewModel::class.java)
_binding = FragmentNewsBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textNews
newsViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 |
Kotlin
|
0
| 0 |
453f585efa97e449b51b38276715dc8c24e62a5c
| 1,403 |
TweakLabTask
|
Apache License 2.0
|
kovibes/src/commonMain/kotlin/io/github/rubenquadros/kovibes/api/AuthStorage.kt
|
rubenquadros
| 758,569,353 | false |
{"Kotlin": 130832}
|
package io.github.rubenquadros.kovibes.api
import kotlin.io.encoding.Base64
/**
* AuthStorage is responsible to store the [accessToken].
*
*/
internal class AuthStorage {
private var clientId: String = ""
private var clientSecret: String = ""
private var accessToken: String = ""
/**
* Init the storage.
*
* @param clientId
* @param clientSecret
*/
fun init(clientId: String, clientSecret: String) {
this.clientId = clientId
this.clientSecret = clientSecret
}
/**
* Return the access token.
*
* @return [String].
*/
fun getAccessToken(): String {
return accessToken
}
/**
* Update access token with a new one after expiry.
*
* @param accessToken
*/
fun updateAccessToken(accessToken: String) {
this.accessToken = accessToken
}
/**
* Encode the [clientId] and [clientSecret] and return the encoded string.
*
* @return [String].
*/
@OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)
fun getEncodedCredentials(): String {
return Base64.encode(
source = "$clientId:$clientSecret".toByteArray()
)
}
}
| 0 |
Kotlin
|
0
| 0 |
3e4d6667f18980a9778c2c3cd964c7e499eee5a8
| 1,223 |
KoVibes
|
MIT License
|
logging-android-appcenter/src/main/java/com/fsryan/tools/logging/android/AppCenterAnalyticsEventLogger.kt
|
andy-andy
| 222,558,782 | true |
{"Kotlin": 80500, "Java": 2810}
|
package com.fsryan.tools.logging.android
import android.content.Context
import android.content.res.Resources
import com.microsoft.appcenter.analytics.Analytics
import com.microsoft.appcenter.analytics.EventProperties
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArraySet
class AppCenterAnalyticsEventLogger : ContextSpecificEventLogger {
private val countableAttrs: MutableMap<String, Long> = ConcurrentHashMap()
private val userProperties: MutableMap<String, String> = ConcurrentHashMap()
private val doubleProperties: MutableSet<String> = CopyOnWriteArraySet()
private val longProperties: MutableSet<String> = CopyOnWriteArraySet()
private val booleanProperties: MutableSet<String> = CopyOnWriteArraySet()
override fun id() = "appcenter"
override fun initialize(context: Context) {
storePropertyNamesInto(context, "fs_appcenter_double_properties", doubleProperties)
storePropertyNamesInto(context, "fs_appcenter_long_properties", longProperties)
storePropertyNamesInto(context, "fs_appcenter_boolean_properties", booleanProperties)
}
override fun addAttr(attrName: String, attrValue: String) {
userProperties[attrName] = attrValue
try {
countableAttrs[attrName] = attrValue.toLong()
} catch (nfe: NumberFormatException) {}
}
override fun incrementAttrValue(attrName: String) = addAttr(attrName, ((countableAttrs[attrName] ?: 0L) + 1).toString())
override fun addEvent(eventName: String, attrs: Map<String, String>) = Analytics.trackEvent(
eventName,
EventProperties().apply {
(userProperties + attrs).forEach { (key, value) ->
when {
doubleProperties.contains(key) -> set(key, value.toDouble())
longProperties.contains(key) -> set(key, value.toLong())
booleanProperties.contains(key) -> set(key, value.toBoolean())
else -> set(key, value)
}
}
}
)
private fun storePropertyNamesInto(context: Context, stringArrayName: String, dest: MutableSet<String>) {
val arrayRes = context.resources.getIdentifier(stringArrayName, "array", context.packageName)
if (arrayRes == 0) {
throw IllegalStateException("must have string-array resource $stringArrayName")
}
try {
dest.addAll(context.resources.getStringArray(arrayRes))
} catch (rnfe : Resources.NotFoundException) {
throw IllegalArgumentException("Error finding string-array resource: '$stringArrayName' ($arrayRes)")
}
}
}
| 0 | null |
0
| 0 |
0b27f58eabea92af88dc3ebeb6ad42c321197211
| 2,681 |
logging
|
Apache License 2.0
|
lib/agency/src/main/kotlin/org/kkris/osmgtfs/agency/matcher/StopMatcher.kt
|
kkris
| 273,951,336 | false | null |
package org.kkris.osmgtfs.agency.matcher
import org.kkris.osmgtfs.common.model.stop.Stop
interface StopMatcher {
fun match(stopName: String, stops: List<Stop>): Stop?
}
| 0 |
Kotlin
|
0
| 2 |
263d25158c2741dd00d639d1b17a95080f761db7
| 174 |
osm-gtfs
|
MIT License
|
redpacket/src/main/java/com/fzm/chat/redpacket/data/bean/AccountAsset.kt
|
txchat
| 507,831,442 | false |
{"Kotlin": 2234450, "Java": 384844}
|
package com.fzm.chat.redpacket.data.bean
import java.io.Serializable
data class AccountAsset(
/**
* ๅธๅท็ๅฐๅ
*/
val addr: String,
/**
* ๅธๅทๆป้ข
*/
val currency: Long,
/**
* ๅธๅท็ๅฏ็จไฝ้ข
*/
val balance: String,
/**
* ๅธๅทไธญๅป็ปไฝ้ข
*/
val frozen: String,
) : Serializable {
/**
* ๅธ็ง็ฒพๅบฆ๏ผๅฐๆฐ็นๅ้ข็ฒพ็กฎไฝๆฐ
*/
var accuracy: Int = 0
var name: String? = null
data class Wrapper(
/**
* tokenๆ ่ฎฐ็ฌฆ
*/
val symbol: String,
val account: AccountAsset
) : Serializable
data class TokenAsset(
val tokenAssets: List<Wrapper>
) : Serializable
}
data class Token(
val name: String?,
val symbol: String?
) : Serializable {
data class Wrapper(
val tokens: List<Token>
) : Serializable
}
| 0 |
Kotlin
|
1
| 1 |
6a3c6edf6ae341199764d4d08dffd8146877678b
| 831 |
ChatPro-Android
|
MIT License
|
src/me/anno/ecs/components/chunks/cartesian/ChunkSystem.kt
|
AntonioNoack
| 266,471,164 | false | null |
package me.anno.ecs.components.chunks.cartesian
import me.anno.ecs.components.chunks.PlayerLocation
import org.joml.Vector3d.lengthSquared
import org.joml.Vector3i
import kotlin.math.max
import kotlin.math.min
/**
* general chunk system,
* LODs can be generated e.g. with OctTree
* */
abstract class ChunkSystem<Chunk, Element>(
val bitsX: Int,
val bitsY: Int,
val bitsZ: Int,
initialCapacity: Int = 256
) : Iterable<MutableMap.MutableEntry<Vector3i, Chunk>> {
val chunks = HashMap<Vector3i, Chunk>(initialCapacity)
val sizeX = 1 shl bitsX
val sizeY = 1 shl bitsY
val sizeZ = 1 shl bitsZ
val totalSize = 1 shl (bitsX + bitsY + bitsZ)
val maskX = sizeX - 1
val maskY = sizeY - 1
val maskZ = sizeZ - 1
abstract fun createChunk(
chunkX: Int, chunkY: Int, chunkZ: Int,
size: Int
): Chunk
abstract fun getElement(
container: Chunk, localX: Int, localY: Int, localZ: Int,
yzxIndex: Int
): Element
abstract fun setElement(
container: Chunk, localX: Int, localY: Int, localZ: Int,
yzxIndex: Int, element: Element
): Boolean
fun getChunk(chunkX: Int, chunkY: Int, chunkZ: Int, generateIfMissing: Boolean): Chunk? {
val key = Vector3i(chunkX, chunkY, chunkZ)
return if (generateIfMissing) {
synchronized(chunks) {
chunks.getOrPut(key) {
val chunk = createChunk(chunkX, chunkY, chunkZ, totalSize)
onCreateChunk(chunk, chunkX, chunkY, chunkZ)
chunk
}
}
} else chunks[key]
}
fun getChunkAt(globalX: Double, globalY: Double, globalZ: Double, generateIfMissing: Boolean): Chunk? {
val cx = globalX.toInt() shr bitsX
val cy = globalY.toInt() shr bitsY
val cz = globalZ.toInt() shr bitsZ
return getChunk(cx, cy, cz, generateIfMissing)
}
fun getChunkAt(globalX: Int, globalY: Int, globalZ: Int, generateIfMissing: Boolean): Chunk? {
val cx = globalX shr bitsX
val cy = globalY shr bitsY
val cz = globalZ shr bitsZ
return getChunk(cx, cy, cz, generateIfMissing)
}
fun getElementAt(globalX: Int, globalY: Int, globalZ: Int, generateIfMissing: Boolean): Element? {
val chunk = getChunkAt(globalX, globalY, globalZ, generateIfMissing) ?: return null
val lx = globalX and maskX
val ly = globalY and maskY
val lz = globalZ and maskZ
return getElement(
chunk, lx, ly, lz,
getYZXIndex(lx, ly, lz)
)
}
fun setElementAt(globalX: Int, globalY: Int, globalZ: Int, generateIfMissing: Boolean, element: Element): Boolean {
val chunk = getChunkAt(globalX, globalY, globalZ, generateIfMissing) ?: return false
val lx = globalX and maskX
val ly = globalY and maskY
val lz = globalZ and maskZ
return setElement(
chunk, lx, ly, lz,
getYZXIndex(lx, ly, lz),
element
)
}
fun getYZXIndex(localX: Int, localY: Int, localZ: Int): Int {
return localX + (localZ + localY.shl(bitsZ)).shl(bitsX)
}
fun decodeYZXIndex(yzx: Int, dst: Vector3i = Vector3i()): Vector3i {
dst.x = yzx and maskX
val yz = yzx shr bitsX
dst.z = yz and maskZ
val y = yz shr bitsZ
dst.y = y and maskY
return dst
}
// todo we might want a function, where we process neighbors as well, e.g. 3x3x3 or 5x5x5, or 1x3x1 or sth like that
fun process(
min: Vector3i,
max: Vector3i,
generateIfMissing: Boolean,
processor: (x: Int, y: Int, z: Int, e: Element) -> Unit
) {
// iterate in chunks
// don't generate, if not generateIfMissing
// todo currently this might only work for positive values, idk
val minX = min.x shr bitsX
val maxX = (max.x + sizeX - 1) shr bitsX
val minY = min.y shr bitsY
val maxY = (max.y + sizeY - 1) shr bitsY
val minZ = min.z shr bitsZ
val maxZ = (max.z + sizeZ - 1) shr bitsZ
for (cy in minY..maxY) {
for (cz in minZ..maxZ) {
for (cx in minX..maxX) {
val chunk = getChunk(cx, cy, cz, generateIfMissing)
if (chunk != null) {
val baseX = cx shl bitsX
val baseY = cy shl bitsY
val baseZ = cz shl bitsZ
val minX2 = max(min.x, baseX)
val maxX2 = min(max.x, baseX + sizeX)
val minY2 = max(min.y, baseY)
val maxY2 = min(max.y, baseY + sizeY)
val minZ2 = max(min.z, baseZ)
val maxZ2 = min(max.z, baseZ + sizeZ)
for (y in minY2 until maxY2) {
for (z in minZ2 until maxZ2) {
var yzxIndex = getYZXIndex(minX2, y, z)
for (x in minX2 until maxX2) {
val element = getElement(chunk, x, y, z, yzxIndex++)
processor(x, y, z, element)
}
}
}
}
}
}
}
}
/**
* @param loadingDistance in this radius, new chunks are created
* @param unloadingDistance outside this radius, chunks are destroyed
* @param players basis for loading & unloading chunks
* */
fun updateVisibility(
loadingDistance: Double,
unloadingDistance: Double,
players: List<PlayerLocation>
) {
// ensure every player is inside a chunk
for (player in players) {
getChunkAt(player.x, player.y, player.z, true)
}
// load chunks, which need to be loaded, because they are close
// unload chunks, which no longer need to be loaded
// use sth like k nearest neighbors for this (??)...
synchronized(chunks) {
val sx2 = sizeX * 0.5
val sy2 = sizeY * 0.5
val sz2 = sizeZ * 0.5
chunks.entries.removeIf { (pos, chunk) ->
val px = (pos.x shl bitsX) + sx2
val py = (pos.y shl bitsY) + sy2
val pz = (pos.z shl bitsZ) + sz2
val shallRemove = players.all {
val dist = lengthSquared(px - it.x, py - it.y, pz - it.z)
dist * it.unloadMultiplier > unloadingDistance
}
if (shallRemove) onDestroyChunk(chunk, pos.x, pos.y, pos.z)
shallRemove
}
val sides = listOf(
Vector3i(-1, 0, 0),
Vector3i(+1, 0, 0),
Vector3i(0, -1, 0),
Vector3i(0, +1, 0),
Vector3i(0, 0, -1),
Vector3i(0, 0, +1),
)
for ((pos, _) in chunks) {
val px = (pos.x shl bitsX) + sx2
val py = (pos.y shl bitsY) + sy2
val pz = (pos.z shl bitsZ) + sz2
for ((dx, dy, dz) in sides) {
val cx = px + dx * sizeX
val cy = py + dy * sizeY
val cz = pz + dz * sizeZ
if (players.any { p ->
val dist = lengthSquared(cx - p.x, cy - p.y, cz - p.z)
dist * p.loadMultiplier < loadingDistance
}) {
getChunk(pos.x + dx, pos.y + dy, pos.z + dz, true)
}
}
}
}
}
open fun onCreateChunk(chunk: Chunk, chunkX: Int, chunkY: Int, chunkZ: Int) {}
open fun onDestroyChunk(chunk: Chunk, chunkX: Int, chunkY: Int, chunkZ: Int) {}
override fun iterator() = chunks.iterator()
operator fun Vector3i.component1() = x
operator fun Vector3i.component2() = y
operator fun Vector3i.component3() = z
}
| 0 |
Kotlin
|
1
| 8 |
e5f0bb17202552fa26c87c230e31fa44cd3dd5c6
| 8,150 |
RemsStudio
|
Apache License 2.0
|
app/src/main/java/com/nvkhang96/tymexgithubusers/github_users/domain/repositories/UserRepository.kt
|
nvkhang96
| 877,077,444 | false |
{"Kotlin": 69643}
|
package com.nvkhang96.tymexgithubusers.github_users.domain.repositories
import androidx.paging.PagingData
import com.nvkhang96.tymexgithubusers.base.data.utils.DataResult
import com.nvkhang96.tymexgithubusers.github_users.domain.models.User
import kotlinx.coroutines.flow.Flow
/**
* A repository interface for accessing user data.
*
* This interface provides methods for retrieving user data from the database,
* including a paginated list of users and details for a specific user.
*/
interface UserRepository {
/**
* Retrieves a paginated list of users from the database.
*
* This function returns a [Flow] of [PagingData] containing [User] objects.
* The [PagingData] is designed to be used with Paging 3 for efficient loading
* and display of large lists in UI elements like `RecyclerView`.
*
* @return A [Flow] of [PagingData] containing [User] objects.
*/
fun getUsersPaging(): Flow<PagingData<User>>
/**
* Retrieves the details of a specific user by their username.
*
* This function fetches the detailed information of a user identified by the provided `username`.
* It returns a [Flow] of [DataResult] objects, which encapsulate the result of the operation,
* including potential success ([DataResult.Success]) or failure ([DataResult.Error]) scenarios.
*
* The emitted [DataResult] will contain a [User] object upon successful retrieval.
*
* @param username The username of the user to retrieve details for.
* @return A [Flow] emitting [DataResult] objects, wrapping either a [User] on success or
* an error indication on failure.
*/
suspend fun getUserDetail(username: String): Flow<DataResult<User>>
}
| 0 |
Kotlin
|
0
| 0 |
9d04290a9ac7aaae5dcf21f11f15d28111bd4d44
| 1,745 |
TymeXGitHubUsers
|
Apache License 2.0
|
app/src/main/java/com/sandeep/easynotification/notification/models/NotificationAction.kt
|
sandeepgurram
| 160,318,197 | false | null |
package com.sandeep.easynotification.notification.models
import android.app.PendingIntent
import androidx.annotation.DrawableRes
data class NotificationAction(
val name: String,
@DrawableRes val icon: Int = 0,
val pendingIntent: PendingIntent?
)
| 0 |
Kotlin
|
0
| 0 |
395c84817da7cf1f40a6e304c5a765cf99a3082e
| 259 |
Easy-Notification
|
Apache License 2.0
|
app/src/main/java/me/jaxvy/kotlinboilerplate/api/request/BaseRequest.kt
|
jaxvy
| 96,854,265 | false | null |
package me.jaxvy.kotlinboilerplate.api.request
import io.reactivex.Single
abstract class BaseRequest<T>(
private var onSuccess: (() -> Unit)? = null,
private var onError: ((Throwable) -> Unit)? = null
) : InjectionBase() {
abstract fun getSingle(): Single<T>
fun onComplete() {
onSuccess?.invoke()
}
fun onFail(throwable: Throwable) {
onError?.invoke(throwable)
}
/**
* Database operations (for caching incoming response data) is performed on the IO thread. This
* method is the callback to implement db operation on Room
*/
open fun databaseOperationCallback(t: T) {}
}
| 0 |
Kotlin
|
1
| 0 |
a9581d9dc388683caa52a8122b7295b7fcca2a5c
| 651 |
android-kotlin-arch-boilerplate
|
MIT License
|
demo/demo/src/jvmMain/kotlin/zakadabar/demo/backend/misc/PingBackend.kt
|
kondorj
| 355,137,640 | true |
{"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253}
|
/*
* Copyright ยฉ 2020, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.demo.backend.misc
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
import zakadabar.stack.backend.custom.CustomBackend
object PingBackend : CustomBackend() {
override fun onInstallRoutes(route: Route) {
with(route) {
get("ping") {
call.respond("pong")
}
}
}
}
| 0 | null |
0
| 0 |
2379c0fb031f04a230e753a9afad6bd260f6a0b2
| 493 |
zakadabar-stack
|
Apache License 2.0
|
security/backend/src/main/kotlin/ams/abramelin/security/auth/controller/request/DecodeRequest.kt
|
tilau2328
| 156,662,968 | false | null |
package ams.abramelin.security.auth.controller.request
data class DecodeRequest(val token: String)
| 0 |
Kotlin
|
0
| 0 |
e9889bfd73056ef4c07c48ec1bc85e0e2cda61be
| 99 |
Abramelin
|
Apache License 2.0
|
interactors/src/main/java/app/tivi/interactors/Interactor.kt
|
kumamon-git
| 143,403,157 | true |
{"Kotlin": 535436, "Shell": 2064, "Java": 737}
|
/*
* Copyright 2018 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.interactors
import android.arch.paging.DataSource
import app.tivi.extensions.toFlowable
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.BehaviorSubject
import kotlinx.coroutines.experimental.CoroutineDispatcher
import kotlinx.coroutines.experimental.CoroutineStart
import kotlinx.coroutines.experimental.DefaultDispatcher
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.launch
import kotlin.coroutines.experimental.CoroutineContext
interface Interactor<in P> {
val dispatcher: CoroutineDispatcher
suspend operator fun invoke(param: P)
}
interface Interactor2<P, T> : Interactor<P> {
fun observe(): Flowable<T>
fun clear()
}
interface PagingInteractor<P, T> : Interactor<P> {
fun dataSourceFactory(): DataSource.Factory<Int, T>
}
abstract class SubjectInteractor<P, T> : Interactor2<P, T> {
private var disposable: Disposable? = null
private val subject: BehaviorSubject<T> = BehaviorSubject.create()
final override suspend fun invoke(param: P) {
setSource(createObservable(param))
execute(param)
}
protected abstract fun createObservable(param: P): Flowable<T>
protected abstract suspend fun execute(param: P)
override fun clear() {
disposable?.dispose()
disposable = null
}
final override fun observe(): Flowable<T> = subject.toFlowable()
private fun setSource(source: Flowable<T>) {
disposable?.dispose()
disposable = source.subscribe(subject::onNext, subject::onError)
}
}
@Suppress("UNCHECKED_CAST")
fun <T> emptyInteractor(): Interactor<T> = EmptyInteractor as Interactor<T>
internal object EmptyInteractor : Interactor<Unit> {
override val dispatcher: CoroutineDispatcher
get() = DefaultDispatcher
override suspend fun invoke(param: Unit) = Unit
}
fun <P> launchInteractor(
interactor: Interactor<P>,
param: P,
context: CoroutineContext = interactor.dispatcher,
start: CoroutineStart = CoroutineStart.DEFAULT,
parent: Job? = null
) = launch(context = context, start = start, parent = parent, block = { interactor(param) })
| 0 |
Kotlin
|
0
| 0 |
576ce71a830303f3a78bf0ed20ef4dd9e6f93b1d
| 2,792 |
tivi
|
Apache License 2.0
|
app/src/main/java/com/jlmari/android/basepokedex/main/MainActivity.kt
|
jlmari
| 561,303,847 | false |
{"Kotlin": 127493}
|
package com.jlmari.android.basepokedex.main
import com.jlmari.android.basepokedex.R
import com.jlmari.android.basepokedex.application.di.AppComponent
import com.jlmari.android.basepokedex.base.BaseActivity
import com.jlmari.android.basepokedex.presentation.main.MainContract
class MainActivity : BaseActivity<MainContract.View, MainContract.Router, MainContract.Presenter>(),
MainContract.View, MainContract.Router {
override val layoutResId = R.layout.ac_main
override fun injectDependencies(appComponent: AppComponent?) {
appComponent?.mainComponentFactory()
?.create()
?.inject(this)
}
}
| 0 |
Kotlin
|
0
| 0 |
3dcb577c0bf011e30c5769c21202aa6d98e94f8f
| 643 |
BasePokedex
|
Apache License 2.0
|
repl/src/main/java/dev/martianzoo/repl/commands/PhaseCommand.kt
|
MartianZoo
| 565,478,564 | false | null |
package dev.martianzoo.repl.commands
import dev.martianzoo.repl.ReplCommand
import dev.martianzoo.repl.ReplSession
internal class PhaseCommand(val repl: ReplSession) : ReplCommand("phase") {
override val usage = "phase <phase name>"
override val help =
"""
Asks the engine to begin a new phase, e.g. `phase Corporation`
"""
override fun withArgs(args: String) =
repl.describeExecutionResults(repl.access().phase(args.trim()))
}
| 35 |
Kotlin
|
2
| 8 |
dd2908659aa7c7a18a72e8ca862111952fca0433
| 462 |
solarnet
|
Apache License 2.0
|
presentation/src/main/java/com/jslee/presentation/feature/detail/viewholder/info/MovieInfoViewHolder.kt
|
JaesungLeee
| 675,525,103 | false |
{"Kotlin": 281300}
|
package com.jslee.presentation.feature.detail.viewholder.info
import com.jslee.core.ui.base.BaseViewHolder
import com.jslee.core.ui.decoration.CommonItemDecoration
import com.jslee.core.ui.decoration.LayoutType
import com.jslee.core.ui.model.PaddingValues
import com.jslee.presentation.databinding.ItemDetailInfoBinding
import com.jslee.presentation.feature.detail.adapter.info.MovieInfoListAdapter
import com.jslee.presentation.feature.detail.model.item.DetailListItem
/**
* MooBeside
* @author jaesung
* @created 2023/10/21
*/
class MovieInfoViewHolder(
private val binding: ItemDetailInfoBinding,
) : BaseViewHolder<DetailListItem.MovieInfo>(binding) {
private val movieInfoListAdapter = MovieInfoListAdapter()
init {
initMovieInfoList()
}
private fun initMovieInfoList() = with(binding.rvMovieInfo) {
adapter = movieInfoListAdapter
val paddingValues = PaddingValues.horizontal(0, 24)
addItemDecoration(CommonItemDecoration(paddingValues, LayoutType.HORIZONTAL))
}
override fun bindItems(item: DetailListItem.MovieInfo) = with(binding) {
movieInfo = item.movieInfoData
movieInfoListAdapter.submitList(item.movieInfoData.movieInfoData)
executePendingBindings()
}
}
| 10 |
Kotlin
|
0
| 3 |
7829fdfe77bc3cbedf8597e5ed7acae789a43841
| 1,264 |
MooBeside
|
MIT License
|
kommons-junit-jupiter/src/test/kotlin/io/kommons/junit/jupiter/system/SystemPropertyExtensionMetaTest.kt
|
debop
| 235,066,649 | false | null |
package io.kommons.junit.jupiter.system
import io.kommons.junit.jupiter.utils.ExtensionTester
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldEqual
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.TestInstance.Lifecycle
import org.junit.jupiter.api.parallel.Execution
import org.junit.jupiter.api.parallel.ExecutionMode
import org.junit.platform.engine.discovery.DiscoverySelectors.selectClass
import org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod
/**
* ๋ค๋ฅธ ํ
์คํธ ํด๋์ค์ ๋ฉ์๋๋ฅผ ์ํํ๊ณ , ์์คํ
์์ฑ์ด ์๋ณต๋๋์ง ํ์ธํ๋ค
*/
@TestInstance(Lifecycle.PER_CLASS)
@Execution(ExecutionMode.SAME_THREAD)
class SystemPropertyExtensionMetaTest {
@Test
fun `ํด๋์ค ๋จ์๋ก ์์คํ
์์ฑ์ ์๋ณต๋๋ค`() {
// ์ํ ์์ฑ
System.setProperty("classPropertyC", "no")
//ํ
์คํธ ์ํ ์์๋ classPropertyValueC ๋ก ์ค์ ๋๋ค
ExtensionTester.execute(selectClass(SystemPropertyExtensionClassTest::class.java))
// ๋ณต์๋ ์์ฑ
System.getProperty("classPropertyC") shouldEqual "no"
}
@Test
fun `ํด๋์ค ๋จ์๋ก ์์คํ
์์ฑ๋ค์ด ์๋ณต๋๋ค`() {
// ์ํ ์์ฑ
System.setProperty("classPropertyA", "no")
System.setProperty("classPropertyB", "yes")
//ํ
์คํธ ์ํ ์์๋ classPropertyValueC ๋ก ์ค์ ๋๋ค
ExtensionTester.execute(selectClass(SystemPropertyExtensionClassTest::class.java))
// ๋ณต์๋ ์์ฑ
System.getProperty("classPropertyA") shouldEqual "no"
System.getProperty("classPropertyB") shouldEqual "yes"
}
@Test
fun `๋ฉ์๋ ๋จ์๋ก ์์คํ
์์ฑ์ ์๋ณต๋๋ค`() {
// ์ํ ์์ฑ
System.setProperty("keyC", "no")
//ํ
์คํธ ์ํ ์์๋ classPropertyValueC ๋ก ์ค์ ๋๋ค
ExtensionTester.execute(selectMethod(SystemPropertyExtensionClassTest::class.java, "๋ฉ์๋ ๋จ์๋ก ํ
์คํธ๋ฅผ ์ํ ์์คํ
์์ฑ์ ์ค์ "))
// ๋ณต์๋ ์์ฑ
System.getProperty("keyC") shouldEqual "no"
}
@Test
fun `๋ฉ์๋ ๋จ์๋ก ํ
์คํธ ์, ๊ธฐ์กด ์์ฑ์ด ์๋ ๊ฒฝ์ฐ null ๋ก ๋ฆฌ์
๋๋ค`() {
// ์ํ ์์ฑ
System.clearProperty("keyC")
//ํ
์คํธ ์ํ ์์๋ classPropertyValueC ๋ก ์ค์ ๋๋ค
ExtensionTester.execute(selectMethod(SystemPropertyExtensionClassTest::class.java, "๋ฉ์๋ ๋จ์๋ก ํ
์คํธ๋ฅผ ์ํ ์์คํ
์์ฑ์ ์ค์ "))
// ๋ณต์๋ ์์ฑ
System.getProperty("keyC").shouldBeNull()
}
}
| 0 |
Kotlin
|
11
| 53 |
c00bcc0542985bbcfc4652d0045f31e5c1304a70
| 2,232 |
kotlin-design-patterns
|
Apache License 2.0
|
src/backend/oci/api-oci/src/main/kotlin/com/tencent/bkrepo/oci/constant/OciErrorMessageConstants.kt
|
TencentBlueKing
| 548,243,758 | false |
{"Kotlin": 13715127, "Vue": 1261493, "JavaScript": 683823, "Shell": 124343, "Lua": 101021, "SCSS": 34137, "Python": 25877, "CSS": 17382, "HTML": 13052, "Dockerfile": 4483, "Smarty": 3661, "Java": 423}
|
/*
* Tencent is pleased to support the open source community by making BK-CI ่้ฒธๆ็ปญ้ๆๅนณๅฐ available.
*
* Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-CI ่้ฒธๆ็ปญ้ๆๅนณๅฐ is licensed under the MIT license.
*
* A copy of the MIT License is included in this file.
*
*
* Terms of the MIT License:
* ---------------------------------------------------
* 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.tencent.bkrepo.oci.constant
const val BLOB_UNKNOWN_CODE = "BLOB_UNKNOWN"
const val BLOB_UNKNOWN_MESSAGE = "blob unknown to registry"
const val BLOB_UNKNOWN_DESCRIPTION = "This error MAY be returned when a blob is unknown to the " +
"registry in a specified repository. This can be returned with a standard get or if a manifest " +
"references an unknown layer during upload."
const val BLOB_UPLOAD_INVALID_CODE = "BLOB_UPLOAD_INVALID"
const val BLOB_UPLOAD_INVALID_MESSAGE = "blob upload invalid"
const val BLOB_UPLOAD_INVALID_DESCRIPTION = "The blob upload encountered an error and can no longer proceed."
const val BLOB_UPLOAD_UNKNOWN_CODE = "BLOB_UPLOAD_UNKNOWN"
const val BLOB_UPLOAD_UNKNOWN_MESSAGE = "blob upload unknown to registry"
const val BLOB_UPLOAD_UNKNOWN_DESCRIPTION = "If a blob upload has been cancelled or was never started, " +
"this error code MAY be returned."
const val DIGEST_INVALID_CODE = "DIGEST_INVALID"
const val DIGEST_INVALID_MESSAGE = "provided digest did not match uploaded content"
const val DIGEST_INVALID_DESCRIPTION = "When a blob is uploaded, the registry will check " +
"that the content matches the digest provided by the client. " +
"The error MAY include a detail structure with the key \"digest\", including the invalid digest string. " +
"This error MAY also be returned when a manifest includes an invalid layer digest."
const val MANIFEST_BLOB_UNKNOWN_CODE = "MANIFEST_BLOB_UNKNOWN"
const val MANIFEST_BLOB_UNKNOWN_MESSAGE = "blob unknown to registry"
const val MANIFEST_BLOB_UNKNOWN_DESCRIPTION = "This error MAY be returned when a manifest blob " +
"is unknown to the registry."
const val MANIFEST_INVALID_CODE = "MANIFEST_INVALID"
const val MANIFEST_INVALID_MESSAGE = "manifest invalid"
const val MANIFEST_INVALID_DESCRIPTION = "During upload, manifests undergo several checks ensuring validity. " +
"If those checks fail, this error MAY be returned, unless a more specific error is included. " +
"The detail will contain information the failed validation."
const val MANIFEST_UNKNOWN_CODE = "MANIFEST_UNKNOWN"
const val MANIFEST_UNKNOWN_MESSAGE = "manifest unknown"
const val MANIFEST_UNKNOWN_DESCRIPTION = "This error is returned when the manifest, " +
"identified by name and tag is unknown to the repository."
const val MANIFEST_UNVERIFIED_CODE = "MANIFEST_UNVERIFIED"
const val MANIFEST_UNVERIFIED_MESSAGE = "manifest failed signature verification"
const val MANIFEST_UNVERIFIED_DESCRIPTION = "During manifest upload, if the manifest fails signature verification, " +
"this error will be returned."
const val NAME_INVALID_CODE = "NAME_INVALID"
const val NAME_INVALID_MESSAGE = "invalid repository name"
const val NAME_INVALID_DESCRIPTION = "Invalid repository name encountered either during " +
"manifest validation or any API operation."
const val NAME_UNKNOWN_CODE = "NAME_UNKNOWN"
const val NAME_UNKNOWN_MESSAGE = "repository name not known to registry"
const val NAME_UNKNOWN_DESCRIPTION = "This is returned if the name used during an operation is unknown to the registry."
const val SIZE_INVALID_CODE = "SIZE_INVALID"
const val SIZE_INVALID_MESSAGE = "provided length did not match content length"
const val SIZE_INVALID_DESCRIPTION = "When a layer is uploaded, " +
"the provided size will be checked against the uploaded content. " +
"If they do not match, this error will be returned."
const val TAG_INVALID_CODE = "TAG_INVALID"
const val TAG_INVALID_MESSAGE = "manifest tag did not match URI"
const val TAG_INVALID_DESCRIPTION = "During a manifest upload," +
" if the tag in the manifest does not match the uri tag, " +
"this error will be returned."
const val UNAUTHORIZED_CODE = "UNAUTHORIZED"
const val UNAUTHORIZED_MESSAGE = "authentication required"
const val UNAUTHORIZED_DESCRIPTION = "The access controller was unable to authenticate the client. " +
"Often this will be accompanied by a Www-Authenticate HTTP response header indicating how to authenticate."
const val DENIED_CODE = "DENIED"
const val DENIED_MESSAGE = "requested access to the resource is denied"
const val DENIED_DESCRIPTION = "The access controller denied access for the operation on a resource."
const val UNSUPPORTED_CODE = "UNSUPPORTED"
const val UNSUPPORTED_MESSAGE = "The operation is unsupported."
const val UNSUPPORTED_DESCRIPTION = "The operation was unsupported due to a missing implementation or " +
"invalid set of parameters."
| 383 |
Kotlin
|
38
| 70 |
817363204d5cb57fcd6d0cb520210fa7b33cd5d6
| 5,925 |
bk-repo
|
MIT License
|
android-ui/src/main/java/com/a_blekot/shlokas/android_ui/view/list_dev/ListDevView.kt
|
a-blekot
| 522,545,932 | false |
{"Kotlin": 452729, "Swift": 124616, "Ruby": 87}
|
package com.a_blekot.shlokas.android_ui.view.list_dev
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.*
import androidx.compose.material3.*
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.MaterialTheme.typography
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.unit.dp
import com.a_blekot.shlokas.android_ui.custom.StandartColumn
import com.a_blekot.shlokas.android_ui.custom.StandartLazyColumn
import com.a_blekot.shlokas.android_ui.custom.StandartRow
import com.a_blekot.shlokas.android_ui.theme.Dimens
import com.a_blekot.shlokas.android_ui.theme.Dimens.iconSizeL
import com.a_blekot.shlokas.android_ui.theme.Dimens.radiusS
import com.a_blekot.shlokas.common.list_api.ListComponent
import com.arkivanov.decompose.extensions.compose.jetpack.subscribeAsState
@Composable
fun ListDevView(component: ListComponent) {
val state = component.flow.subscribeAsState()
StandartColumn(modifier = Modifier.background(colorScheme.background)) {
ButtonsRow(state.value.hasChanges, component, modifier = Modifier.padding(12.dp))
Text(
state.value.config.title,
color = colorScheme.primary,
style = typography.headlineLarge,
modifier = Modifier.padding(top = 20.dp)
)
StandartLazyColumn {
itemsIndexed(state.value.config.list, key = { _, it -> it.shloka.id }) { index, config ->
ListDevItemView(index, config, component)
}
}
}
}
@Composable
private fun ButtonsRow(listHasChanges: Boolean, component: ListComponent, modifier: Modifier = Modifier) {
StandartRow(
modifier = modifier
.border(
width = Dimens.borderS,
color = colorScheme.primary,
shape = RoundedCornerShape(radiusS)
)
) {
fun removeShloka() {
component.flow.value.config.list.lastOrNull()?.let {
component.remove(it.shloka.id)
}
}
IconButton(
onClick = { component.add() },
modifier = modifier.size(iconSizeL),
) {
Icon(
Icons.Rounded.AddBox,
"add shloka",
tint = colorScheme.primary,
modifier = Modifier.fillMaxSize()
)
}
IconButton(
onClick = { removeShloka() },
modifier = modifier.size(iconSizeL),
) {
Icon(
Icons.Rounded.Delete,
"remove shloka",
tint = colorScheme.primary,
modifier = Modifier.fillMaxSize()
)
}
val infiniteTransition = rememberInfiniteTransition()
val alpha by infiniteTransition.animateFloat(
initialValue = 1f,
targetValue = if (listHasChanges) 0.5f else 1.0f,
animationSpec = infiniteRepeatable(
animation = tween(1000, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
)
)
IconButton(
enabled = listHasChanges,
onClick = { component.save() },
modifier = modifier
.size(iconSizeL)
.alpha(alpha),
) {
Icon(
Icons.Rounded.Save,
"save list",
tint = colorScheme.primary,
modifier = Modifier.fillMaxSize()
)
}
IconButton(
onClick = { component.play() },
modifier = Modifier.size(iconSizeL),
) {
Icon(
Icons.Rounded.PlayCircle,
"play",
tint = colorScheme.primary,
modifier = Modifier.fillMaxSize()
)
}
IconButton(
onClick = { component.settings() },
modifier = Modifier.size(iconSizeL),
) {
Icon(
Icons.Rounded.Settings,
"settings",
tint = colorScheme.primary,
modifier = Modifier.fillMaxSize()
)
}
}
}
| 0 |
Kotlin
|
0
| 2 |
ac37f147a54c3233113806defc7564480f9c460f
| 4,619 |
memorize_shloka
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ControllerMethod.kt
|
Danilo-Araujo-Silva
| 271,904,885 | false | null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: ControllerMethod
*
* Full name: System`ControllerMethod
*
* Usage: ControllerMethod is an option for Manipulate, Graphics3D, Plot3D, and related functions that specifies the default way that controls on an external controller device should apply.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/ControllerMethod
* Documentation: web: http://reference.wolfram.com/language/ref/ControllerMethod.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun controllerMethod(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("ControllerMethod", arguments.toMutableList(), options)
}
| 2 |
Kotlin
|
0
| 3 |
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,133 |
mathemagika
|
Apache License 2.0
|
bindroid-kotlin/src/main/java/com/bindroid/utils/CompiledProperty.kt
|
depoll
| 8,004,623 | false | null |
package com.bindroid.utils
import java.lang.ref.WeakReference
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
class CompiledProperty<T>(prop: () -> KProperty0<T>, cls: Class<T>) : Property<T>() {
companion object {
inline operator fun <reified T> invoke(noinline prop: () -> KProperty0<T>): CompiledProperty<T> {
return CompiledProperty(prop, T::class.java)
}
}
init {
this.getter = Function {
try {
val resolved = prop()
resolved.get()
} catch (e: NullPointerException) {
null
}
}
this.setter = Action {
val kprop = prop()
if (kprop is KMutableProperty0<T>) {
kprop.set(it)
} else {
throw UnsupportedOperationException("Property ${kprop?.name} has no setter")
}
}
this.propertyType = cls
}
}
inline infix fun <T, TResult> T.weakBind(crossinline operation: T.() -> TResult): () -> TResult {
val weakThis = WeakReference(this)
return { weakThis.get()!!.operation() }
}
inline infix fun <T, reified TResult> T.weakProp(crossinline operation: T.() -> KProperty0<TResult>):
CompiledProperty<TResult> {
return CompiledProperty(this weakBind operation)
}
inline fun <reified T> compiledProp(noinline prop: () -> KProperty0<T>): CompiledProperty<T> {
return CompiledProperty(prop)
}
| 4 |
Java
|
17
| 168 |
6dde1a5a46f6c7ecbeef13750d6cc098256d3949
| 1,549 |
bindroid
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.