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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
samples/src/main/java/com/hedvig/flexboxcomposesample/MainActivity.kt
|
HedvigInsurance
| 532,780,148 | false |
{"Kotlin": 57711}
|
package com.hedvig.flexboxcomposesample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { Root() }
}
}
| 0 |
Kotlin
|
0
| 6 |
7572be01f1c1ab1a8683da256ffc0e6a3fbf7c0d
| 335 |
FlexboxCompose
|
MIT License
|
shared/src/commonMain/kotlin/com/joelkanyi/focusbloom/core/domain/repository/tasks/TasksRepository.kt
|
JoelKanyi
| 680,275,879 | false | null |
/*
* Copyright 2023 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.joelkanyi.focusbloom.core.domain.repository.tasks
import com.joelkanyi.focusbloom.core.domain.model.Task
import kotlinx.coroutines.flow.Flow
interface TasksRepository {
fun getTasks(): Flow<List<Task>>
fun getTask(id: Int): Flow<Task?>
suspend fun addTask(task: Task)
suspend fun updateTask(task: Task)
suspend fun deleteTask(id: Int)
suspend fun deleteAllTasks()
suspend fun updateConsumedFocusTime(id: Int, focusTime: Long)
suspend fun updateConsumedShortBreakTime(id: Int, shortBreakTime: Long)
suspend fun updateConsumedLongBreakTime(id: Int, longBreakTime: Long)
suspend fun updateTaskInProgress(id: Int, inProgressTask: Boolean)
suspend fun updateTaskCompleted(id: Int, completed: Boolean)
suspend fun updateCurrentSessionName(id: Int, current: String)
suspend fun updateTaskCycleNumber(id: Int, cycle: Int)
fun getActiveTask(): Flow<Task?>
suspend fun updateTaskActive(id: Int, active: Boolean)
suspend fun updateAllTasksActiveStatusToInactive()
}
| 4 | null |
16
| 59 |
e127ec6afaae541ed735b29f317a3000b90b9c94
| 1,626 |
FocusBloom
|
Apache License 2.0
|
src/test/kotlin/no/nav/syfo/testutil/generators/KafkaIdenthendelseDTOGenerator.kt
|
navikt
| 378,118,189 | false |
{"Kotlin": 696096, "Dockerfile": 226}
|
package no.nav.syfo.testutil.generators
import no.nav.syfo.domain.PersonIdent
import no.nav.syfo.identhendelse.kafka.IdentType
import no.nav.syfo.identhendelse.kafka.Identifikator
import no.nav.syfo.identhendelse.kafka.KafkaIdenthendelseDTO
import no.nav.syfo.testutil.UserConstants
fun generateKafkaIdenthendelseDTO(
personident: PersonIdent = UserConstants.ARBEIDSTAKER_FNR,
hasOldPersonident: Boolean,
): KafkaIdenthendelseDTO {
val identifikatorer = mutableListOf(
Identifikator(
idnummer = personident.value,
type = IdentType.FOLKEREGISTERIDENT,
gjeldende = true,
),
Identifikator(
idnummer = "10${personident.value}",
type = IdentType.AKTORID,
gjeldende = true
),
)
if (hasOldPersonident) {
identifikatorer.addAll(
listOf(
Identifikator(
idnummer = UserConstants.ARBEIDSTAKER_2_FNR.value,
type = IdentType.FOLKEREGISTERIDENT,
gjeldende = false,
),
Identifikator(
idnummer = "9${UserConstants.ARBEIDSTAKER_2_FNR.value.drop(1)}",
type = IdentType.FOLKEREGISTERIDENT,
gjeldende = false,
),
)
)
}
return KafkaIdenthendelseDTO(identifikatorer)
}
| 1 |
Kotlin
|
2
| 0 |
ec69933ec2a370b965bdfc0e23f92cbf17c51f5d
| 1,405 |
ispersonoppgave
|
MIT License
|
src/gaea.app/src/main/kotlin/com/synebula/gaea/app/controller/cmd/CommandApp.kt
|
synebula-myths
| 205,819,036 | false |
{"Kotlin": 270684}
|
package com.synebula.gaea.app.controller.cmd
import com.synebula.gaea.data.message.HttpMessageFactory
import com.synebula.gaea.domain.service.ICommand
import com.synebula.gaea.domain.service.IService
import com.synebula.gaea.log.ILogger
import org.springframework.beans.factory.annotation.Autowired
/**
* 指令服务,同时实现ICommandApp
*
* @param name 业务名称
* @param service 业务domain服务
* @param logger 日志组件
*/
open class CommandApp<TCommand : ICommand, ID>(
override var name: String,
override var service: IService<ID>,
override var logger: ILogger,
) : ICommandApp<TCommand, ID> {
@Autowired
override lateinit var httpMessageFactory: HttpMessageFactory
}
| 0 |
Kotlin
|
0
| 0 |
b9f929ddbd60703640ea85acd9ec5964a4648e52
| 673 |
gaea
|
MIT License
|
src/main/kotlin/Day01.kt
|
SimonMarquis
| 724,825,757 | false |
{"Kotlin": 30983}
|
class Day01(private val input: List<String>) {
fun part1() = input.asSequence()
.map { it.filter(Char::isDigit) }
.sumOf { "${it.first()}${it.last()}".toInt() }
private val replacements = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
fun part2() = input.asSequence()
.map { line ->
line.foldIndexed(StringBuilder()) { accIndex, acc, c ->
if (c.isDigit()) return@foldIndexed acc.append(c)
replacements.forEachIndexed { index, replacement ->
if (line.startsWith(replacement, startIndex = accIndex)) return@foldIndexed acc.append(index + 1)
}
return@foldIndexed acc
}
}
.sumOf { "${it.first()}${it.last()}".toInt() }
}
| 0 |
Kotlin
|
0
| 1 |
043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e
| 814 |
advent-of-code-2023
|
MIT License
|
app/src/main/java/ca/sudbury/hghasemi/notifyplus/MainActivity.kt
|
hojat72elect
| 157,974,752 | false |
{"Kotlin": 94572}
|
package ca.sudbury.hghasemi.notifyplus
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.DialogFragment
import ca.sudbury.hghasemi.notifyplus.fragments.AppsDialog
import ca.sudbury.hghasemi.notifyplus.fragments.ColorDialog
import ca.sudbury.hghasemi.notifyplus.fragments.ContactUsDialogFragment
import ca.sudbury.hghasemi.notifyplus.fragments.HelpDialogFragment
import ca.sudbury.hghasemi.notifyplus.services.FloatingViewService
import ca.sudbury.hghasemi.notifyplus.services.NotificationService
import com.google.android.material.navigation.NavigationView
/**
First created by <NAME> on Saturday , 11 March 2017.
Contact the author at "https://github.com/hojat72elect"
*/
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener,
ColorDialog.ColorDialogListener,
AppsDialog.AppsDialogListener {
private val CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084
private val REQUEST_CODE_BLUETOOTH = 101
// The LinearLayout that contains the buttons
// (the background color will be applied to this layout)
private var buttonsHolder: LinearLayout? = null
// Position of the button clicked by user
private var buttonPosition: Int? = null
// All the buttons
private var ab1: Button? = null
private var ab2: Button? = null
private var ab3: Button? = null
private var ab4: Button? = null
private var ab5: Button? = null
private var ab6: Button? = null
private var ab7: Button? = null
private var ab8: Button? = null
private var notificationToggle: SwitchCompat? = null
private var floatingControlCenterToggle: SwitchCompat? = null
// All the SharedPrefs used by this app
private var colorSharedPref: SharedPreferences? = null
private var firstButtonSharedPref: SharedPreferences? = null // package name of 1st button.
private var secondButtonSharedPref: SharedPreferences? = null // package name of 2nd button.
private var thirdButtonSharedPref: SharedPreferences? = null // package name of 3rd button.
private var fourthButtonSharedPref: SharedPreferences? = null // package name of 4th button.
private var fifthButtonSharedPref: SharedPreferences? = null // package name of 5th button.
private var sixthButtonSharedPref: SharedPreferences? = null // package name of 6th button.
private var seventhButtonSharedPref: SharedPreferences? = null // package name of 7th button.
private var eighthButtonSharedPref: SharedPreferences? = null // package name of 8th button.
private var notificationToggleSharedPref: SharedPreferences? =
null // the state of the notification service.
private var controlCenterToggleSharedPref: SharedPreferences? =
null // switch for floating control center.
// All the keys for reading from and writing to SharedPrefs
private val colorWriteKey = "color_shared_preferences_read/write_key"
private val firstButtonWriteKey = "first_button_write_key"
private val secondButtonWriteKey = "second_button_write_key"
private val thirdButtonWriteKey = "third_button_write_key"
private val fourthButtonWriteKey = "fourth_button_write_key"
private val fifthButtonWriteKey = "fifth_button_write_key"
private val sixthButtonWriteKey = "sixth_button_write_key"
private val seventhButtonWriteKey = "seventh_button_write_key"
private val eighthButtonWriteKey = "eighth_button_write_key"
private val notificationToggleWriteKey = "notification_toggle_write_key"
private val controlCenterToggleWriteKey = "control_center_toggle_write_key"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setting up everything for NavigationView and NavigationDrawer
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
)
drawer.setDrawerListener(toggle)
toggle.syncState()
val navigationView = findViewById<NavigationView>(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)
// Loading all the other UI elements
buttonsHolder = findViewById(R.id.newbuttonsholder)
ab1 = findViewById(R.id.button1)
ab2 = findViewById(R.id.button2)
ab3 = findViewById(R.id.button3)
ab4 = findViewById(R.id.button4)
ab5 = findViewById(R.id.button5)
ab6 = findViewById(R.id.button6)
ab7 = findViewById(R.id.button7)
ab8 = findViewById(R.id.button8)
notificationToggle = findViewById(R.id.notify_switch)
floatingControlCenterToggle = findViewById(R.id.floating_control_center_switch)
// Loading all the needed SharedPreferences
colorSharedPref = getSharedPreferences("rang_prefs", 0)
firstButtonSharedPref = getSharedPreferences("first_button_prefs", 0)
secondButtonSharedPref = getSharedPreferences("second_button_prefs", 0)
thirdButtonSharedPref = getSharedPreferences("third_button_prefs", 0)
fourthButtonSharedPref = getSharedPreferences("forth_button_prefs", 0)
fifthButtonSharedPref = getSharedPreferences("fifth_button_prefs", 0)
sixthButtonSharedPref = getSharedPreferences("sixth_button_prefs", 0)
seventhButtonSharedPref = getSharedPreferences("seventh_button_prefs", 0)
eighthButtonSharedPref = getSharedPreferences("eighth_button_prefs", 0)
notificationToggleSharedPref = getSharedPreferences("notification_toggle_prefs", 0)
controlCenterToggleSharedPref = getSharedPreferences("control_center_toggle_prefs", 0)
// when the app starts up, color should be applied to UI
updateBackgroundColor(colorSharedPref)
// Registering all the listeners
findViewById<View>(R.id.bgcolorlayout).let {
it.setOnClickListener {
// show the dialog of "Background color".
ColorDialog().show(supportFragmentManager, "color")
}
}
findViewById<View>(R.id.notification_toggle_layout).let {
it.setOnClickListener {
// toggle the notification switch
notificationToggle?.toggle()
}
}
findViewById<View>(R.id.floating_control_center_layout).let {
it.setOnClickListener {
// toggle the floating control center switch
floatingControlCenterToggle?.toggle()
}
}
notificationToggle?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// The switch is turned on; show the notification.
notificationToggleSharedPref?.edit().let {
it?.putBoolean(notificationToggleWriteKey, true)
it?.apply()
}
startNotification()
} else {
// stop showing the notification
notificationToggleSharedPref?.edit().let {
it?.putBoolean(notificationToggleWriteKey, false)
it?.apply()
}
stopService(Intent(this, NotificationService::class.java))
}
}
floatingControlCenterToggle?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// first check for bluetooth permissions
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH
) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH_ADMIN
) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// ask user to accept those permissions
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_COARSE_LOCATION
), REQUEST_CODE_BLUETOOTH
)
}
// then check for permission to draw over other apps
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
!Settings.canDrawOverlays(applicationContext)
) {
// The API is above 23 and the permission to draw over
// other apps is not yet granted. Ask them to grant the permission.
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:$packageName")
)
(this as Activity).startActivityForResult(
intent,
CODE_DRAW_OVER_OTHER_APP_PERMISSION
)
Toast.makeText(
applicationContext,
"You need to first accept the permission requests of this app.",
Toast.LENGTH_LONG
).show()
floatingControlCenterToggle?.isChecked = false
controlCenterToggleSharedPref?.edit().let {
it?.putBoolean(controlCenterToggleWriteKey, false)
it?.apply()
}
} else {
// User has already granted the permissions; start the floating control center.
controlCenterToggleSharedPref?.edit().let {
it?.putBoolean(controlCenterToggleWriteKey, true)
it?.apply()
}
startFloatingControlCenter()
}
} else {
// stop showing the control center
controlCenterToggleSharedPref?.edit().let {
it?.putBoolean(controlCenterToggleWriteKey, false)
it?.apply()
}
stopService(Intent(this, FloatingViewService::class.java))
}
}
ab1 = findViewById<Button?>(R.id.button1).also {
it.setOnClickListener {
buttonPosition = 0
showAppsDialog()
}
}
ab2 = findViewById<Button?>(R.id.button2).also {
it.setOnClickListener {
buttonPosition = 1
showAppsDialog()
}
}
ab3 = findViewById<Button?>(R.id.button3).also {
it.setOnClickListener {
buttonPosition = 2
showAppsDialog()
}
}
ab4 = findViewById<Button?>(R.id.button4).also {
it.setOnClickListener {
buttonPosition = 3
showAppsDialog()
}
}
ab5 = findViewById<Button?>(R.id.button5).also {
it.setOnClickListener {
buttonPosition = 4
showAppsDialog()
}
}
ab6 = findViewById<Button?>(R.id.button6).also {
it.setOnClickListener {
buttonPosition = 5
showAppsDialog()
}
}
ab7 = findViewById<Button?>(R.id.button7).also {
it.setOnClickListener {
buttonPosition = 6
showAppsDialog()
}
}
ab8 = findViewById<Button?>(R.id.button8).also {
it.setOnClickListener {
buttonPosition = 7
showAppsDialog()
}
}
// Update the background drawable of all buttons in main UI according to SharedPrefs
val packageManager = applicationContext.packageManager
ab1?.background = firstButtonSharedPref?.getString(firstButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab2?.background = secondButtonSharedPref?.getString(secondButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab3?.background = thirdButtonSharedPref?.getString(thirdButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab4?.background = fourthButtonSharedPref?.getString(fourthButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab5?.background = fifthButtonSharedPref?.getString(fifthButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab6?.background = sixthButtonSharedPref?.getString(sixthButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab7?.background = seventhButtonSharedPref?.getString(seventhButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
ab8?.background = eighthButtonSharedPref?.getString(eighthButtonWriteKey, null).let {
try {
packageManager.getApplicationIcon(it ?: this.packageName)
} catch (e: PackageManager.NameNotFoundException) {
packageManager.getApplicationIcon(this.packageName)
}
}
// Update the state of notification switch according to SharedPref
notificationToggleSharedPref?.getBoolean(notificationToggleWriteKey, false).let {
if (it != null) {
notificationToggle?.isChecked = it
}
}
// Update the state of floating control center switch according to SharedPref
controlCenterToggleSharedPref?.getBoolean(controlCenterToggleWriteKey, false).let {
if (it != null) {
floatingControlCenterToggle?.isChecked = it
}
}
}
// The ColorDialog receives a reference to MainActivity through the
// DialogFragment.onAttach() callback, which it uses to call the following methods
// defined by the ColorDialog.ColorDialogListener interface.
override fun onColorChanged(dialog: DialogFragment, newColor: Int) {
// Update the SharedPrefs with the new color
colorSharedPref?.edit().let {
it?.putInt(
colorWriteKey, Color.argb(
Color.alpha(newColor),
Color.red(newColor),
Color.green(newColor),
Color.blue(newColor)
)
)
it?.apply()
}
updateBackgroundColor(colorSharedPref)
// If the notification is on, the new color should be applied to it too
// we just call the corresponding function after we have updated the SharedPref of color.
if (notificationToggleSharedPref?.getBoolean(notificationToggleWriteKey, false) == true) {
startNotification()
}
}
// The AppsDialog receives a reference to MainActivity through the
// DialogFragment.onAttach() callback, which it uses to call the following methods
// defined by the AppsDialog.AppsDialogListener interface.
override fun onAppChanged(imv: ImageView?, tv: TextView?) {
// apply the icon to corresponding button
// and update the related SharedPref
when (buttonPosition) {
0 -> {
ab1?.background = imv?.drawable
firstButtonSharedPref?.edit().let {
it?.putString(firstButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
1 -> {
ab2?.background = imv?.drawable
secondButtonSharedPref?.edit().let {
it?.putString(secondButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
2 -> {
ab3?.background = imv?.drawable
thirdButtonSharedPref?.edit().let {
it?.putString(thirdButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
3 -> {
ab4?.background = imv?.drawable
fourthButtonSharedPref?.edit().let {
it?.putString(fourthButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
4 -> {
ab5?.background = imv?.drawable
fifthButtonSharedPref?.edit().let {
it?.putString(fifthButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
5 -> {
ab6?.background = imv?.drawable
sixthButtonSharedPref?.edit().let {
it?.putString(sixthButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
6 -> {
ab7?.background = imv?.drawable
seventhButtonSharedPref?.edit().let {
it?.putString(seventhButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
7 -> {
ab8?.background = imv?.drawable
eighthButtonSharedPref?.edit().let {
it?.putString(eighthButtonWriteKey, tv?.text.toString())
it?.apply()
}
}
}
// If the notification is on, the change in favorite apps should be applied to it too.
// we just call the corresponding function after we have updated the SharedPref of favorite apps.
if (notificationToggleSharedPref?.getBoolean(notificationToggleWriteKey, false) == true) {
startNotification()
}
}
/**
* When user presses the back button in the app.
*/
override fun onBackPressed() {
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
/**
* Inflate the menu items in the action bar.
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_settings -> {
suggestShare()
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* Handle navigation view item clicks here.
*/
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_contactus -> {
ContactUsDialogFragment().show(supportFragmentManager, "contactus")
}
R.id.nav_help -> {
HelpDialogFragment().show(supportFragmentManager, "help")
}
R.id.nav_share -> {
suggestShare()
}
}
findViewById<DrawerLayout>(R.id.drawer_layout).closeDrawer(GravityCompat.START)
return true
}
// show the dialog of installed apps.
private fun showAppsDialog() {
AppsDialog().show(supportFragmentManager, "installed_apps")
}
// Suggesting the user to share a link to this app.
private fun suggestShare() {
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(
Intent.EXTRA_TEXT, """
${getString(R.string.share_text)}
The app isn't currently published in any markets
""".trimIndent()
)
sendIntent.type = "text/plain"
startActivity(Intent.createChooser(sendIntent, resources.getText(R.string.send_to)))
}
// Whenever you want to update the background color according to
// sharedPrefs, just call this function
private fun updateBackgroundColor(color: SharedPreferences?) {
buttonsHolder?.setBackgroundColor(
color?.getInt(colorWriteKey, 0) ?: Color.WHITE
)
}
private fun startNotification() {
// First make a list of all the current favorite apps
val faveApps = arrayOf(
firstButtonSharedPref?.getString(firstButtonWriteKey, null)
?: this.packageName,
secondButtonSharedPref?.getString(secondButtonWriteKey, null)
?: this.packageName,
thirdButtonSharedPref?.getString(thirdButtonWriteKey, null)
?: this.packageName,
fourthButtonSharedPref?.getString(fourthButtonWriteKey, null)
?: this.packageName,
fifthButtonSharedPref?.getString(fifthButtonWriteKey, null)
?: this.packageName,
sixthButtonSharedPref?.getString(sixthButtonWriteKey, null)
?: this.packageName,
seventhButtonSharedPref?.getString(seventhButtonWriteKey, null)
?: this.packageName,
eighthButtonSharedPref?.getString(eighthButtonWriteKey, null)
?: this.packageName
)
try {
// Creating the view hierarchy that will be shown in the notification
val remoteView = RemoteViews(this.packageName, R.layout.notify8)
remoteView.setInt(
R.id.notificationlayout,
"setBackgroundColor",
colorSharedPref?.getInt(colorWriteKey, 0) ?: 0
)
// Starting up the notification
val notificationIntent = Intent(this, NotificationService::class.java)
notificationIntent.putExtra("ufa", faveApps)
notificationIntent.putExtra("viewgroup", remoteView)
startService(notificationIntent) // This service works pretty independently
// and doesn't need to communicate with the MainActivity.
} catch (e: Exception) {
Toast.makeText(
this,
"unable to start notification\n${e.message}",
Toast.LENGTH_LONG
)
.show()
}
}
/**
* This service needs to be bound to the MainActivity because it needs to communicate some stuff.
*/
private fun startFloatingControlCenter() {
try {
startService(Intent(this, FloatingViewService::class.java))
} catch (e: Exception) {
Toast.makeText(
this,
"unable to start floating control center\n${e.message}",
Toast.LENGTH_LONG
)
.show()
}
}
}
| 3 |
Kotlin
|
0
| 2 |
3fa48e5196d6baba7063a3f8c65fabd2170bb9c6
| 25,159 |
Notifyplus
|
MIT License
|
app/src/main/java/com/satwik/noteit/model/NotesDatabase.kt
|
Satwik055
| 584,702,410 | false | null |
package com.satwik.noteit.model
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [NotesEntity::class], version = 1, exportSchema = false)
abstract class NotesDatabase:RoomDatabase() {
abstract fun myNotesDao():NotesDao
companion object{
@Volatile
private var INSTANCE:NotesDatabase?=null
fun getDatabaseInstance(context: Context):NotesDatabase {
if(INSTANCE == null){
synchronized(this){
INSTANCE = Room.databaseBuilder(context.applicationContext,
NotesDatabase::class.java,
"NotesDB").allowMainThreadQueries().build()
}
}
return INSTANCE!!
}
}
}
| 10 |
Kotlin
|
0
| 1 |
713a4ebd98307ac1b70b9fedd8c4167a30182110
| 826 |
Noteit
|
MIT License
|
mobile/src/main/java/com/aptopayments/mobile/repository/card/remote/requests/ActivatePhysicalCardRequest.kt
|
ShiftFinancial
| 130,093,227 | false |
{"Markdown": 2, "Gradle": 5, "Text": 1, "Ignore List": 1, "Kotlin": 492, "JSON": 41, "XML": 2, "YAML": 1}
|
package com.aptopayments.mobile.repository.card.remote.requests
import com.google.gson.annotations.SerializedName
import java.io.Serializable
internal data class ActivatePhysicalCardRequest(
@SerializedName("code")
val code: String
) : Serializable
| 0 |
Kotlin
|
0
| 5 |
f79b3c532ae2dfec8e571b315401ef03d8e507f9
| 261 |
shift-sdk-android
|
MIT License
|
app/src/main/java/es/guiguegon/kotlinsample/adapters/ViewTypeDelegateAdapter.kt
|
guiguegon
| 73,807,458 | false | null |
package es.guiguegon.kotlinsample.adapters
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
/**
* Created by guiguegon on 15/11/2016.
*/
interface ViewTypeDelegateAdapter {
fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder
fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType)
}
| 0 |
Kotlin
|
0
| 0 |
f1b164b65eda2db5c62c0f9e332808b4bf516954
| 352 |
KotlinSample
|
Apache License 2.0
|
save-cloud-common/src/commonMain/kotlin/com/saveourtool/save/utils/DateTimeUtils.kt
|
saveourtool
| 300,279,336 | false | null |
/**
* Utility methods related to a Date and Time
*/
package com.saveourtool.save.utils
import kotlinx.datetime.*
/**
* @return [Instant] from epoch time in mills
*/
fun Long.millisToInstant(): Instant = Instant.fromEpochMilliseconds(this)
/**
* @return [Instant] from epoch time in seconds
*/
fun Long.secondsToInstant(): Instant = Instant.fromEpochSeconds(this)
/**
* @return pretty string representation of [LocalDateTime]
*/
fun LocalDateTime.prettyPrint() = this.toString()
.replace("T", " ")
.replace("Z", "")
.replace("-", ".")
/**
* @return current local date-time in UTC timezone
*/
fun getCurrentLocalDateTime(): LocalDateTime = Clock.System.now().toLocalDateTime(TimeZone.UTC)
| 160 |
Kotlin
|
1
| 31 |
d83a26b101c0f809d39a6deab4e183de04cc7832
| 715 |
save-cloud
|
MIT License
|
FlowEngine/src/main/kotlin/org/dustbins/main/core/operation/DbOperation.kt
|
justdoins
| 728,611,967 | false |
{"Kotlin": 9816}
|
package org.dustbins.main.core.operation
interface DbOperation{
fun read()
fun delete()
fun update()
fun create()
fun init()
}
| 0 |
Kotlin
|
0
| 0 |
75d7d8f78d5646db173896d8e6f13ea8cb722745
| 151 |
tds
|
Apache License 2.0
|
app/src/main/kotlin/io/github/edwinchang24/salvage/MainActivity.kt
|
EdwinChang24
| 722,416,299 | false |
{"Kotlin": 13750}
|
package io.github.edwinchang24.salvage
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import dagger.hilt.android.AndroidEntryPoint
import io.github.edwinchang24.salvage.ui.theme.SalvageTheme
@AndroidEntryPoint(ComponentActivity::class)
class MainActivity : Hilt_MainActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
SalvageTheme {
Scaffold { padding ->
Greeting(name = "Android", modifier = Modifier.padding(padding))
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
SalvageTheme {
Greeting("Android")
}
}
| 2 |
Kotlin
|
0
| 0 |
8102ad67b92659f270dd933229faf8fb981aad7a
| 1,411 |
salvage
|
MIT License
|
app/src/main/java/com/example/vet_santabarbara/adapters/CitaAdapter.kt
|
AlejandroVelasco
| 693,446,818 | false |
{"Kotlin": 46229, "Python": 15514}
|
package com.example.vet_santabarbara.adapters
import android.view.View
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.vet_santabarbara.R
import com.example.vet_santabarbara.models.Cita
class CitaAdapter(private val citas: List<Cita>, val onItemClickListener: (Cita) -> Unit) : RecyclerView.Adapter<CitaAdapter.CitaViewHolder>() {
class CitaViewHolder(val view: View, val onItemClickListener: (Cita) -> Unit) : RecyclerView.ViewHolder(view) {
// Referencias a los elementos de la UI del CardView, por ejemplo:
private val pacienteTextView: TextView = view.findViewById(R.id.pacienteTextView)
private val propietarioTextView: TextView = view.findViewById(R.id.propietarioTextView)
private val fechaTextView: TextView = view.findViewById(R.id.fechaTextView)
private val doctorTextView: TextView = view.findViewById(R.id.doctorTextView)
// Método para asociar datos del objeto Doctor con elementos de la UI
fun bind(cita: Cita) {
pacienteTextView.text = cita.paciente
propietarioTextView.text = cita.propietario
fechaTextView.text = cita.fecha_cita + cita.hora_cita
doctorTextView.text = "Doctor: " + cita.doctor
itemView.setOnClickListener {
// Llama al listener cuando se hace clic en el CardView
onItemClickListener.invoke(cita)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CitaViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.card_cita, parent, false)
return CitaViewHolder(view, onItemClickListener)
}
override fun onBindViewHolder(holder: CitaViewHolder, position: Int) {
holder.bind(citas[position])
}
override fun getItemCount() = citas.size
}
| 0 |
Kotlin
|
2
| 0 |
1dfc5d5238c8e3a978afaf4e93c403d547651ff2
| 1,949 |
Vet-SantaBarbara-DSM
|
Creative Commons Zero v1.0 Universal
|
visionforge-solid/src/commonMain/kotlin/space/kscience/visionforge/solid/transform/RemoveSingleChild.kt
|
mipt-npm
| 174,502,624 | false | null |
package space.kscience.visionforge.solid.transform
import space.kscience.dataforge.meta.itemSequence
import space.kscience.dataforge.misc.DFExperimental
import space.kscience.dataforge.names.asName
import space.kscience.visionforge.MutableVisionGroup
import space.kscience.visionforge.Vision
import space.kscience.visionforge.VisionGroup
import space.kscience.visionforge.meta
import space.kscience.visionforge.solid.*
private operator fun Number.plus(other: Number) = toFloat() + other.toFloat()
private operator fun Number.times(other: Number) = toFloat() * other.toFloat()
@DFExperimental
internal fun Vision.updateFrom(other: Vision): Vision {
if (this is Solid && other is Solid) {
x += other.x
y += other.y
z += other.y
rotationX += other.rotationX
rotationY += other.rotationY
rotationZ += other.rotationZ
scaleX *= other.scaleX
scaleY *= other.scaleY
scaleZ *= other.scaleZ
other.meta.itemSequence().forEach { (name, item) ->
if (getProperty(name) == null) {
setProperty(name, item)
}
}
}
return this
}
@DFExperimental
internal object RemoveSingleChild : VisualTreeTransform<SolidGroup>() {
override fun SolidGroup.transformInPlace() {
fun MutableVisionGroup.replaceChildren() {
children.forEach { (childName, parent) ->
if (parent is SolidReferenceGroup) return@forEach //ignore refs
if (parent is MutableVisionGroup) {
parent.replaceChildren()
}
if (parent is VisionGroup && parent.children.size == 1) {
val child = parent.children.values.first()
val newParent = child.updateFrom(parent)
newParent.parent = null
set(childName.asName(), newParent)
}
}
}
replaceChildren()
prototypes {
replaceChildren()
}
}
override fun SolidGroup.clone(): SolidGroup {
TODO()
}
}
| 11 |
Kotlin
|
5
| 25 |
456e01fcfa48f798a03cc5866acc5d4c557e00c3
| 2,100 |
visionforge
|
Apache License 2.0
|
problems/2020adventofcode18b/submissions/accepted/Stefan.kt
|
stoman
| 47,287,900 | false |
{"Text": 4, "Ignore List": 1, "Markdown": 2, "Python": 99, "Shell": 2, "JSON": 4, "C++": 164, "C": 51, "Go": 17, "Starlark": 3, "Diff": 7, "Makefile": 4, "SWIG": 1, "Java": 38, "YAML": 302, "Kotlin": 103, "TeX": 11, "XML": 5, "SVG": 1}
|
import java.math.BigInteger
import java.util.*
fun evaluate(it: Stack<Char>, start: BigInteger = BigInteger.ZERO, readClosingBracket: Boolean = false): BigInteger {
var buffer = start
var operation = '?'
while(it.isNotEmpty()) {
when (val next = it.pop()) {
')' -> {
if(!readClosingBracket) {
it.add(next)
}
return buffer
}
in setOf('*', '+') -> operation = next
' ' -> { }
else -> {
val term: BigInteger = if(next == '(') evaluate(it, readClosingBracket = true) else next.toString().toBigInteger()
when(operation) {
'?' -> buffer = term
'*' -> buffer *= evaluate(it, start = term)
'+' -> buffer += term
}
}
}
}
return buffer
}
fun main() {
val s = Scanner(System.`in`).useDelimiter("\n")
var r = BigInteger.ZERO
while(s.hasNext()) {
val stack = Stack<Char>()
stack.addAll(s.next().toList().reversed())
r += evaluate(stack)
}
println(r)
}
| 0 |
C
|
1
| 3 |
ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9
| 1,006 |
competitive-programming
|
MIT License
|
frogoconsumeapi/src/main/java/com/frogobox/api/news/ConsumeNewsApi.kt
|
frogobox
| 389,577,716 | false | null |
package com.frogobox.api.news
import android.content.Context
import com.frogobox.coreapi.ConsumeApiResponse
import com.frogobox.coreapi.news.NewsApi
import com.frogobox.coreapi.news.response.ArticleResponse
import com.frogobox.coreapi.news.response.SourceResponse
import com.frogobox.sdk.ext.usingChuck
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import okhttp3.Interceptor
/**
* Created by <NAME>
* FrogoBox Inc License
* =========================================
* consumable-code-news-api
* Copyright (C) 15/03/2020.
* All rights reserved
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* LinkedIn : linkedin.com/in/faisalamircs
* -----------------------------------------
* FrogoBox Software Industries
* com.frogobox.frogoconsumeapi.news
*
*/
class ConsumeNewsApi(apiKey: String) : IConsumeNewsApi {
private var newsApi = NewsApi(AndroidSchedulers.mainThread(), apiKey)
override fun usingChuckInterceptor(context: Context) {
usingChuckInterceptor(context.usingChuck())
}
override fun usingChuckInterceptor(chuckerInterceptor: Interceptor) {
newsApi.usingChuckInterceptor(chuckerInterceptor)
}
override fun getTopHeadline(
q: String?,
sources: String?,
category: String?,
country: String?,
pageSize: Int?,
page: Int?,
callback: ConsumeApiResponse<ArticleResponse>
) {
newsApi.getTopHeadline(
q,
sources,
category,
country,
pageSize,
page,
callback
)
}
override fun getEverythings(
q: String?,
from: String?,
to: String?,
qInTitle: String?,
sources: String?,
domains: String?,
excludeDomains: String?,
language: String?,
sortBy: String?,
pageSize: Int?,
page: Int?,
callback: ConsumeApiResponse<ArticleResponse>
) {
newsApi.getEverythings(
q,
from,
to,
qInTitle,
sources,
domains,
excludeDomains,
language,
sortBy,
pageSize,
page,
callback
)
}
override fun getSources(
language: String,
country: String,
category: String,
callback: ConsumeApiResponse<SourceResponse>
) {
newsApi.getSources(
language,
country,
category,
callback
)
}
}
| 0 |
Kotlin
|
2
| 7 |
1dd90a037f9acb2ba30066f753d35f7b909621a6
| 2,635 |
frogo-consume-api
|
Apache License 2.0
|
core/src/test/kotlin/com/github/mibac138/argparser/BooleanParserTest.kt
|
mibac138
| 90,508,185 | false |
{"Gradle": 4, "XML": 20, "Markdown": 4, "INI": 1, "Shell": 4, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Kotlin": 94, "Java Properties": 1, "Java": 3}
|
package com.github.mibac138.argparser
import com.github.mibac138.argparser.exception.ParserInvalidInputException
import com.github.mibac138.argparser.parser.BooleanParser
import com.github.mibac138.argparser.reader.asReader
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Created by mibac138 on 06-04-2017.
*/
class BooleanParserTest : ParserTest() {
private val parser = BooleanParser()
@Test fun supportedTypes() {
assertTrue(parser.supportedTypes == setOf(Boolean::class.java, Boolean::class.javaObjectType))
}
@Test fun parse() {
assertEquals(true, parser.parse("yes".asReader(), reqElement()))
assertEquals(true, parser.parse("true".asReader(), reqElement()))
assertEquals(false, parser.parse("no".asReader(), reqElement()))
assertEquals(false, parser.parse("false".asReader(), reqElement()))
}
@Test(expected = ParserInvalidInputException::class) fun invalid() {
parser.parse("maybe".asReader(), reqElement())
}
}
| 7 | null |
1
| 1 |
3796fc0fe829fcde906bde6e498ebf45b752d79d
| 1,055 |
ArgParser
|
MIT License
|
int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiRadioButtonStyling.kt
|
JetBrains
| 440,164,967 | false |
{"Kotlin": 799234, "Java": 22778}
|
package org.jetbrains.jewel.intui.standalone.styling
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import org.jetbrains.jewel.intui.core.theme.IntUiDarkTheme
import org.jetbrains.jewel.intui.core.theme.IntUiLightTheme
import org.jetbrains.jewel.intui.standalone.standalonePainterProvider
import org.jetbrains.jewel.ui.component.styling.RadioButtonColors
import org.jetbrains.jewel.ui.component.styling.RadioButtonIcons
import org.jetbrains.jewel.ui.component.styling.RadioButtonMetrics
import org.jetbrains.jewel.ui.component.styling.RadioButtonStyle
import org.jetbrains.jewel.ui.painter.PainterProvider
@Composable
fun RadioButtonStyle.Companion.light(
colors: RadioButtonColors = RadioButtonColors.light(),
metrics: RadioButtonMetrics = RadioButtonMetrics.defaults(),
icons: RadioButtonIcons = RadioButtonIcons.light(),
) = RadioButtonStyle(colors, metrics, icons)
@Composable
fun RadioButtonStyle.Companion.dark(
colors: RadioButtonColors = RadioButtonColors.dark(),
metrics: RadioButtonMetrics = RadioButtonMetrics.defaults(),
icons: RadioButtonIcons = RadioButtonIcons.dark(),
) = RadioButtonStyle(colors, metrics, icons)
@Composable
fun RadioButtonColors.Companion.light(
content: Color = Color.Unspecified,
contentHovered: Color = content,
contentDisabled: Color = IntUiLightTheme.colors.grey(8),
contentSelected: Color = content,
contentSelectedHovered: Color = content,
contentSelectedDisabled: Color = contentDisabled,
) = RadioButtonColors(
content,
contentHovered,
contentDisabled,
contentSelected,
contentSelectedHovered,
contentSelectedDisabled,
)
@Composable
fun RadioButtonColors.Companion.dark(
content: Color = Color.Unspecified,
contentHovered: Color = content,
contentDisabled: Color = IntUiDarkTheme.colors.grey(8),
contentSelected: Color = content,
contentSelectedHovered: Color = content,
contentSelectedDisabled: Color = contentDisabled,
) = RadioButtonColors(
content,
contentHovered,
contentDisabled,
contentSelected,
contentSelectedHovered,
contentSelectedDisabled,
)
fun RadioButtonMetrics.Companion.defaults(
radioButtonSize: DpSize = DpSize(19.dp, 19.dp),
iconContentGap: Dp = 8.dp,
) = RadioButtonMetrics(radioButtonSize, iconContentGap)
fun RadioButtonIcons.Companion.light(
radioButton: PainterProvider = standalonePainterProvider("com/intellij/ide/ui/laf/icons/intellij/radio.svg"),
) = RadioButtonIcons(radioButton)
fun RadioButtonIcons.Companion.dark(
radioButton: PainterProvider = standalonePainterProvider("com/intellij/ide/ui/laf/icons/darcula/radio.svg"),
) = RadioButtonIcons(radioButton)
| 47 |
Kotlin
|
24
| 512 |
003eb1eed21fc71b5c911e27cbf953d9a149d0ca
| 2,824 |
jewel
|
Apache License 2.0
|
test/krosemann.lise.declarative.coding.kata/test.kt
|
krosemann
| 493,666,487 | false |
{"Kotlin": 2780}
|
package krosemann.lise.declarative.coding.kata
import org.assertj.core.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class Test {
@ParameterizedTest
@CsvSource(value = [
"'',1,0",
"a,0,1",
"a,1,1",
"b,1,2",
"z,1,8",
"abc,1,6",
"iiii,1,36",
"xyz,1,21",
"z,2,8",
"iiii,2,9",
"xyz,2,3",
"lise,1,27",
"lise,2,9",
"lise,3,9",
"abcdefghijklmnopqrstuvwxyz,10,9"
])
fun test(input: String, times: Int, expected: String) {
println(input)
println(times)
println(expected)
Assertions.assertThat(sumOfDigitsOfStringAfterConvert(input, times))
.isEqualTo(expected)
}
}
| 0 |
Kotlin
|
0
| 1 |
59b6a40114bda635f77d0754a865a5f4e07c4ca7
| 813 |
declarative-coding-kata
|
MIT License
|
src/main/kotlin/com/k/pmpstudy/dialog/RenameConfirmDialog.kt
|
Miura-KR
| 395,952,470 | false | null |
package com.k.pmpstudy.dialog
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.PsiDirectory
import com.intellij.ui.dsl.builder.RowLayout
import com.intellij.ui.dsl.builder.panel
import com.k.pmpstudy.domain.ReplaceWord
import javax.swing.JComponent
class RenameConfirmDialog(
private val targetDir: PsiDirectory,
private val replaceWord: ReplaceWord,
private val targetFilesSize: Int
) : DialogWrapper(true) {
init {
title = "Rename Files..."
init()
}
override fun createCenterPanel(): JComponent = panel {
row {
label("TargetDirectory")
label(targetDir.virtualFile.path)
}.layout(RowLayout.PARENT_GRID)
row {
label("Search word")
label(replaceWord.search)
}.layout(RowLayout.PARENT_GRID)
row {
label("Replace word")
label(replaceWord.replace)
}.layout(RowLayout.PARENT_GRID)
row {
label("Found files count")
label("$targetFilesSize")
}.layout(RowLayout.PARENT_GRID)
row("\nThis refactoring will probably change a lot of files.") {}.layout(RowLayout.PARENT_GRID)
}
}
| 2 |
Kotlin
|
0
| 2 |
2a5611d3d9d2192981e95a83423b79c89fec1e09
| 1,202 |
RenameFilesRefactorBatch-intellij
|
Apache License 2.0
|
app/src/main/java/com/nodmp/guide/MainActivity.kt
|
nodmp
| 287,563,072 | false | null |
package com.nodmp.guide
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
open class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.activity_main, menu)
return true
}
}
| 0 |
Kotlin
|
0
| 0 |
99f55b5fe190ccdd4dad846615f0af09bc8e284b
| 471 |
guide
|
Apache License 2.0
|
app/src/main/java/com/example/nms_android_v1/feature/login/model/LoginRequest.kt
|
DSM-DMS
| 429,717,656 | false | null |
package com.example.nms_android_v1.feature.login.model
import com.google.gson.annotations.SerializedName
data class LoginRequest(
@SerializedName("email") val email: String,
@SerializedName("password") val password: String
)
| 3 | null |
1
| 3 |
de9b02c12ab05f1e6ce3c19f0f7fe0e88603eccb
| 235 |
NMS-Android-V1
|
MIT License
|
app/src/main/java/com/syntext_error/demoKeyBoard/MainActivity.kt
|
rahat14
| 443,552,041 | false |
{"Kotlin": 61594}
|
package com.syntext_error.demoKeyBoard
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.material.internal.ContextUtils.getActivity
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.syntext_error.demoKeyBoard.components.expandableView.GifInterface
import com.syntext_error.demoKeyBoard.components.keyboard.CustomKeyboardView
import com.syntext_error.demoKeyBoard.models.Link
import java.util.*
class MainActivity : AppCompatActivity(), GifInterface,
GifListAdapter.Interaction {
private lateinit var keyboard: CustomKeyboardView
private lateinit var addGIF: Button
private lateinit var mAdapter: GifListAdapter
private lateinit var recyclerView: RecyclerView
val list: MutableList<Link> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mAdapter = GifListAdapter(this)
recyclerView = findViewById(R.id.rcvList)
recyclerView.apply {
adapter = mAdapter
layoutManager = LinearLayoutManager(this@MainActivity)
}
val qwertyField: EditText = findViewById(R.id.testQwertyField)
addGIF = findViewById(R.id.addGif)
keyboard = findViewById(R.id.customKeyboardView)
keyboard.registerEditText(CustomKeyboardView.KeyboardType.QWERTY, qwertyField, this)
addGIF.setOnClickListener {
openImage()
}
}
private fun uploadImageToFirebase(fileUri: Uri) {
if (fileUri != null) {
Toast.makeText(applicationContext, "Starting Upload...", Toast.LENGTH_LONG).show()
val fileName = UUID.randomUUID().toString() + ".gif"
val database = FirebaseDatabase.getInstance()
val dataabseREF =
database.getReference("gifs").child("${System.currentTimeMillis() / 10}")
val refStorage = FirebaseStorage.getInstance().reference.child("images/$fileName")
refStorage.putFile(fileUri)
.addOnSuccessListener(
OnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener {
val imageUrl = it.toString()
val model = Link(imageUrl)
dataabseREF.setValue(model).addOnCompleteListener {
Toast.makeText(
applicationContext,
"Successfully Uploaded...",
Toast.LENGTH_LONG
).show()
}
}
})
.addOnFailureListener(OnFailureListener { e ->
print(e.message)
})
}
}
override fun onBackPressed() {
if (keyboard.isExpanded) {
keyboard.translateLayout()
} else {
super.onBackPressed()
}
}
override fun keyClicked(c: String) {
Log.d("TAG", "keyClicked: $c ")
passLink(c)
}
fun openImage() {
// intent of the type image
// intent of the type image
val i = Intent()
i.type = "image/gif"
i.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(i, "Select Picture"), 100)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
// compare the resultCode with the
// SELECT_PICTURE constant
if (requestCode == 100) {
// Get the url of the image from data
val selectedImageUri: Uri? = data?.data
if (null != selectedImageUri) {
uploadImageToFirebase(selectedImageUri)
}
}
}
}
override fun onItemSelected(position: Int, item: Link) {
}
fun passLink(item: String = "") {
val model = Link(item)
list.add(model)
mAdapter.submitList(list)
Log.d("size", "passLink: ${list.size}")
recyclerView.smoothScrollToPosition(list.size - 1)
}
}
| 0 |
Kotlin
|
0
| 1 |
82ee0a0454d79273e1f3933a05900ed46d8d8e67
| 4,839 |
Gif-CustomKeyboard-Andorid-
|
MIT License
|
skiko/src/commonMain/kotlin/org/jetbrains/skia/svg/SVGNode.kt
|
JetBrains
| 282,864,178 | false | null |
package org.jetbrains.skia.svg
import org.jetbrains.skia.impl.Library.Companion.staticLoad
import org.jetbrains.skia.impl.RefCnt
import org.jetbrains.skia.impl.Stats
import org.jetbrains.skia.impl.reachabilityBarrier
import org.jetbrains.skia.ExternalSymbolName
import org.jetbrains.skia.ModuleImport
import org.jetbrains.skia.impl.NativePointer
abstract class SVGNode internal constructor(ptr: NativePointer) : RefCnt(ptr) {
companion object {
init {
staticLoad()
}
}
val tag: SVGTag
get() = try {
Stats.onNativeCall()
SVGTag.values()[SVGNode_nGetTag(_ptr)]
} finally {
reachabilityBarrier(this)
}
}
@ExternalSymbolName("org_jetbrains_skia_svg_SVGNode__1nGetTag")
@ModuleImport("./skiko.mjs", "org_jetbrains_skia_svg_SVGNode__1nGetTag")
private external fun SVGNode_nGetTag(ptr: NativePointer): Int
| 42 | null |
43
| 840 |
cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe
| 904 |
skiko
|
Apache License 2.0
|
example/src/main/java/com/kazakago/swr/compose/example/todolist/ToDoEditingDialog.kt
|
KazaKago
| 566,693,483 | false |
{"Kotlin": 274493}
|
package com.kazakago.swr.compose.example.todolist
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.kazakago.swr.compose.example.ui.theme.AppTheme
@Composable
fun ToDoEditingDialog(
initialText: String,
onSubmit: (text: String) -> Unit,
onDelete: () -> Unit,
onCancel: () -> Unit,
) {
var text by remember { mutableStateOf(initialText) }
Dialog(onDismissRequest = {}) {
Card {
Column(modifier = Modifier.padding(16.dp)) {
OutlinedTextField(
value = text,
singleLine = true,
onValueChange = { text = it },
)
Spacer(modifier = Modifier.size(16.dp))
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { onSubmit(text) },
) {
Text(text = "OK")
}
OutlinedButton(
modifier = Modifier.fillMaxWidth(),
onClick = onCancel,
) {
Text(text = "Cancel")
}
Spacer(modifier = Modifier.size(16.dp))
Button(
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
onClick = { onDelete() },
) {
Text(text = "Delete")
}
}
}
}
}
@Preview
@Composable
fun PreviewToDoEditingDialog() {
AppTheme {
Surface {
ToDoEditingDialog(
initialText = "hoge",
onSubmit = {},
onCancel = {},
onDelete = {},
)
}
}
}
| 4 |
Kotlin
|
0
| 37 |
34a5d599e0e2b8350af77039b97ea766af5c21da
| 2,037 |
swr-compose
|
Apache License 2.0
|
src/main/kotlin/org/philips/arcson/schema/superposition/models/RootSuperposition.kt
|
Und97n
| 513,674,141 | false |
{"Kotlin": 53179}
|
package org.philips.arcson.schema.superposition.models
import org.philips.arcson.FieldName
import org.philips.arcson.schema.superposition.JsonField
import org.philips.arcson.schema.superposition.createSuperpositionC
import org.philips.arcson.schema.superposition.createSuperpositionS
import org.philips.arcson.type.*
import org.philips.arcson.utils.StringIndentation
class RootSuperposition : ComplexElementSuperposition() {
override fun nextSimpleEncounter(type: ArcsonTypeSimple, name: FieldName?, value: Any?): SimpleElementSuperposition =
collection
.getOrMake(type, type::createSuperpositionS)
.let { it as SimpleElementSuperposition }
.let {
it.nextValue(value)
it
}
override fun nextComplexEncounter(type: ArcsonTypeComplex, name: FieldName?): ComplexElementSuperposition =
collection
.getOrMake(type, type::createSuperpositionC)
.let { it as ComplexElementSuperposition }
override val type: ArcsonType
get() = ArcsonSpecialTypeNONE
private val collection: JsonField = JsonField()
override fun toNiceString(indent: StringIndentation): String =
"$indent#ROOT($occurrences) [${collection.toNiceString(indent.next())}$indent]"
}
| 0 |
Kotlin
|
0
| 0 |
1b6bfc774e11b77b2b745e0b0fb3bfcba6626fee
| 1,294 |
arcson
|
Apache License 2.0
|
src/main/kotlin/net/devoev/vanilla_cubed/enchantment/HurlingEnchantment.kt
|
Devoev
| 473,273,645 | false |
{"Kotlin": 259944, "Java": 37528}
|
package net.devoev.vanilla_cubed.enchantment
import net.devoev.vanilla_cubed.enchantment.HurlingEnchantment.damage
import net.devoev.vanilla_cubed.mixin.TridentEntityMixin
import net.minecraft.enchantment.Enchantment
import net.minecraft.enchantment.EnchantmentHelper
import net.minecraft.enchantment.EnchantmentTarget
import net.minecraft.entity.EquipmentSlot
import net.minecraft.entity.projectile.TridentEntity
import net.minecraft.item.ItemStack
import net.minecraft.item.TridentItem
/**
* An [Enchantment] that increases the damage of thrown [tridents][TridentItem].
*/
object HurlingEnchantment : Enchantment(Rarity.UNCOMMON, EnchantmentTarget.TRIDENT, arrayOf(EquipmentSlot.MAINHAND)) {
override fun getMinPower(level: Int): Int = 5 + level * 7
override fun getMaxPower(level: Int): Int = 50
override fun getMaxLevel(): Int = 3
/**
* The amount of extra damage per [level].
*/
fun damage(level: Int) = (1 + level)/2
/**
* The amount of extra damage for the given [stack].
*/
fun damage(stack: ItemStack) = damage(level(stack))
/**
* The level of this enchantment the given [stack] has.
*/
private fun level(stack: ItemStack): Int = EnchantmentHelper.getLevel(ModEnchantments.HURLING, stack)
}
/**
* Applies the force enchantment when a trident hits an entity
* by modifying the local [f] variable in [TridentEntity.onEntityHit].
* @see TridentEntityMixin.hurlingOnEntityHit
*/
fun hurlingOnEntityHit(f: Float, tridentStack: ItemStack): Float {
return f + damage(tridentStack)
}
| 0 |
Kotlin
|
2
| 1 |
606da9a71725e805f5b423a288612a046c18d782
| 1,569 |
vanilla-cubed
|
MIT License
|
app/src/main/java/behale/health/reminder/database/pills/PillsReminderModel.kt
|
Akshay-kumar79
| 427,837,509 | false |
{"Kotlin": 110919}
|
package behale.health.reminder.database.pills
import androidx.room.Entity
import androidx.room.PrimaryKey
import behale.health.reminder.utils.ConstantUtils
import java.util.*
import kotlin.collections.ArrayList
@Entity(tableName = ConstantUtils.DAILY_PILL_REMINDER_TABLE)
data class PillsReminderModel(
@PrimaryKey(autoGenerate = true)
var id : Int = 0,
var pillName: String = "",
var type: String = ConstantUtils.ADD_PILL_TYPE_EVERYDAY,
var time: List<Calendar> = ArrayList(),
var startFrom : Calendar = Calendar.getInstance(),
var period: Int = 1
)
| 0 |
Kotlin
|
0
| 2 |
cdaa5b20feb2411229eccbb0d3b555b9930fcd97
| 583 |
Behale
|
MIT License
|
logbot/src/main/java/com/tomoima/logbot/view/OverlayViewService.kt
|
tomoima525
| 127,387,453 | false |
{"Gradle": 6, "XML": 24, "Java Properties": 2, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 12, "Java": 4, "YAML": 1}
|
/*
* Copyright (C) 2018 <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.tomoima.logbot.view
import android.animation.ValueAnimator
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.ImageView
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
import com.tomoima.logbot.R
import com.tomoima.logbot.core.Consts
import com.tomoima.logbot.core.Logbot
class OverlayViewService : Service() {
companion object {
fun createIntent(context: Context): Intent = Intent(context, OverlayViewService::class.java)
}
private val overlayView: View by lazy {
LayoutInflater.from(this).inflate(R.layout.view_overlay, null)
}
private val windowManager: WindowManager by lazy {
getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
private val messageReceiver: MessageReceiver by lazy {
MessageReceiver(this)
}
private val logAdapter =
LogAdapter(Logbot.logbotSettings?.bufferSize
?: Consts.DEFAULT_LOG_BUFFER)
private lateinit var recyclerView: RecyclerView
private lateinit var shrinkButton: ImageView
private lateinit var expandButton: ImageView
override fun onBind(Intent: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
LocalBroadcastManager
.getInstance(this)
.registerReceiver(messageReceiver, IntentFilter(Consts.EVENT_SEND_LOG))
val params = createWindowLayoutParams()
params.gravity = Gravity.TOP or Gravity.LEFT
params.x = 0
params.y = 100
params.width = resources.getDimensionPixelSize(R.dimen.overlay_width)
params.height = resources.getDimensionPixelSize(R.dimen.overlay_height)
windowManager.addView(overlayView, params)
overlayView.findViewById<ImageView>(R.id.close).setOnClickListener { _ -> stopSelf() }
overlayView.findViewById<ImageView>(R.id.clear_log).setOnClickListener { _ -> clearLog() }
overlayView.findViewById<ImageView>(R.id.share_log).setOnClickListener { _ -> shareLog() }
shrinkButton = overlayView.findViewById(R.id.shrink)
shrinkButton.setOnClickListener { _ -> shrink() }
expandButton = overlayView.findViewById(R.id.expand)
expandButton.setOnClickListener { _ -> expand() }
recyclerView = overlayView.findViewById(R.id.log_list)
recyclerView.adapter = logAdapter
overlayView.setOnTouchListener(object : View.OnTouchListener {
private var lastAction: Int = 0
private var initialX: Int = 0
private var initialY: Int = 0
private var initialTouchX: Float = 0.toFloat()
private var initialTouchY: Float = 0.toFloat()
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
initialX = params.x
initialY = params.y
initialTouchX = event.rawX
initialTouchY = event.rawY
lastAction = event.action
return true
}
MotionEvent.ACTION_UP -> {
if (lastAction == MotionEvent.ACTION_DOWN) {
// TODO: add pluggable action here
}
lastAction = event.action
return true
}
MotionEvent.ACTION_MOVE -> {
params.x = initialX + (event.rawX - initialTouchX).toInt()
params.y = initialY + (event.rawY - initialTouchY).toInt()
//Update the layout with new X & Y coordinate
windowManager.updateViewLayout(overlayView, params)
lastAction = event.action
return true
}
}
return false
}
})
}
override fun onDestroy() {
super.onDestroy()
windowManager.removeView(overlayView)
LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver)
}
fun addLog(log: String) {
logAdapter.addLog(log)
recyclerView.smoothScrollToPosition(logAdapter.itemCount - 1)
}
private fun clearLog() = logAdapter.clearLog()
private fun shareLog() {
val message = logAdapter.getFullFormattedLogs()
val actionIntent = Intent()
actionIntent.action = Intent.ACTION_SEND
actionIntent.type = "text/plain"
actionIntent.putExtra(Intent.EXTRA_TEXT, message)
actionIntent.putExtra(Intent.EXTRA_SUBJECT, "Log")
startActivity(actionIntent)
}
private fun shrink() {
val newHeight = resources.getDimensionPixelSize(R.dimen.margin_large)
val slideAnimator = ValueAnimator
.ofInt(overlayView.height, newHeight)
.setDuration(300)
slideAnimator.addUpdateListener { animation ->
val value = animation.animatedValue as Int
overlayView.layoutParams.height = value
windowManager.updateViewLayout(overlayView, overlayView.layoutParams)
}
slideAnimator.doOnEnd {
shrinkButton.visibility = View.GONE
expandButton.visibility = View.VISIBLE
}
slideAnimator.start()
}
private fun expand() {
val newHeight = resources.getDimensionPixelSize(R.dimen.overlay_height)
val slideAnimator = ValueAnimator
.ofInt(overlayView.height, newHeight)
.setDuration(300)
slideAnimator.addUpdateListener { animation ->
val value = animation.animatedValue as Int
overlayView.layoutParams.height = value
windowManager.updateViewLayout(overlayView, overlayView.layoutParams)
}
slideAnimator.doOnStart {
shrinkButton.visibility = View.VISIBLE
expandButton.visibility = View.GONE
}
slideAnimator.start()
}
private fun createWindowLayoutParams() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT)
} else {
@Suppress("DEPRECATION")
WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT)
}
internal class MessageReceiver(private val overlayViewService: OverlayViewService)
: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
val message = it.getStringExtra(Consts.INTENT_MESSAGE)
overlayViewService.addLog(message)
}
}
}
}
| 3 |
Kotlin
|
0
| 2 |
c7145f3fc0b1895b1800d65b900ed0da6e4a305e
| 8,163 |
logbot
|
Apache License 2.0
|
vss-processor/src/main/kotlin/org/eclipse/kuksa/vssprocessor/parser/yaml/YamlVssParser.kt
|
eclipse-kuksa
| 687,949,615 | false |
{"Kotlin": 310376, "Java": 9058, "Shell": 2409}
|
/*
* Copyright (c) 2023 Contributors to the Eclipse Foundation
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*
*/
package org.eclipse.kuksa.vssprocessor.parser
import org.eclipse.kuksa.vsscore.model.VssSpecification
import org.eclipse.kuksa.vssprocessor.spec.VssSpecificationSpecModel
import java.io.File
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.memberProperties
internal class YamlDefinitionParser : VssDefinitionParser {
override fun parseSpecifications(definitionFile: File, elementDelimiter: String): List<VssSpecificationSpecModel> {
val specificationElements = mutableListOf<VssSpecificationSpecModel>()
definitionFile.useLines { lines ->
val yamlAttributes = mutableListOf<String>()
for (line in lines.toList()) {
val trimmedLine = line.trim()
if (trimmedLine == elementDelimiter) { // A new element will follow after the delimiter
parseYamlElement(yamlAttributes)?.let { specificationElement ->
specificationElements.add(specificationElement)
}
yamlAttributes.clear()
continue
}
yamlAttributes.add(trimmedLine)
}
// Add the last element because no empty line will follow
parseYamlElement(yamlAttributes)?.let { specificationElement ->
specificationElements.add(specificationElement)
}
}
return specificationElements
}
// Example .yaml element:
//
// Vehicle.ADAS.ABS:
// description: Antilock Braking System signals.
// type: branch
// uuid: 219270ef27c4531f874bbda63743b330
private fun parseYamlElement(yamlElement: List<String>, delimiter: Char = ';'): VssSpecificationSpecModel? {
val elementVssPath = yamlElement.first().substringBefore(":")
val yamlElementJoined = yamlElement
.joinToString(separator = delimiter.toString())
.substringAfter(delimiter) // Remove vssPath (already parsed)
.prependIndent(delimiter.toString()) // So the parsing is consistent for the first element
val members = VssSpecificationSpecModel::class.memberProperties
val fieldsToSet = mutableListOf<Pair<String, Any?>>()
// The VSSPath is an exception because it is parsed from the top level name.
val vssPathFieldInfo = Pair("vssPath", elementVssPath)
fieldsToSet.add(vssPathFieldInfo)
// Parse (example: "description: Antilock Braking System signals.") into name + value for all .yaml lines
for (member in members) {
val memberName = member.name
if (!yamlElementJoined.contains(memberName)) continue
// Also parse the delimiter to not confuse type != datatype
val memberValue = yamlElementJoined
.substringAfter("$delimiter$memberName: ")
.substringBefore(delimiter)
val fieldInfo = Pair(memberName, memberValue)
fieldsToSet.add(fieldInfo)
}
val vssSpecificationMember = VssSpecificationSpecModel()
vssSpecificationMember.setFields(fieldsToSet)
if (vssSpecificationMember.uuid.isEmpty()) return null
return vssSpecificationMember
}
}
/**
* @param fields to set via reflection. Pair<PropertyName, anyValue>.
* @param remapNames which can be used if the propertyName does not match with the input name
*/
private fun VssSpecification.setFields(
fields: List<Pair<String, Any?>>,
remapNames: Map<String, String> = emptyMap(),
) {
val nameToProperty = this::class.memberProperties.associateBy(KProperty<*>::name)
val remappedFields = fields.toMutableList()
remapNames.forEach { (propertyName, newName) ->
val find = fields.find { it.first == propertyName } ?: return@forEach
remappedFields.remove(find)
remappedFields.add(Pair(find.first, newName))
}
remappedFields.forEach { (propertyName, propertyValue) ->
nameToProperty[propertyName]
.takeIf { it is KMutableProperty<*> }
?.let { it as KMutableProperty<*> }
?.setter?.call(this, propertyValue)
}
}
| 19 |
Kotlin
|
1
| 2 |
dc303f550b130bae2302e81bb5565ad3d28521c1
| 4,858 |
kuksa-android-sdk
|
Apache License 2.0
|
core/src/test/java/com/afollestad/inlineactivityresult/SchedulerTest.kt
|
afollestad
| 183,301,949 | false | null |
/**
* Designed and developed by <NAME> (@afollestad)
*
* 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.afollestad.inlineactivityresult
import android.app.Activity.RESULT_CANCELED
import android.app.Activity.RESULT_OK
import android.content.Intent
import com.afollestad.inlineactivityresult.internal.InlineFragment
import com.afollestad.inlineactivityresult.internal.Scheduler
import com.afollestad.inlineactivityresult.internal.Scheduler.Companion.FRAGMENT_TAG_PREFIX
import com.afollestad.inlineactivityresult.tests.NoManifestTestRunner
import com.afollestad.inlineactivityresult.tests.TestFragmentManager
import com.afollestad.inlineactivityresult.tests.TestOnResult
import com.afollestad.inlineactivityresult.tests.assertFragmentAdded
import com.afollestad.inlineactivityresult.tests.expectThrows
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(NoManifestTestRunner::class)
class SchedulerTest {
private val testFragmentManager = TestFragmentManager()
private val intent = Intent("com.action.TEST")
@After fun cleanup() {
Scheduler.destroy()
}
@Test fun `schedule and deliver result - success`() {
val requestCode = 69
val onResult = TestOnResult()
val instance = Scheduler.get()
.apply {
schedule(
fragmentManager = testFragmentManager.fragmentManager,
intent = intent,
requestCode = requestCode,
onResult = onResult.capture()
)
}
assertThat(instance.pending).containsKey(requestCode)
val (fragment, tag) = testFragmentManager.assertFragmentAdded<InlineFragment>()
assertThat(tag).isEqualTo("${FRAGMENT_TAG_PREFIX}_$requestCode")
// Try to deliver result with mismatched requestCodex
expectThrows<IllegalStateException>("There's no pending request for requestCode 12313.") {
instance.deliverResult(12313, RESULT_OK, intent)
}
// Now successfully deliver a result
instance.deliverResult(requestCode, RESULT_OK, intent)
testFragmentManager.assertFragmentRemoved(fragment)
assertThat(instance.pending).doesNotContainKey(requestCode)
// Assert the callback invocation
onResult.assertValues(true, intent)
}
@Test fun `schedule and deliver result - failure`() {
val requestCode = 70
val onResult = TestOnResult()
val instance = Scheduler.get()
.apply {
schedule(
fragmentManager = testFragmentManager.fragmentManager,
intent = intent,
requestCode = requestCode,
onResult = onResult.capture()
)
}
assertThat(instance.pending).containsKey(requestCode)
val (fragment, tag) = testFragmentManager.assertFragmentAdded<InlineFragment>()
assertThat(tag).isEqualTo("${FRAGMENT_TAG_PREFIX}_$requestCode")
// Now successfully deliver a result
instance.deliverResult(requestCode, RESULT_CANCELED, intent)
testFragmentManager.assertFragmentRemoved(fragment)
assertThat(instance.pending).doesNotContainKey(requestCode)
// Assert the callback invocation
onResult.assertValues(false, intent)
}
}
| 2 |
Kotlin
|
14
| 318 |
01a4c388a279d2205ada800d583e53d1dc34a3d7
| 3,721 |
inline-activity-result
|
Apache License 2.0
|
flogger/src/main/java/com/zc/flogger/extensions/StringExtensions.kt
|
zahichemaly
| 791,852,547 | false |
{"Kotlin": 25227}
|
package com.zc.flogger.extensions
private const val REGEX_BRACKETS = "\\{([^{}]+)\\}"
private fun String.extractFromRegex(regex: String): String? {
val matchResult = Regex(regex).find(this)
return matchResult?.groupValues?.getOrNull(1)
}
internal fun String.extractFromBrackets(): String? =
extractFromRegex(REGEX_BRACKETS)
| 0 |
Kotlin
|
0
| 0 |
19a9dc929b9ea5fc6dadd050e58f5ff31a1dc94e
| 340 |
FLogger
|
Apache License 2.0
|
compiler/testData/codegen/box/defaultArguments/reflection/classInClassObject.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// TARGET_BACKEND: JVM_IR
package test
class A {
companion object {
class Foo(val a: Int = 1) {}
}
}
fun box(): String {
Class.forName("test.A\$Companion\$Foo").getDeclaredConstructor()
return "OK"
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 227 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/matheusfernandes/remove/RemoveChaveEndpoint.kt
|
Mfrzero
| 391,083,206 | true |
{"Kotlin": 19535}
|
package br.com.zup.matheusfernandes.remove
import br.com.zup.matheusfernandes.KeymanagerRemoveGrpcServiceGrpc
import br.com.zup.matheusfernandes.RemoveChavePixRequest
import br.com.zup.matheusfernandes.RemoveChavePixResponse
import br.com.zup.matheusfernandes.handler.ErrorHandler
import io.grpc.stub.StreamObserver
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
@ErrorHandler
class RemoveChaveEndpoint (
@Inject private val service: RemoveChavePixService
) : KeymanagerRemoveGrpcServiceGrpc.KeymanagerRemoveGrpcServiceImplBase() {
override fun remove(request: RemoveChavePixRequest, responseObserver: StreamObserver<RemoveChavePixResponse>) {
service.remove(
clienteId = request.clienteId,
pixId = request.pixId
)
responseObserver.onNext(
RemoveChavePixResponse.newBuilder()
.setClienteId(request.clienteId)
.setPixId(request.pixId)
.build()
)
responseObserver.onCompleted()
}
}
| 0 |
Kotlin
|
0
| 0 |
cfbea74cf1c0ef888d55efb60b4339f230a31789
| 1,083 |
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
octicons/src/commonMain/kotlin/compose/icons/octicons/Gear24.kt
|
DevSrSouza
| 311,134,756 | false |
{"Kotlin": 36719092}
|
package compose.icons.octicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 compose.icons.Octicons
public val Octicons.Gear24: ImageVector
get() {
if (_gear24 != null) {
return _gear24!!
}
_gear24 = Builder(name = "Gear24", 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 = EvenOdd) {
moveTo(16.0f, 12.0f)
arcToRelative(4.0f, 4.0f, 0.0f, true, true, -8.0f, 0.0f)
arcToRelative(4.0f, 4.0f, 0.0f, false, true, 8.0f, 0.0f)
close()
moveTo(14.5f, 12.0f)
arcToRelative(2.5f, 2.5f, 0.0f, true, true, -5.0f, 0.0f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, 5.0f, 0.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(12.0f, 1.0f)
curveToRelative(-0.268f, 0.0f, -0.534f, 0.01f, -0.797f, 0.028f)
curveToRelative(-0.763f, 0.055f, -1.345f, 0.617f, -1.512f, 1.304f)
lineToRelative(-0.352f, 1.45f)
curveToRelative(-0.02f, 0.078f, -0.09f, 0.172f, -0.225f, 0.22f)
arcToRelative(8.45f, 8.45f, 0.0f, false, false, -0.728f, 0.303f)
curveToRelative(-0.13f, 0.06f, -0.246f, 0.044f, -0.315f, 0.002f)
lineToRelative(-1.274f, -0.776f)
curveToRelative(-0.604f, -0.368f, -1.412f, -0.354f, -1.99f, 0.147f)
curveToRelative(-0.403f, 0.348f, -0.78f, 0.726f, -1.129f, 1.128f)
curveToRelative(-0.5f, 0.579f, -0.515f, 1.387f, -0.147f, 1.99f)
lineToRelative(0.776f, 1.275f)
curveToRelative(0.042f, 0.069f, 0.059f, 0.185f, -0.002f, 0.315f)
curveToRelative(-0.112f, 0.237f, -0.213f, 0.48f, -0.302f, 0.728f)
curveToRelative(-0.05f, 0.135f, -0.143f, 0.206f, -0.221f, 0.225f)
lineToRelative(-1.45f, 0.352f)
curveToRelative(-0.687f, 0.167f, -1.249f, 0.749f, -1.304f, 1.512f)
arcToRelative(11.149f, 11.149f, 0.0f, false, false, 0.0f, 1.594f)
curveToRelative(0.055f, 0.763f, 0.617f, 1.345f, 1.304f, 1.512f)
lineToRelative(1.45f, 0.352f)
curveToRelative(0.078f, 0.02f, 0.172f, 0.09f, 0.22f, 0.225f)
curveToRelative(0.09f, 0.248f, 0.191f, 0.491f, 0.303f, 0.729f)
curveToRelative(0.06f, 0.129f, 0.044f, 0.245f, 0.002f, 0.314f)
lineToRelative(-0.776f, 1.274f)
curveToRelative(-0.368f, 0.604f, -0.354f, 1.412f, 0.147f, 1.99f)
curveToRelative(0.348f, 0.403f, 0.726f, 0.78f, 1.128f, 1.129f)
curveToRelative(0.579f, 0.5f, 1.387f, 0.515f, 1.99f, 0.147f)
lineToRelative(1.275f, -0.776f)
curveToRelative(0.069f, -0.042f, 0.185f, -0.059f, 0.315f, 0.002f)
curveToRelative(0.237f, 0.112f, 0.48f, 0.213f, 0.728f, 0.302f)
curveToRelative(0.135f, 0.05f, 0.206f, 0.143f, 0.225f, 0.221f)
lineToRelative(0.352f, 1.45f)
curveToRelative(0.167f, 0.687f, 0.749f, 1.249f, 1.512f, 1.303f)
arcToRelative(11.125f, 11.125f, 0.0f, false, false, 1.594f, 0.0f)
curveToRelative(0.763f, -0.054f, 1.345f, -0.616f, 1.512f, -1.303f)
lineToRelative(0.352f, -1.45f)
curveToRelative(0.02f, -0.078f, 0.09f, -0.172f, 0.225f, -0.22f)
curveToRelative(0.248f, -0.09f, 0.491f, -0.191f, 0.729f, -0.303f)
curveToRelative(0.129f, -0.06f, 0.245f, -0.044f, 0.314f, -0.002f)
lineToRelative(1.274f, 0.776f)
curveToRelative(0.604f, 0.368f, 1.412f, 0.354f, 1.99f, -0.147f)
curveToRelative(0.403f, -0.348f, 0.78f, -0.726f, 1.129f, -1.128f)
curveToRelative(0.5f, -0.579f, 0.515f, -1.387f, 0.147f, -1.99f)
lineToRelative(-0.776f, -1.275f)
curveToRelative(-0.042f, -0.069f, -0.059f, -0.185f, 0.002f, -0.315f)
curveToRelative(0.112f, -0.237f, 0.213f, -0.48f, 0.302f, -0.728f)
curveToRelative(0.05f, -0.135f, 0.143f, -0.206f, 0.221f, -0.225f)
lineToRelative(1.45f, -0.352f)
curveToRelative(0.687f, -0.167f, 1.249f, -0.749f, 1.303f, -1.512f)
arcToRelative(11.125f, 11.125f, 0.0f, false, false, 0.0f, -1.594f)
curveToRelative(-0.054f, -0.763f, -0.616f, -1.345f, -1.303f, -1.512f)
lineToRelative(-1.45f, -0.352f)
curveToRelative(-0.078f, -0.02f, -0.172f, -0.09f, -0.22f, -0.225f)
arcToRelative(8.469f, 8.469f, 0.0f, false, false, -0.303f, -0.728f)
curveToRelative(-0.06f, -0.13f, -0.044f, -0.246f, -0.002f, -0.315f)
lineToRelative(0.776f, -1.274f)
curveToRelative(0.368f, -0.604f, 0.354f, -1.412f, -0.147f, -1.99f)
curveToRelative(-0.348f, -0.403f, -0.726f, -0.78f, -1.128f, -1.129f)
curveToRelative(-0.579f, -0.5f, -1.387f, -0.515f, -1.99f, -0.147f)
lineToRelative(-1.275f, 0.776f)
curveToRelative(-0.069f, 0.042f, -0.185f, 0.059f, -0.315f, -0.002f)
arcToRelative(8.465f, 8.465f, 0.0f, false, false, -0.728f, -0.302f)
curveToRelative(-0.135f, -0.05f, -0.206f, -0.143f, -0.225f, -0.221f)
lineToRelative(-0.352f, -1.45f)
curveToRelative(-0.167f, -0.687f, -0.749f, -1.249f, -1.512f, -1.304f)
arcTo(11.149f, 11.149f, 0.0f, false, false, 12.0f, 1.0f)
close()
moveTo(11.31f, 2.525f)
arcToRelative(9.648f, 9.648f, 0.0f, false, true, 1.38f, 0.0f)
curveToRelative(0.055f, 0.004f, 0.135f, 0.05f, 0.162f, 0.16f)
lineToRelative(0.351f, 1.45f)
curveToRelative(0.153f, 0.628f, 0.626f, 1.08f, 1.173f, 1.278f)
curveToRelative(0.205f, 0.074f, 0.405f, 0.157f, 0.6f, 0.249f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, 1.733f, -0.074f)
lineToRelative(1.275f, -0.776f)
curveToRelative(0.097f, -0.06f, 0.186f, -0.036f, 0.228f, 0.0f)
curveToRelative(0.348f, 0.302f, 0.674f, 0.628f, 0.976f, 0.976f)
curveToRelative(0.036f, 0.042f, 0.06f, 0.13f, 0.0f, 0.228f)
lineToRelative(-0.776f, 1.274f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, -0.074f, 1.734f)
curveToRelative(0.092f, 0.195f, 0.175f, 0.395f, 0.248f, 0.6f)
curveToRelative(0.198f, 0.547f, 0.652f, 1.02f, 1.278f, 1.172f)
lineToRelative(1.45f, 0.353f)
curveToRelative(0.111f, 0.026f, 0.157f, 0.106f, 0.161f, 0.161f)
arcToRelative(9.653f, 9.653f, 0.0f, false, true, 0.0f, 1.38f)
curveToRelative(-0.004f, 0.055f, -0.05f, 0.135f, -0.16f, 0.162f)
lineToRelative(-1.45f, 0.351f)
arcToRelative(1.833f, 1.833f, 0.0f, false, false, -1.278f, 1.173f)
arcToRelative(6.926f, 6.926f, 0.0f, false, true, -0.25f, 0.6f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, 0.075f, 1.733f)
lineToRelative(0.776f, 1.275f)
curveToRelative(0.06f, 0.097f, 0.036f, 0.186f, 0.0f, 0.228f)
arcToRelative(9.555f, 9.555f, 0.0f, false, true, -0.976f, 0.976f)
curveToRelative(-0.042f, 0.036f, -0.13f, 0.06f, -0.228f, 0.0f)
lineToRelative(-1.275f, -0.776f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, -1.733f, -0.074f)
arcToRelative(6.926f, 6.926f, 0.0f, false, true, -0.6f, 0.248f)
arcToRelative(1.833f, 1.833f, 0.0f, false, false, -1.172f, 1.278f)
lineToRelative(-0.353f, 1.45f)
curveToRelative(-0.026f, 0.111f, -0.106f, 0.157f, -0.161f, 0.161f)
arcToRelative(9.653f, 9.653f, 0.0f, false, true, -1.38f, 0.0f)
curveToRelative(-0.055f, -0.004f, -0.135f, -0.05f, -0.162f, -0.16f)
lineToRelative(-0.351f, -1.45f)
arcToRelative(1.833f, 1.833f, 0.0f, false, false, -1.173f, -1.278f)
arcToRelative(6.928f, 6.928f, 0.0f, false, true, -0.6f, -0.25f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, -1.734f, 0.075f)
lineToRelative(-1.274f, 0.776f)
curveToRelative(-0.097f, 0.06f, -0.186f, 0.036f, -0.228f, 0.0f)
arcToRelative(9.56f, 9.56f, 0.0f, false, true, -0.976f, -0.976f)
curveToRelative(-0.036f, -0.042f, -0.06f, -0.13f, 0.0f, -0.228f)
lineToRelative(0.776f, -1.275f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, 0.074f, -1.733f)
arcToRelative(6.948f, 6.948f, 0.0f, false, true, -0.249f, -0.6f)
arcToRelative(1.833f, 1.833f, 0.0f, false, false, -1.277f, -1.172f)
lineToRelative(-1.45f, -0.353f)
curveToRelative(-0.111f, -0.026f, -0.157f, -0.106f, -0.161f, -0.161f)
arcToRelative(9.648f, 9.648f, 0.0f, false, true, 0.0f, -1.38f)
curveToRelative(0.004f, -0.055f, 0.05f, -0.135f, 0.16f, -0.162f)
lineToRelative(1.45f, -0.351f)
arcToRelative(1.833f, 1.833f, 0.0f, false, false, 1.278f, -1.173f)
arcToRelative(6.95f, 6.95f, 0.0f, false, true, 0.249f, -0.6f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, -0.074f, -1.734f)
lineToRelative(-0.776f, -1.274f)
curveToRelative(-0.06f, -0.097f, -0.036f, -0.186f, 0.0f, -0.228f)
curveToRelative(0.302f, -0.348f, 0.628f, -0.674f, 0.976f, -0.976f)
curveToRelative(0.042f, -0.036f, 0.13f, -0.06f, 0.228f, 0.0f)
lineToRelative(1.274f, 0.776f)
arcToRelative(1.832f, 1.832f, 0.0f, false, false, 1.734f, 0.074f)
arcToRelative(6.95f, 6.95f, 0.0f, false, true, 0.6f, -0.249f)
arcToRelative(1.833f, 1.833f, 0.0f, false, false, 1.172f, -1.277f)
lineToRelative(0.353f, -1.45f)
curveToRelative(0.026f, -0.111f, 0.106f, -0.157f, 0.161f, -0.161f)
close()
}
}
.build()
return _gear24!!
}
private var _gear24: ImageVector? = null
| 17 |
Kotlin
|
25
| 571 |
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 11,497 |
compose-icons
|
MIT License
|
src/test/kotlin/com/sordle/WatpadsCardDeck/WatpadsCardDeckApplicationTests.kt
|
TomasValdes
| 829,781,761 | false |
{"Kotlin": 2339}
|
package com.sordle.WatpadsCardDeck
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class WatpadsCardDeckApplicationTests {
@Test
fun contextLoads() {
}
}
| 2 |
Kotlin
|
0
| 0 |
f6dcae6370eb651791f11d5b4edacdc20395b8a6
| 223 |
watpads-card-deck
|
MIT License
|
ratatosk/src/main/java/com/danielceinos/ratatosk/extensions/FlowableExtensions.kt
|
danielceinos
| 171,038,649 | false | null |
package com.danielceinos.ratatosk.extensions
import io.reactivex.Flowable
import io.reactivex.Observable
import mini.mapNotNull
/**
* Apply the mapping function if object is not null.
*/
inline fun <T, U> Flowable<T>.mapNotNull(crossinline fn: (T) -> U?): Flowable<U> {
return flatMap {
val mapped = fn(it)
if (mapped == null) Flowable.empty()
else Flowable.just(mapped)
}
}
/**
* Apply the mapping function if object is not null.
*/
inline fun <T, U> Observable<T>.mapNotNull(crossinline fn: (T) -> U?): Observable<U> {
return flatMap {
val mapped = fn(it)
if (mapped == null) Observable.empty()
else Observable.just(mapped)
}
}
/**
* Apply the mapping function if object is not null together with a distinctUntilChanged call.
*/
inline fun <T, U> Flowable<T>.select(crossinline fn: (T) -> U?): Flowable<U> =
mapNotNull(fn).distinctUntilChanged()
/**
* Apply the mapping function if object is not null together with a distinctUntilChanged call.
*/
inline fun <T, U> Observable<T>.select(crossinline fn: (T) -> U?): Observable<U> =
mapNotNull(fn).distinctUntilChanged()
| 3 |
Kotlin
|
1
| 5 |
cfdd3c1059b386cb6c0a06e3afdc912079871741
| 1,155 |
Ratatosk
|
MIT License
|
src/main/java/com/fynd/nitrozen/nitrozenbutton/drawer/DividerDrawer.kt
|
gofynd
| 238,860,720 | false | null |
package com.fynd.nitrozen.nitrozenbutton.drawer
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.LinearLayout
import com.fynd.nitrozen.utils.Drawer
import com.fynd.nitrozen.nitrozenbutton.NBtn
import com.fynd.nitrozen.nitrozenbutton.model.NitrozenButton
import com.fynd.nitrozen.nitrozenbutton.model.Shape
class DividerDrawer(val view: NBtn, val button: NitrozenButton)
: Drawer<NBtn, NitrozenButton>(view, button) {
private var div: View = View(view.context)
override fun draw() {
initDivider()
view.addView(div)
}
override fun isReady(): Boolean {
return button.divVisibility != View.GONE
}
private fun initDivider() {
div.visibility = button.divVisibility
val divParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
divParams.marginStart = button.divMarginStart.toInt()
divParams.topMargin = button.divMarginTop.toInt()
divParams.marginEnd = button.divMarginEnd.toInt()
divParams.bottomMargin = button.divMarginBottom.toInt()
setMeasure(divParams)
setColor()
div.layoutParams = divParams
}
private fun setColor() {
if (!button.enable) {
if (button.elementsDisableColor != 0) {
div.setBackgroundColor(button.elementsDisableColor)
} else {
div.setBackgroundColor(button.divColor)
div.alpha = getAlpha()
}
} else {
div.setBackgroundColor(button.divColor)
}
}
// Set the divider measure if a shape of the button was changed
private fun setMeasure(divParams: ViewGroup.MarginLayoutParams) {
val minMeasure = Math.min(view.measuredWidthAndState, view.measuredHeightAndState)
val borderMeasure = (button.borderWidth * 2f).toInt()
if (button.divHeight == 0f && view.orientation == LinearLayout.HORIZONTAL) {
divParams.height = view.measuredHeightAndState - borderMeasure
} else {
divParams.height = button.divHeight.toInt()
}
if (button.divWidth == 0f && view.orientation == LinearLayout.VERTICAL) {
divParams.width = view.measuredWidthAndState - borderMeasure
} else {
divParams.width = button.divWidth.toInt()
}
}
override fun updateLayout() {
initDivider()
}
}
| 0 |
Kotlin
|
0
| 1 |
9b98a8eaeec547c44ddb35c345b5ac3dff2d0a6f
| 2,459 |
nitrozen-android
|
MIT License
|
goblinframework-remote-server/src/main/java/org/goblinframework/remote/server/module/config/RemoteServerConfigManager.kt
|
HuangKunInkess
| 224,439,191 | false |
{"INI": 8, "Gradle": 35, "Markdown": 1, "Text": 1, "Ignore List": 1, "Kotlin": 514, "XML": 27, "JSON": 9, "Java": 418, "FreeMarker": 10, "SQL": 3, "CSS": 8, "JavaScript": 8, "SVG": 2, "Fluent": 5}
|
package org.goblinframework.remote.server.module.config
import org.goblinframework.api.annotation.Singleton
import org.goblinframework.core.service.GoblinManagedObject
@Singleton
class RemoteServerConfigManager private constructor()
: GoblinManagedObject(), RemoteServerConfigManagerMXBean {
companion object {
@JvmField val INSTANCE = RemoteServerConfigManager()
}
val configParser = RemoteServerConfigParser()
fun getRemoteServerConfig(): RemoteServerConfig? {
return configParser.getRemoteServerConfig()
}
override fun disposeBean() {
configParser.dispose()
}
}
| 1 | null |
1
| 1 |
75124c38c952c51dfed9849d11ee20d2424eb081
| 598 |
goblinframework
|
Apache License 2.0
|
subprojects/common/sentry/src/main/kotlin/com/avito/android/sentry/SentryConfig.kt
|
avito-tech
| 230,265,582 | false | null |
package com.avito.android.sentry
import io.sentry.SentryClient
import io.sentry.SentryClientFactory
import io.sentry.connection.NoopConnection
import io.sentry.context.ThreadLocalContextManager
import java.io.Serializable
fun sentryClient(config: SentryConfig): SentryClient {
return when (config) {
is SentryConfig.Disabled ->
SentryClient(NoopConnection(), ThreadLocalContextManager())
is SentryConfig.Enabled ->
SentryClientFactory.sentryClient(
config.dsn,
CustomizableSentryClientFactory(config.maxStringLength)
).apply {
environment = config.environment
serverName = config.serverName
release = config.release
config.tags.forEach { (key, value) ->
addTag(key, value)
}
}
}
}
/**
* Some payloads are bigger than default 400 symbols but helpful for troubleshooting
*
* https://github.com/getsentry/sentry-java/issues/543
*/
private const val DEFAULT_SENTRY_MAX_STRING: Int = 50000
/**
* Default config for SentryClient
*/
sealed class SentryConfig : Serializable {
object Disabled : SentryConfig()
data class Enabled(
val dsn: String,
val environment: String,
val serverName: String,
val release: String,
val tags: Map<String, String>,
val maxStringLength: Int = DEFAULT_SENTRY_MAX_STRING
) : SentryConfig()
}
| 10 | null |
50
| 414 |
bc94abf5cbac32ac249a653457644a83b4b715bb
| 1,491 |
avito-android
|
MIT License
|
src/main/kotlin/me/elsiff/morefish/shop/FishShopKeeperTrait.kt
|
wotnak
| 360,557,145 | true |
{"Kotlin": 105382}
|
package me.elsiff.morefish.shop
import me.elsiff.morefish.MoreFish
import me.elsiff.morefish.configuration.Config
import me.elsiff.morefish.configuration.Lang
import net.citizensnpcs.api.event.NPCRightClickEvent
import net.citizensnpcs.api.trait.Trait
import net.citizensnpcs.api.trait.TraitName
import org.bukkit.event.EventHandler
/**
* Created by elsiff on 2019-01-24.
*/
@TraitName("fishshop")
class FishShopKeeperTrait : Trait("fishshop") {
@EventHandler
fun onClickNpc(event: NPCRightClickEvent) {
if (event.npc == this.npc && MoreFish.instance.isEnabled) {
if (Config.standard.boolean("fish-shop.enable")) {
fishShop.openGuiTo(event.clicker)
} else {
event.clicker.sendMessage(Lang.text("shop-disabled"))
}
}
}
companion object {
private lateinit var fishShop: FishShop
fun init(fishShop: FishShop) {
this.fishShop = fishShop
}
}
}
| 8 |
Kotlin
|
1
| 3 |
7f2f55f76bd1114a2fd59c336cc8f17a8ac9449e
| 985 |
more-fish
|
MIT License
|
src/main/java/com/example/resilience4jkotlin/controller/NambawanController.kt
|
napatn
| 165,094,980 | false | null |
package com.example.resilience4jkotlin.controller
import com.example.resilience4jkotlin.service.NambawanService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/namba1")
class NambawanController(
val service: NambawanService
) {
@GetMapping("/method1")
fun method1(): String {
return service.method1()
}
@GetMapping("/circuitbreaker")
fun circuitbreaker(): String {
return service.circuitbreaker()
}
}
| 0 |
Kotlin
|
0
| 0 |
b78b4077cb7b74c76d4e68a68a8210736188d07d
| 620 |
resilience4j-kotlin
|
MIT License
|
src/main/kotlin/net/axay/kspigot/ipaddress/badipdetectionservices/GetIPIntel.kt
|
bluefireoly
| 275,054,909 | false | null |
@file:Suppress("MemberVisibilityCanBePrivate")
package net.axay.kspigot.ipaddress.badipdetectionservices
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.floatOrNull
import kotlinx.serialization.json.jsonPrimitive
import net.axay.kspigot.ipaddress.BadIPDetectionResult
import net.axay.kspigot.ipaddress.BadIPDetectionService
class GetIPIntel(
private val intensity: Float = 0.99f,
private val contactEmail: String = "[email protected]",
) : BadIPDetectionService("getipintel.net") {
override fun requestString(ip: String) =
"https://check.getipintel.net/check.php?ip=$ip&contact=$contactEmail&format=json"
override fun interpreteResult(result: JsonObject): BadIPDetectionResult {
val probability = result["result"]?.jsonPrimitive?.floatOrNull
?: return BadIPDetectionResult.ERROR
return if (probability >= intensity) BadIPDetectionResult.GENERAL_BAD else BadIPDetectionResult.GOOD
}
}
| 1 |
Kotlin
|
15
| 63 |
47c220f65b4e020275d8deaf92923018332686a1
| 969 |
KSpigot
|
Apache License 2.0
|
core/model/src/main/java/com/wap/wapp/core/model/survey/SurveyAnswer.kt
|
pknu-wap
| 689,890,586 | false |
{"Kotlin": 464855, "Shell": 233}
|
package com.wap.wapp.core.model.survey
data class SurveyAnswer(
val questionTitle: String,
val questionAnswer: String,
val questionType: QuestionType,
)
| 6 |
Kotlin
|
0
| 8 |
c113f9748956e4fd0400f632eaed93ccf3e2ef78
| 166 |
WAPP
|
MIT License
|
app/src/main/java/com/decimalab/simpletask/data/local/datastore/UserPreferences.kt
|
ShakilAhmedShaj
| 318,355,269 | false | null |
package com.decimalab.simpletask.data.local.datastore
import android.content.Context
import android.util.Log
import androidx.datastore.DataStore
import androidx.datastore.preferences.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
/**
* Created by <NAME> on 22,September,2020.
* <EMAIL>
*/
class UserPreferences(context: Context) {
private val applicationContext = context.applicationContext
private val dataStore: DataStore<Preferences>
companion object {
const val PREFERENCE_NAME = "my_data_store"
}
private object PreferenceKeys {
val ACCESS_TOKEN = preferencesKey<String>("key_access_token")
val TOKEN_ID = preferencesKey<String>("key_token_id")
val USER_ID = preferencesKey<String>("key_user_id")
val USER_NAME = preferencesKey<String>("key_user_name")
val USER_EMAIL = preferencesKey<String>("key_user_email")
}
init {
dataStore = applicationContext.createDataStore(
name = PREFERENCE_NAME
)
}
val getAccessToken: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
Log.d("DataStore", exception.message.toString())
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preference ->
val myName = preference[PreferenceKeys.ACCESS_TOKEN] ?: "null"
myName
}
val getTokenId: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
Log.d("DataStore", exception.message.toString())
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preference ->
val myName = preference[PreferenceKeys.TOKEN_ID] ?: "none"
myName
}
val getUserID: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
Log.d("DataStore", exception.message.toString())
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preference ->
val myName = preference[PreferenceKeys.USER_ID] ?: "none"
myName
}
val getUserName: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
Log.d("DataStore", exception.message.toString())
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preference ->
val myName = preference[PreferenceKeys.USER_NAME] ?: "none"
myName
}
val getUserEmail: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
Log.d("DataStore", exception.message.toString())
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preference ->
val myName = preference[PreferenceKeys.USER_EMAIL] ?: "none"
myName
}
suspend fun saveAccessToken(authToken: String) {
dataStore.edit { preferences ->
preferences[PreferenceKeys.ACCESS_TOKEN] = authToken
}
}
suspend fun saveTokenId(authToken: String) {
dataStore.edit { preferences ->
preferences[PreferenceKeys.TOKEN_ID] = authToken
}
}
suspend fun saveUserID(authToken: String) {
dataStore.edit { preferences ->
preferences[PreferenceKeys.USER_ID] = authToken
}
}
suspend fun saveUserName(authToken: String) {
dataStore.edit { preferences ->
preferences[PreferenceKeys.USER_NAME] = authToken
}
}
suspend fun saveUserEmail(authToken: String) {
dataStore.edit { preferences ->
preferences[PreferenceKeys.USER_EMAIL] = authToken
}
}
}
| 0 |
Kotlin
|
0
| 1 |
371f22b2cc387b2235003c838fa97a9b80700cbe
| 4,153 |
Simple_Task_RU
|
The Unlicense
|
arrangement/src/main/java/com/fang/arrangement/ui/shared/component/ArrangementList.kt
|
7ANG2C
| 794,384,998 | false |
{"Kotlin": 435901}
|
package com.fang.arrangement.ui.shared.component
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.FloatingActionButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.unit.dp
import com.fang.arrangement.R
import com.fang.arrangement.ui.shared.ext.clickRipple
import com.fang.cosmos.foundation.Action
import com.fang.cosmos.foundation.Invoke
import com.fang.cosmos.foundation.ui.component.CustomIcon
import com.fang.cosmos.foundation.ui.dsl.MaterialColor
@Composable
internal inline fun <reified T> ArrangementList(
modifier: Modifier = Modifier,
items: List<T>,
noinline key: ((item: T) -> Any)? = null,
noinline contentType: (item: T) -> Any? = { null },
noinline onSelect: Action<T>,
noinline onAdd: Invoke,
crossinline content: @Composable ColumnScope.(item: T) -> Unit,
) = Box(Modifier.fillMaxSize()) {
Crossfade(
targetState = items,
label = "ArrangementList${T::class.java.simpleName}",
) { innerItems ->
if (innerItems.isEmpty()) {
EmptyScreen(modifier = Modifier.fillMaxSize())
} else {
LazyColumn(
modifier = modifier,
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(
items = innerItems,
key = key,
contentType = contentType,
) { item ->
ArrangementCard(
modifier =
Modifier
.animateItem()
.fillMaxWidth()
.clickRipple { onSelect(item) },
) {
content(this, item)
}
}
item {
Fab(
modifier =
Modifier
.padding(bottom = 8.dp)
.alpha(0f),
onClick = {},
)
}
}
}
}
Fab(
modifier =
Modifier
.padding(20.dp)
.align(Alignment.BottomEnd),
onClick = onAdd,
)
}
@Composable
internal fun Fab(
modifier: Modifier,
onClick: Invoke,
) {
val iconTint = MaterialColor.onSecondaryContainer
FloatingActionButton(
onClick = onClick,
modifier = modifier,
containerColor = MaterialColor.inversePrimary,
contentColor = iconTint,
) {
CustomIcon(
drawableResId = R.drawable.arr_r24_add,
tint = iconTint,
)
}
}
| 0 |
Kotlin
|
0
| 0 |
7df9040856234c63b597a24e51feda55a19f4900
| 3,369 |
FANG
|
Apache License 2.0
|
features/game/domain/src/main/kotlin/io/github/japskiddin/sudoku/feature/game/domain/usecase/GetBoardUseCase.kt
|
Japskiddin
| 766,410,608 | false |
{"Kotlin": 298542}
|
package io.github.japskiddin.sudoku.feature.game.domain.usecase
import io.github.japskiddin.sudoku.core.common.BoardNotFoundException
import io.github.japskiddin.sudoku.core.domain.BoardRepository
import io.github.japskiddin.sudoku.core.model.Board
import javax.inject.Inject
public class GetBoardUseCase
@Inject
constructor(
private val boardRepository: BoardRepository
) {
public suspend operator fun invoke(uid: Long): Board {
return boardRepository.get(uid) ?: throw BoardNotFoundException("Board with $uid not found")
}
}
| 0 |
Kotlin
|
0
| 0 |
cd2211ba7a2e8b7dde80335dc5abf4616d970a88
| 549 |
SudokuGame
|
Apache License 2.0
|
openai-client/client/src/commonMain/kotlin/com/xebia/functional/openai/models/MessageContentTextAnnotationsFileCitationObject.kt
|
xebia-functional
| 629,411,216 | false | null |
/**
* Please note: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress("ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport")
package com.xebia.functional.openai.models
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
/**
* A citation within the message that points to a specific quote from a specific File associated
* with the assistant or the message. Generated when the assistant uses the \"retrieval\" tool to
* search files.
*
* @param type Always `file_citation`.
* @param text The text in the message content that needs to be replaced.
* @param fileCitation
* @param startIndex
* @param endIndex
*/
@Serializable
data class MessageContentTextAnnotationsFileCitationObject(
/* Always `file_citation`. */
@SerialName(value = "type")
@Required
val type: MessageContentTextAnnotationsFileCitationObject.Type,
/* The text in the message content that needs to be replaced. */
@SerialName(value = "text") @Required val text: kotlin.String,
@SerialName(value = "file_citation")
@Required
val fileCitation: MessageContentTextAnnotationsFileCitationObjectFileCitation,
@SerialName(value = "start_index") @Required val startIndex: kotlin.Int,
@SerialName(value = "end_index") @Required val endIndex: kotlin.Int
) {
/**
* Always `file_citation`.
*
* Values: file_citation
*/
@Serializable
enum class Type(val value: kotlin.String) {
@SerialName(value = "file_citation") file_citation("file_citation")
}
}
| 40 | null |
16
| 162 |
e8a62e98e2a6a2f8958045a8098987583d3e8b0a
| 1,645 |
xef
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/iot/CfnResourceSpecificLoggingPropsDsl.kt
|
cloudshiftinc
| 667,063,030 | false | null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.iot
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.iot.CfnResourceSpecificLoggingProps
/**
* Properties for defining a `CfnResourceSpecificLogging`.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.iot.*;
* CfnResourceSpecificLoggingProps cfnResourceSpecificLoggingProps =
* CfnResourceSpecificLoggingProps.builder()
* .logLevel("logLevel")
* .targetName("targetName")
* .targetType("targetType")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-resourcespecificlogging.html)
*/
@CdkDslMarker
public class CfnResourceSpecificLoggingPropsDsl {
private val cdkBuilder: CfnResourceSpecificLoggingProps.Builder =
CfnResourceSpecificLoggingProps.builder()
/**
* @param logLevel The default log level.Valid Values: `DEBUG | INFO | ERROR | WARN | DISABLED`.
*/
public fun logLevel(logLevel: String) {
cdkBuilder.logLevel(logLevel)
}
/** @param targetName The target name. */
public fun targetName(targetName: String) {
cdkBuilder.targetName(targetName)
}
/** @param targetType The target type. Valid Values: `DEFAULT | THING_GROUP` */
public fun targetType(targetType: String) {
cdkBuilder.targetType(targetType)
}
public fun build(): CfnResourceSpecificLoggingProps = cdkBuilder.build()
}
| 4 | null |
0
| 3 |
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 1,822 |
awscdk-dsl-kotlin
|
Apache License 2.0
|
src/main/java/io/github/lcriadof/atrevete/kotlin/capitulo4/c4p6.kt
|
lcriadof
| 344,240,788 | false | null |
/*
Atrévete con Kotlin:
ISBN: 9798792407336 [tapa dura, tipo encuadernación Hardcover (Case Laminate)]
ISBN: 9798596367164 [tapa blanda]
ambas ediciones son idénticas en contenido
Autor: http://luis.criado.online/index.html
Más información sobre el libro: http://luis.criado.online/cv/obra_ackotlin.html
*/
package io.github.lcriadof.atrevete.kotlin.capitulo4
import java.io.File
// ejemplo inspirado en
// https://jamie.mccrindle.org/posts/exploring-kotlin-standard-library-part-2/
fun main() {
try {
if (File("/tmp/kotlin/f6.txt").exists()) { // [1]
File("/tmp/kotlin/f6.txt").delete() // [2]
}
File("/tmp/kotlin/f3.txt").copyTo(File("/tmp/kotlin/f6.txt"))
}
catch (e: Exception) {
println(e)
}
}
| 0 |
Kotlin
|
0
| 0 |
82c5099b4104dd6406a1dc768e0cc4dbdbbf068b
| 759 |
AtreveteConKotlin
|
MIT License
|
app/src/main/kotlin/gg/destiny/lizard/base/widget/EmoteFireView.kt
|
xiphirx
| 108,712,151 | false | null |
package gg.destiny.lizard.base.widget
import android.animation.TimeAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import gg.destiny.lizard.base.extensions.scope
import java.util.Random
class EmoteFireView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private class FloatyBoi(private val emote: Drawable, private val view: View) {
companion object {
private val random = Random()
}
private var x = 0f
private var y = 0f
private var alpha = 1f
private var speedMultiplier = 1f
private var initialBirth = false
fun birth() {
x = random.nextFloat() * (view.width - emote.bounds.width())
y = (view.height + (random.nextInt(5) + 5) * emote.bounds.height()).toFloat()
alpha = 1f
emote.alpha = 255
speedMultiplier = random.nextFloat() / 4f + 0.1f
}
fun update(dt: Float) {
if (view.width * view.height == 0) {
return
}
if (!initialBirth) {
birth()
initialBirth = true
}
y -= view.height * speedMultiplier * dt
alpha -= speedMultiplier * dt
emote.alpha = (255 * alpha).toInt()
if (emote.alpha <= 0 || y < emote.bounds.height()) {
birth()
}
}
fun draw(canvas: Canvas) {
if (view.width * view.height == 0) {
return
}
canvas.scope {
translate(x, y)
emote.draw(canvas)
}
}
}
private val floatyBois = mutableListOf<FloatyBoi>()
private val animator = TimeAnimator()
private val animatorListener = TimeAnimator.TimeListener { _, _, dt ->
for (floatyBoi in floatyBois) {
floatyBoi.update(dt / 1000f)
}
postInvalidate()
}
override fun onFinishInflate() {
super.onFinishInflate()
// EMOTE_MAP.entries.forEach {
// floatyBois.add(FloatyBoi(it.value.drawable.mutate(), this))
// }
}
override fun onDraw(canvas: Canvas) {
for (floatyBoi in floatyBois) {
floatyBoi.draw(canvas)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
animator.start()
animator.setTimeListener(animatorListener)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
animator.setTimeListener(null)
}
}
| 3 |
Kotlin
|
2
| 5 |
e45e8e76cac827ccafa83eade8abadcd70a85bfc
| 2,447 |
lizard
|
Apache License 2.0
|
chess/src/main/java/com/ajcm/chess/board/PositionConst.kt
|
jassielcastro
| 364,715,505 | false | null |
package com.ajcm.chess.board
object PositionConst {
const val ONE = 1
const val TWO = 2
const val THREE = 3
const val FOUR = 4
const val FIVE = 5
const val SIX = 6
const val SEVEN = 7
const val EIGHT = 8
}
| 0 |
Kotlin
|
0
| 9 |
621e9f7f77fac0f82a067f0843a2196e21e22226
| 239 |
ChessApp
|
MIT License
|
app/src/main/java/com/anafthdev/musicompose2/data/SortType.kt
|
kafri8889
| 509,012,286 | false |
{"Kotlin": 356863}
|
package com.anafthdev.musicompose2.data
enum class SortType {
SONG,
ALBUM,
ARTIST,
PLAYLIST
}
| 3 |
Kotlin
|
8
| 40 |
fa8c356aa2967228b91dc68ef99c395be22b73fb
| 98 |
Musicompose-V2
|
Do What The F*ck You Want To Public License
|
src/jvmMain/kotlin/common.kt
|
ilya-g
| 296,181,548 | false | null |
package org.test.benchmarks.string_replace
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.random.Random
fun generateTestString(totalLength: Int, needle: String, occurrences: Int): String {
val seed = Random.nextLong()
val rnd = Random(seed)
require(needle.length > 0 && needle.length * occurrences <= totalLength)
val randomChars = charArrayOf('<', '>')
return buildString(totalLength) {
var totalRuns = (totalLength - (needle.length * occurrences))
val avgRun = totalRuns / (occurrences + 1)
repeat(occurrences) {
val runLength = rnd.nextInt(0, (avgRun * 2).coerceAtMost(totalRuns) + 1)
repeat(runLength) { append(randomChars.random(rnd)) }
append(needle)
totalRuns -= runLength
}
repeat(totalRuns) { append(randomChars.random(rnd)) }
check(this.length == totalLength)
println("$seed: ${this.take(80)}...")
}
}
fun String.replaceRegex(oldValue: String, newValue: String, ignoreCase: Boolean = false): String {
return Pattern.compile(oldValue, Pattern.LITERAL or if(ignoreCase) Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE else 0)
.matcher(this)
.replaceAll(Matcher.quoteReplacement(newValue))
}
fun String.replaceRegex1(oldValue: String, newValue: String, ignoreCase: Boolean = false): String {
val matcher = Pattern.compile(oldValue, Pattern.LITERAL or if (ignoreCase) Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE else 0).matcher(this)
if (!matcher.find()) return this
val sb = StringBuilder()
var i = 0
do {
sb.append(this, i, matcher.start()).append(newValue)
i = matcher.end()
} while (matcher.find())
sb.append(this, i, length)
return sb.toString()
}
fun String.replacePlatform(oldValue: String, newValue: String, ignoreCase: Boolean = false): String {
require(ignoreCase == false) { "case insensitive replacement is not supported" }
return (this as java.lang.String).replace(oldValue, newValue)
}
fun String.replaceManual(oldValue: String, newValue: String, ignoreCase: Boolean = false): String {
var occurrenceIndex: Int = indexOf(oldValue, 0, ignoreCase)
// FAST PATH: no match
if (occurrenceIndex < 0) return this
val oldValueLength = oldValue.length
val searchStep = oldValueLength.coerceAtLeast(1)
val newLengthHint = length - oldValueLength + newValue.length
if (newLengthHint < 0) throw OutOfMemoryError()
val stringBuilder = StringBuilder(newLengthHint)
var i = 0
do {
stringBuilder.append(this, i, occurrenceIndex).append(newValue)
i = occurrenceIndex + oldValueLength
if (occurrenceIndex >= length) break
occurrenceIndex = indexOf(oldValue, occurrenceIndex + searchStep, ignoreCase)
} while (occurrenceIndex > 0)
return stringBuilder.append(this, i, length).toString()
}
| 0 |
Kotlin
|
0
| 1 |
b236524f52bae3a4154e3d2ee256cf6f2dcddaf8
| 2,928 |
string-replace-benchmark
|
Apache License 2.0
|
executor/executor-rx-android/src/main/kotlin/com/agoda/boots/executor/RxAndroidExecutor.kt
|
agoda-com
| 166,779,285 | false | null |
package com.agoda.boots.executor
import com.agoda.boots.Executor
import com.agoda.boots.Executor.Companion.DEFAULT_CAPACITY
import rx.Completable
import rx.Scheduler
import rx.android.schedulers.AndroidSchedulers
/**
* Rx implementation of [Executor] with Android support.
*
* Can switch to Android's main thread context to invoke listeners
* and [non-concurrent][com.agoda.boots.Bootable.isConcurrent] bootables.
*/
class RxAndroidExecutor @JvmOverloads constructor(
private val scheduler: Scheduler,
override val capacity: Int = DEFAULT_CAPACITY
) : Executor {
override val isMainThreadSupported = true
override fun execute(isConcurrent: Boolean, executable: () -> Unit) {
val completable = Completable.create {
executable()
it.onCompleted()
}
val scheduler = if (isConcurrent) {
this.scheduler
} else {
AndroidSchedulers.mainThread()
}
completable
.subscribeOn(scheduler)
.observeOn(scheduler)
.subscribe()
}
}
| 8 | null |
10
| 89 |
5510efa719e1eb2dca6b7480c8ca0c6932e3174f
| 1,098 |
boots
|
Apache License 2.0
|
Demo/src/main/java/com/paypal/android/usecase/UpdateOrderUseCase.kt
|
paypal
| 390,097,712 | false |
{"Kotlin": 299789}
|
package com.paypal.android.usecase
import com.paypal.android.api.services.SDKSampleServerAPI
import com.paypal.android.api.services.SDKSampleServerResult
import com.paypal.android.paypalnativepayments.PayPalNativeShippingMethod
import com.paypal.android.utils.OrderUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class UpdateOrderUseCase @Inject constructor(
private val sdkSampleServerAPI: SDKSampleServerAPI
) {
suspend operator fun invoke(
orderId: String,
shippingMethod: PayPalNativeShippingMethod
): SDKSampleServerResult<Boolean, Exception> =
withContext(Dispatchers.IO) {
// https://developer.paypal.com/docs/api/orders/v2/#orders_patch
val options = OrderUtils.createShippingOptionsBuilder(selectedId = shippingMethod.id)
val patchShipping = PatchRequestBody(
path = "/purchase_units/@reference_id=='PUHF'/shipping/options",
value = options
)
val amount =
OrderUtils.getAmount(value = "5.0", shippingValue = shippingMethod.value ?: "0.0")
val patchAmount = PatchRequestBody(
path = "/purchase_units/@reference_id=='PUHF'/amount",
value = amount
)
sdkSampleServerAPI.patchOrder(orderId, listOf(patchAmount, patchShipping))
}
data class PatchRequestBody(
val op: String = "replace",
val path: String,
val value: Any
)
}
| 22 |
Kotlin
|
43
| 74 |
dcc46f92771196e979f7863b9b8d3fa3d6dc1a7d
| 1,543 |
paypal-android
|
Apache License 2.0
|
app/src/main/java/com/gold24park/jetsurvey/survey/SurveyViewModel.kt
|
gold24park
| 634,749,732 | false | null |
package com.gold24park.jetsurvey.survey
import android.net.Uri
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gold24park.jetsurvey.util.PhotoUriManager
const val simpleDateFormatPattern = "EEE, MMM d"
class SurveyViewModel(
private val photoUriManager: PhotoUriManager
) : ViewModel() {
private val questionOrder: List<SurveyQuestion> = SurveyQuestion.values().toList()
private var questionIndex = 0
private val _freeTimeResponse = mutableStateListOf<Int>()
val freeTimeResponse: List<Int>
get() = _freeTimeResponse
private val _superheroResponse = mutableStateOf<Superhero?>(null)
val superheroResponse: Superhero?
get() = _superheroResponse.value
private val _takeawayResponse = mutableStateOf<Long?>(null)
val takeawayResponse: Long?
get() = _takeawayResponse.value
private val _feelingAboutSelfiesResponse = mutableStateOf<Float?>(null)
val feelingAboutSelfiesResponse: Float?
get() = _feelingAboutSelfiesResponse.value
private val _selfieUri = mutableStateOf<Uri?>(null)
val selfieUri
get() = _selfieUri.value
private val _surveyScreenData = mutableStateOf(createSurveyScreenData())
val surveyScreenData: SurveyScreenData
get() = _surveyScreenData.value
private val _isNextEnabled = mutableStateOf(false)
val isNextEnabled: Boolean
get() = _isNextEnabled.value
fun onBackPressed(): Boolean {
if (questionIndex ==0) {
return false
}
changeQuestion(questionIndex - 1)
return true
}
fun onPreviousPressed() {
if (questionIndex == 0) {
throw IllegalStateException("onPreivousPressed when on question 0")
}
changeQuestion(questionIndex - 1)
}
fun onNextPressed() {
changeQuestion(questionIndex + 1)
}
fun onDonePressed(onSurveyComplete: () -> Unit) {
onSurveyComplete()
}
fun onFreeTimeResponse(selected: Boolean, answer: Int) {
if (selected) {
_freeTimeResponse.add(answer)
} else {
_freeTimeResponse.remove(answer)
}
_isNextEnabled.value = getIsNextEnabled()
}
fun onSuperheroResponse(superhero: Superhero) {
_superheroResponse.value = superhero
_isNextEnabled.value = getIsNextEnabled()
}
fun onTakeawayResponse(timestamp: Long) {
_takeawayResponse.value = timestamp
_isNextEnabled.value = getIsNextEnabled()
}
fun onFeelingAboutSelfiesResponse(feeling: Float) {
_feelingAboutSelfiesResponse.value = feeling
_isNextEnabled.value = getIsNextEnabled()
}
fun onSelfieResponse(uri: Uri) {
_selfieUri.value = uri
_isNextEnabled.value = getIsNextEnabled()
}
fun getNewSelfieUri() = photoUriManager.buildNewUri()
private fun changeQuestion(newQuestionIndex: Int) {
questionIndex = newQuestionIndex
_isNextEnabled.value = getIsNextEnabled()
_surveyScreenData.value = createSurveyScreenData()
}
private fun getIsNextEnabled(): Boolean {
return when (questionOrder[questionIndex]) {
SurveyQuestion.FREE_TIME -> _freeTimeResponse.isNotEmpty()
SurveyQuestion.SUPERHERO -> _superheroResponse.value != null
SurveyQuestion.LAST_TAKEAWAY -> _takeawayResponse.value != null
SurveyQuestion.FEELING_ABOUT_SELFIES -> _feelingAboutSelfiesResponse.value != null
SurveyQuestion.TAKE_SELFIE -> _selfieUri.value != null
}
}
private fun createSurveyScreenData(): SurveyScreenData {
return SurveyScreenData(
questionIndex = questionIndex,
questionCount = questionOrder.size,
shouldShowPreviousButton = questionIndex > 0,
shouldShowDoneButton = questionIndex == questionOrder.size - 1,
surveyQuestion = questionOrder[questionIndex]
)
}
}
class SurveyViewModelFactory(
private val photoUriManager: PhotoUriManager
): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SurveyViewModel::class.java)) {
return SurveyViewModel(photoUriManager) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
enum class SurveyQuestion {
FREE_TIME,
SUPERHERO,
LAST_TAKEAWAY,
FEELING_ABOUT_SELFIES,
TAKE_SELFIE,
}
data class SurveyScreenData(
val questionIndex: Int,
val questionCount: Int,
val shouldShowPreviousButton: Boolean,
val shouldShowDoneButton: Boolean,
val surveyQuestion: SurveyQuestion,
)
| 0 |
Kotlin
|
0
| 1 |
bb7386f5c238655606fca381d117aa9c70d4e8fd
| 4,821 |
JetSurvey-Simplified
|
MIT License
|
app/src/test/java/com/yatik/qrscanner/paging/sources/HistoryPagingSourceTest.kt
|
yatiksihag01
| 559,106,532 | false |
{"Kotlin": 231676, "Java": 1274}
|
/*
* Copyright 2023 Yatik
*
* 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.yatik.qrscanner.paging.sources
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.paging.PagingSource
import com.google.common.truth.Truth.*
import com.google.mlkit.vision.barcode.common.Barcode
import com.yatik.qrscanner.database.BarcodeDao
import com.yatik.qrscanner.models.BarcodeData
import com.yatik.qrscanner.utils.TestConstants.Companion.ITEMS_PER_PAGE
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.anyInt
import org.mockito.Mockito.mock
@OptIn(ExperimentalCoroutinesApi::class)
class HistoryPagingSourceTest {
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private val mockedDao = mock(BarcodeDao::class.java)
private lateinit var historyPagingSource: HistoryPagingSource
private val barcodeData = BarcodeData(
Barcode.FORMAT_QR_CODE, Barcode.TYPE_TEXT,
"sample text", null, null, "09-02-2023 11:50:54"
)
private val barcodeData2 = BarcodeData(
Barcode.FORMAT_QR_CODE, Barcode.TYPE_TEXT,
"sample text2", null, null, "09-02-2023 11:50:54"
)
@Before
fun setUp() {
historyPagingSource = HistoryPagingSource(mockedDao, ITEMS_PER_PAGE)
}
@Test
fun `load returns LoadResult page`() = runTest {
val mockedList = listOf(barcodeData, barcodeData2)
Mockito.`when`(mockedDao.getBarcodePages(anyInt(), anyInt())).thenReturn(mockedList)
val params = PagingSource.LoadParams
.Refresh<Int>(
key = null,
loadSize = ITEMS_PER_PAGE,
placeholdersEnabled = false
)
val result = historyPagingSource.load(params)
assertThat(result).isInstanceOf(PagingSource.LoadResult.Page::class.java)
val pageResult = result as PagingSource.LoadResult.Page
assertThat(pageResult.data).isEqualTo(mockedList)
assertThat(pageResult.prevKey).isNull()
assertThat(pageResult.nextKey).isEqualTo(1)
}
}
| 0 |
Kotlin
|
0
| 1 |
1a3b0f7294d9427a1be95057d8a70e18055db103
| 2,760 |
QR-Code-Scanner--Google-ML-Kit
|
Apache License 2.0
|
cookies/cookies-store/src/main/java/com/duckduckgo/cookies/store/thirdpartycookienames/ThirdPartyCookieNamesDao.kt
|
duckduckgo
| 78,869,127 | false |
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
|
/*
* Copyright (c) 2024 DuckDuckGo
*
* 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.duckduckgo.cookies.store.thirdpartycookienames
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.duckduckgo.cookies.store.CookieNamesEntity
@Dao
abstract class ThirdPartyCookieNamesDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertCookieNames(cookieNames: List<CookieNamesEntity>)
@Transaction
open fun updateAllCookieNames(cookieNames: List<CookieNamesEntity>) {
deleteCookieNames()
insertCookieNames(cookieNames)
}
@Query("select * from third_party_cookie_names")
abstract fun getCookieNames(): List<CookieNamesEntity>
@Query("delete from third_party_cookie_names")
abstract fun deleteCookieNames()
}
| 67 |
Kotlin
|
901
| 3,823 |
6415f0f087a11a51c0a0f15faad5cce9c790417c
| 1,410 |
Android
|
Apache License 2.0
|
app/src/main/java/io/homeassistant/companion/android/background/LocationBroadcastReceiverBase.kt
|
colincachia
| 284,297,238 | true |
{"Kotlin": 414215}
|
package io.homeassistant.companion.android.background
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import io.homeassistant.companion.android.common.dagger.GraphComponentAccessor
import io.homeassistant.companion.android.domain.integration.IntegrationUseCase
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
abstract class LocationBroadcastReceiverBase : BroadcastReceiver() {
companion object {
const val MINIMUM_ACCURACY = 200
const val ACTION_REQUEST_LOCATION_UPDATES =
"io.homeassistant.companion.android.background.REQUEST_UPDATES"
const val ACTION_REQUEST_ACCURATE_LOCATION_UPDATE =
"io.homeassistant.companion.android.background.REQUEST_ACCURATE_UPDATE"
const val ACTION_PROCESS_LOCATION =
"io.homeassistant.companion.android.background.PROCESS_UPDATES"
const val ACTION_PROCESS_GEO =
"io.homeassistant.companion.android.background.PROCESS_GEOFENCE"
internal const val TAG = "LocBroadcastReceiver"
}
@Inject
lateinit var integrationUseCase: IntegrationUseCase
internal val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job())
override fun onReceive(context: Context, intent: Intent) {
ensureInjected(context)
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED,
ACTION_REQUEST_LOCATION_UPDATES -> setupLocationTracking(context)
ACTION_PROCESS_LOCATION -> handleLocationUpdate(intent)
ACTION_PROCESS_GEO -> handleGeoUpdate(context, intent)
ACTION_REQUEST_ACCURATE_LOCATION_UPDATE -> requestSingleAccurateLocation(context)
else -> Log.w(TAG, "Unknown intent action: ${intent.action}!")
}
}
private fun ensureInjected(context: Context) {
if (context.applicationContext is GraphComponentAccessor) {
DaggerReceiverComponent.builder()
.appComponent((context.applicationContext as GraphComponentAccessor).appComponent)
.build()
.inject(this)
} else {
throw Exception("Application Context passed is not of our application!")
}
}
internal abstract fun setupLocationTracking(context: Context)
internal abstract fun handleLocationUpdate(intent: Intent)
internal abstract fun handleGeoUpdate(context: Context, intent: Intent)
internal abstract fun requestSingleAccurateLocation(context: Context)
}
| 0 |
Kotlin
|
0
| 0 |
56c7871e0f857d6472173789730dd814b9cd0bc6
| 2,627 |
android
|
Apache License 2.0
|
Estrutura Sequencial/Exercicio07.kt
|
DenertSousa
| 613,699,145 | false | null |
/*Este programa que calcula a área de um quadrado, e, em seguida, mostra
o dobro desta área para o usuário.*/
fun main () {
println("Informe o lado do quadro que você deseja calcular a área: ")
var l: Double? = readLine()!!.toDoubleOrNull()
if (l != null) {
println("""
A área do quadrado é ${l * l} u.a (unidade de área)
O dobro dessa área é ${2 * l * l} u.a (unidade de área)
""".trimIndent())
} else {
println("O que você informou não é um núemero\n" +
"Portanto, não podemos calcular a área.")
}
}
| 0 |
Kotlin
|
0
| 0 |
1902d1179ce553d1629e869a5e7e1af9ce049d94
| 589 |
Programando-em-Kotlin
|
MIT License
|
src/test/kotlin/com/wabradshaw/claptrap/ClaptrapServiceTest.kt
|
wabradshaw
| 154,681,482 | false | null |
package com.wabradshaw.claptrap
import com.wabradshaw.claptrap.design.JokeDesigner
import com.wabradshaw.claptrap.repositories.custom.JsonRepository
import com.wabradshaw.claptrap.repositories.datamuse.DataMuseRepository
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ClapTrapServiceTest {
@Test
fun tellRandomJoke(){
val mainRepository = JsonRepository()
val nucleusRepository = JsonRepository(object{}.javaClass.getResourceAsStream("/nucleusDictionary.json"))
val jokeDesigner = JokeDesigner(dictionaryRepo = mainRepository,
primarySemanticRepo = nucleusRepository,
secondarySemanticRepo = mainRepository,
linguisticRepo = mainRepository,
nucleusRepository = nucleusRepository)
var result = ClaptrapService(jokeDesigner).tellJoke()
println(result.spec)
println()
println(result.setup)
println(result.punchline)
}
@Test
fun tellSpecificJoke(){
val mainRepository = JsonRepository()
val nucleusRepository = JsonRepository(object{}.javaClass.getResourceAsStream("/nucleusDictionary.json"))
val jokeDesigner = JokeDesigner(dictionaryRepo = mainRepository,
primarySemanticRepo = nucleusRepository,
secondarySemanticRepo = mainRepository,
linguisticRepo = mainRepository,
nucleusRepository = nucleusRepository)
var result = ClaptrapService(jokeDesigner).tellJoke("catapult")
println(result.spec)
println()
println(result.setup)
println(result.punchline)
}
@Test
fun tellJokes(){
val mainRepository = JsonRepository()
val nucleusRepository = JsonRepository(object{}.javaClass.getResourceAsStream("/nucleusDictionary.json"))
val jokeDesigner = JokeDesigner(dictionaryRepo = mainRepository,
primarySemanticRepo = nucleusRepository,
secondarySemanticRepo = mainRepository,
linguisticRepo = mainRepository,
nucleusRepository = nucleusRepository)
val topics = listOf("catapult", "pirate", "captain", "slowboat", "winter", "summer", "spring", "damage", "hammersmith")
for(topic in topics) {
var result = ClaptrapService(jokeDesigner).tellJoke(topic)
println()
println(result.setup)
println(result.punchline)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
7886787603e477d47ea858a8d9c76e11c4c25fe3
| 2,648 |
claptrap
|
Apache License 2.0
|
app/src/main/java/com/radioroam/android/ui/components/player/PlayerComponents.kt
|
oguzhaneksi
| 718,750,332 | false |
{"Kotlin": 100870}
|
package com.radioroam.android.ui.components.player
import android.net.Uri
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment.Companion.Center
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.media3.common.Player
import androidx.media3.ui.R
import coil.compose.AsyncImage
@Composable
fun PlayPauseButton(
modifier: Modifier = Modifier,
isPlaying: Boolean,
isBuffering: Boolean,
iconTint: Color = MaterialTheme.colorScheme.onSurface,
onTogglePlayPause: () -> Unit
) {
if (isBuffering) {
PlayerProgressIndicator(
modifier = modifier,
progressTint = iconTint
)
}
else {
IconButton(
modifier = modifier,
onClick = {
onTogglePlayPause()
}
) {
Icon(
modifier = Modifier.fillMaxSize(fraction = .8f),
painter = painterResource(
id = if (isPlaying)
R.drawable.exo_icon_pause
else
R.drawable.exo_icon_play
),
contentDescription = if (isPlaying) "Pause" else "Play",
tint = iconTint
)
}
}
}
@Composable
fun PlayerProgressIndicator(
modifier: Modifier = Modifier,
progressTint: Color = MaterialTheme.colorScheme.onSurface
) {
Box(
modifier = modifier
) {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize(.8f)
.align(Center),
color = progressTint,
trackColor = Color.Transparent
)
}
}
@Composable
fun MiniPlayerArtworkView(
modifier: Modifier = Modifier,
artworkUri: Uri?
) {
Card(
modifier = modifier,
shape = RoundedCornerShape(4.dp)
) {
AsyncImage(
modifier = Modifier.fillMaxSize(),
model = artworkUri,
contentDescription = null,
)
}
}
@Composable
fun TimeBar(
modifier: Modifier = Modifier,
player: Player
) {
val currentPosition = remember { mutableLongStateOf(0L) }
val duration = remember { mutableLongStateOf(0L) }
LaunchedEffect(player) {
snapshotFlow { player.currentPosition }
.collect { currentPosition.longValue = it }
snapshotFlow { player.duration }
.collect { duration.longValue = it }
}
Slider(
modifier = modifier,
value = currentPosition.longValue.toFloat(),
onValueChange = {
},
valueRange = 0f..duration.longValue.toFloat()
)
}
@Composable
fun PreviousButton(
modifier: Modifier = Modifier,
iconTint: Color = MaterialTheme.colorScheme.onSurface,
onClick: () -> Unit
) {
IconButton(
modifier = modifier,
onClick = onClick
) {
Icon(
modifier = Modifier.fillMaxSize(fraction = .8f),
painter = painterResource(R.drawable.exo_icon_previous),
contentDescription = "Previous",
tint = iconTint
)
}
}
@Composable
fun NextButton(
modifier: Modifier = Modifier,
iconTint: Color = MaterialTheme.colorScheme.onSurface,
onClick: () -> Unit
) {
IconButton(
modifier = modifier,
onClick = onClick
) {
Icon(
modifier = Modifier.fillMaxSize(fraction = .8f),
painter = painterResource(R.drawable.exo_icon_next),
contentDescription = "Previous",
tint = iconTint
)
}
}
| 0 |
Kotlin
|
0
| 0 |
f26df7d4886e8c489653eb6001cd1c3a0bb52782
| 4,312 |
RadioRoam
|
MIT License
|
plugin/src/main/java/org/godotengine/plugin/vr/oculus/mobile/api/OvrDisplay.kt
|
GodotVR
| 135,216,333 | false | null |
@file:JvmName("OvrDisplay")
package org.godotengine.plugin.vr.oculus.mobile.api
import org.godotengine.plugin.vr.oculus.mobile.OvrMobilePlugin
/**
* Color space types for HMDs
* @see https://developer.oculus.com/documentation/native/android/mobile-colorspace/
*/
enum class ColorSpace(internal val value: Int) {
/** No color correction, not recommended for production use. See notes above for more info */
COLOR_SPACE_UNMANAGED(0),
/** Preferred color space for standardized color across all Oculus HMDs with D65 white point */
COLOR_SPACE_REC_2020(1),
/** Rec. 709 is used on Oculus Go and shares the same primary color coordinates as sRGB */
COLOR_SPACE_REC_709(2),
/** Oculus Rift CV1 uses a unique color space, see enum description for more info */
COLOR_SPACE_RIFT_CV1(3),
/** Oculus Rift S uses a unique color space, see enum description for more info */
COLOR_SPACE_RIFT_S(4),
/** Oculus Quest's native color space is slightly different than Rift CV1 */
COLOR_SPACE_QUEST(5),
/** Similar to DCI-P3. See notes above for more details on P3 */
COLOR_SPACE_P3(6),
/** Similar to sRGB but with deeper greens using D65 white point */
COLOR_SPACE_ADOBE_RGB(7);
companion object {
fun toColorSpace(value: Int): ColorSpace {
for (colorSpace in values()) {
if (colorSpace.value == value) {
return colorSpace
}
}
return COLOR_SPACE_UNMANAGED
}
}
}
/**
* Used to retrieve the device color space.
* This is a constant for each device type.
* @see https://developer.oculus.com/documentation/native/android/mobile-colorspace/
*/
fun OvrMobilePlugin.getColorSpace(): ColorSpace {
return if (isSharedLibLoaded()) {
ColorSpace.toColorSpace(nativeGetColorSpace())
} else {
ColorSpace.COLOR_SPACE_UNMANAGED
}
}
/**
* Used to update the device color space.
*
* @param[colorSpace] The new target color space.
* @return True if the device's color space was updated, false otherwise.
*/
fun OvrMobilePlugin.setColorSpace(colorSpace: ColorSpace): Boolean {
return if (isSharedLibLoaded()) {
nativeSetColorSpace(colorSpace.value)
} else {
false
}
}
/**
* Used to access the display refresh rates supported by the device.
*/
fun OvrMobilePlugin.getSupportedDisplayRefreshRates(): FloatArray {
return if (isSharedLibLoaded()) {
nativeGetSupportedDisplayRefreshRates()
} else {
floatArrayOf()
}
}
/**
* Used to update the device display refresh rate.
*
* @param[refreshRate] Target refresh rate. Must be one of the supported values returned by
* [getSupportedDisplayRefreshRates].
*/
fun OvrMobilePlugin.setDisplayRefreshRate(refreshRate: Float): Boolean {
return if (isSharedLibLoaded()) {
nativeSetDisplayRefreshRate(refreshRate)
} else {
false
}
}
private external fun nativeSetColorSpace(colorSpace: Int): Boolean
private external fun nativeGetColorSpace(): Int
private external fun nativeSetDisplayRefreshRate(refreshRate: Float): Boolean
private external fun nativeGetSupportedDisplayRefreshRates(): FloatArray
| 8 | null |
35
| 167 |
ede995f8344e6a41ba06e3f23d0c55e091b97cf9
| 3,221 |
godot_oculus_mobile
|
MIT License
|
app/src/main/java/cn/haohao/dbbook/domain/interactor/GetBookDetailInteractor.kt
|
githubhaohao
| 95,271,877 | false | null |
package cn.haohao.dbbook.domain.interactor
import cn.haohao.dbbook.data.datasource.BookDataSource
import cn.haohao.dbbook.data.entity.http.BookReviewsListResponse
import cn.haohao.dbbook.domain.entity.RequestDetailParams
import cn.haohao.dbbook.domain.executor.PostExecutionThread
import cn.haohao.dbbook.domain.executor.ThreadExecutor
import retrofit2.Response
import rx.Observable
/**
* Created by HaohaoChang on 2017/6/9.
*/
class GetBookDetailInteractor(val bookDataSource: BookDataSource,
threadExecutor: ThreadExecutor,
postExecutionThread: PostExecutionThread) :
Interactor<Response<BookReviewsListResponse>, RequestDetailParams>(threadExecutor, postExecutionThread) {
override fun buildObservable(params: RequestDetailParams): Observable<Response<BookReviewsListResponse>> =
bookDataSource.requestBookDetail(
params.bookId,
params.start,
params.count,
params.fields
)
}
| 1 | null |
32
| 163 |
bc08d6dd89fc86304b2b95cc1c2b3f67b55ee451
| 1,057 |
DoubanBook
|
Apache License 2.0
|
chart_server/src/main/kotlin/io/madrona/njord/layers/Boycar.kt
|
manimaul
| 213,533,249 | false |
{"Kotlin": 310677, "TypeScript": 70948, "Python": 12720, "PLpgSQL": 5036, "HTML": 3275, "Shell": 3043, "Dockerfile": 2008, "CSS": 1315}
|
package io.madrona.njord.layers
import io.madrona.njord.layers.attributehelpers.Catcam
import io.madrona.njord.layers.attributehelpers.Catcam.Companion.catcam
import io.madrona.njord.model.ChartFeature
/**
* Geometry Primitives: Point
*
* Object: Buoy, cardinal
*
* Acronym: BOYCAR
*
* Code: 14
*/
class Boycar : Bcnlat() {
override suspend fun preTileEncode(feature: ChartFeature) {
when (feature.catcam()) {
Catcam.NORTH_CARDINAL_MARK -> feature.pointSymbol(Sprite.BOYCAR01)
Catcam.EAST_CARDINAL_MARK -> feature.pointSymbol(Sprite.BOYCAR02)
Catcam.SOUTH_CARDINAL_MARK -> feature.pointSymbol(Sprite.BOYCAR03)
Catcam.WEST_CARDINAL_MARK -> feature.pointSymbol(Sprite.BOYCAR04)
null -> feature.pointSymbol(Sprite.BOYDEF03)
}
}
override fun layers(options: LayerableOptions) = sequenceOf(
pointLayerFromSymbol(),
)
}
| 16 |
Kotlin
|
3
| 8 |
73e3946d0e85b09b57158830934bb139498eb246
| 926 |
njord
|
Apache License 2.0
|
app/src/main/java/edu/gvsu/art/gallery/ui/artwork/detail/ArtworkDetailTitleRow.kt
|
gvsucis
| 655,904,905 | false |
{"Kotlin": 268436, "Makefile": 1977, "Ruby": 1690, "Java": 1027}
|
package edu.gvsu.art.gallery.ui.artwork.detail
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ViewInAr
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import edu.gvsu.art.client.Artwork
import edu.gvsu.art.gallery.R
import edu.gvsu.art.gallery.extensions.shareArtwork
import edu.gvsu.art.gallery.ui.TitleText
import edu.gvsu.art.gallery.ui.theme.ArtAtGVSUTheme
import edu.gvsu.art.gallery.ui.theme.Red
import java.net.URL
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun ArtworkDetailTitleRow(
artwork: Artwork,
isFavorite: Boolean = false,
toggleFavorite: () -> Unit = {},
) {
val context = LocalContext.current
val arState = rememberARAsset(artwork) { assets ->
Log.d("ArtworkDetailTitleRow", "URIs: $assets")
ArtworkARActivity.start(context, assets)
}
FlowRow(
verticalArrangement = Arrangement.Center,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.heightIn(min = 48.dp)
) {
TitleText(text = artwork.name)
}
Row {
if (artwork.hasAR) {
ArtworkARButton(
arAsset = arState.value,
progress = arState.progress,
onRequestARAsset = {
arState.requestARAsset()
},
)
}
IconButton(
onClick = { toggleFavorite() }
) {
Icon(
imageVector = if (isFavorite) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
tint = Red,
contentDescription = null
)
}
IconButton(onClick = { context.shareArtwork(artwork) }) {
Icon(
imageVector = Icons.Default.Share,
contentDescription = stringResource(R.string.artwork_detail_share)
)
}
}
}
}
@Composable
@Preview
fun PreviewArtworkDetailTitleRow() {
val artwork = Artwork(name = "My Artwork")
ArtAtGVSUTheme {
ArtworkDetailTitleRow(artwork = artwork)
}
}
@Composable
@Preview("Long title that could wrap")
fun PreviewArtworkDetailTitleRowLongText() {
val artwork = Artwork(name = "My Artwork Continuous Stream of Words")
ArtAtGVSUTheme {
ArtworkDetailTitleRow(artwork = artwork)
}
}
@Composable
@Preview("AR Available")
fun PreviewArtworkDetailTitleWithAR() {
val artwork = Artwork(
name = "My Life's Work",
arDigitalAssetURL = URL("https://example.com")
)
ArtAtGVSUTheme {
ArtworkDetailTitleRow(artwork = artwork)
}
}
| 3 |
Kotlin
|
1
| 1 |
ad8ed8ad47bb1be892c1e60a4e232509f2c34a1f
| 3,940 |
art-at-gvsu-android
|
Apache License 2.0
|
app/src/main/java/com/damakable/kotlinnews/screens/feed/NewsfeedView.kt
|
ablake
| 220,690,560 | false | null |
package com.damakable.kotlinnews.screens.feed
import com.damakable.kotlinnews.model.NewsItem
interface NewsfeedView {
fun clear()
fun addItems(newsItems: List<NewsItem>)
fun displayError(error: Exception)
fun isEmpty() : Boolean
}
| 10 |
Kotlin
|
0
| 0 |
160457751a3d24cef3f021a4cea579aedfb21587
| 251 |
kotlin-news-for-android
|
Apache License 2.0
|
src/main/kotlin/com/ocsoftware/UndefinedFactoryException.kt
|
ryanthames
| 118,261,799 | false | null |
package com.ocsoftware
class UndefinedFactoryException(override var message:String): Exception()
| 2 |
Kotlin
|
0
| 0 |
3439797096932ca951d0bd53695878a04b78181e
| 97 |
fabriKator
|
MIT License
|
shardis-web/src/main/kotlin/com/shardis/web/config/WebfluxConfig.kt
|
kucharzyk
| 115,920,163 | false |
{"TypeScript": 40052, "Kotlin": 10795, "Shell": 6541, "Batchfile": 5084, "HTML": 1596, "CSS": 255}
|
package com.shardis.web.config
import com.shardis.web.handlers.WebFluxErrorWebExceptionHandler
import org.springframework.beans.factory.ObjectProvider
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.web.ResourceProperties
import org.springframework.boot.autoconfigure.web.ServerProperties
import org.springframework.boot.web.reactive.error.ErrorAttributes
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler
import org.springframework.context.ApplicationContext
import org.springframework.context.MessageSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.annotation.Order
import org.springframework.core.io.Resource
import org.springframework.http.codec.ServerCodecConfigurer
import org.springframework.web.reactive.result.view.ViewResolver
@Configuration
class WebfluxConfig(@Value("classpath:/static/index.html") private val indexHtml: Resource) {
@Bean
@Primary
@Order(-1)
fun errorWebExceptionHandler(errorAttributes: ErrorAttributes, messageSource: MessageSource, serverProperties: ServerProperties,
applicationContext: ApplicationContext,
resourceProperties: ResourceProperties,
viewResolversProvider: ObjectProvider<List<ViewResolver>>,
serverCodecConfigurer: ServerCodecConfigurer): ErrorWebExceptionHandler {
val exceptionHandler = WebFluxErrorWebExceptionHandler(
errorAttributes,
resourceProperties,
serverProperties.error,
applicationContext,
indexHtml
)
exceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable { emptyList() })
exceptionHandler.setMessageWriters(serverCodecConfigurer.writers)
exceptionHandler.setMessageReaders(serverCodecConfigurer.readers)
return exceptionHandler
}
}
| 0 |
TypeScript
|
0
| 2 |
9c2ba054b5b78559c546f9386e813ec0d8659c12
| 2,112 |
react-with-cra
|
MIT License
|
geshikt/src/main/kotlin/io/github/sikrinick/geshikt/dsl/component/modifiers/ConditionalFormat.kt
|
sikrinick
| 602,118,796 | false |
{"Kotlin": 146585}
|
package io.github.sikrinick.geshikt.dsl.component.modifiers
import io.github.sikrinick.geshikt.dsl.component.style.Color
import io.github.sikrinick.geshikt.dsl.types.Criterion
import io.github.sikrinick.geshikt.dsl.types.Expression
import io.github.sikrinick.geshikt.dsl.types.Type
// TODO. Refactor, make more readable
class ConditionalFormatting(
val conditionalFormats: List<Pair<Type.Criterion, ConditionalFormat.ResultingFormat>>,
root: Modifier?
) : Modifier(root)
fun Modifier.Companion.formatBy(vararg conditions: ConditionalFormat) =
ConditionalFormatting(conditions.map { Expression().let(it.criterion) to it.format }, null)
fun Modifier.formatBy(vararg conditions: ConditionalFormat) =
ConditionalFormatting(conditions.map { Expression().let(it.criterion) to it.format }, this)
data class ConditionalFormat(
val criterion: Criterion,
val format: ResultingFormat
) {
data class ResultingFormat(
val bold: Boolean? = null,
val strikethrough: Boolean? = null,
val underline: Boolean? = null,
val italic: Boolean? = null,
val textColor: Color? = null,
val backgroundColor: Color? = null
)
}
| 0 |
Kotlin
|
0
| 1 |
4b848844efca405a9db599cd956447ccaac09756
| 1,180 |
geshikt
|
Apache License 2.0
|
library/src/main/java/com/pluscubed/recyclerfastscroll/RecyclerFastScrollerUtils.kt
|
jahirfiquitiva
| 101,790,334 | true |
{"Kotlin": 17510}
|
package com.pluscubed.recyclerfastscroll
import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
@Suppress("DEPRECATION")
internal fun View.setViewBackground(background: Drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(background)
} else {
setBackgroundDrawable(background)
}
}
internal val Context.isRTL: Boolean
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL
} else {
false
}
@ColorInt
internal fun Context.resolveColor(@AttrRes color: Int): Int {
val a = obtainStyledAttributes(intArrayOf(color))
val resId = a.getColor(0, 0)
a.recycle()
return resId
}
internal inline val Float.dpToPx: Float
get() = this * Resources.getSystem().displayMetrics.density
internal inline val Int.dpToPx: Int
get() = toFloat().dpToPx.toInt()
| 1 |
Kotlin
|
1
| 6 |
355558fb0c8782d9ff79f8145a2aaf58a049e873
| 1,121 |
recycler-fast-scroll
|
Apache License 2.0
|
src/main/kotlin/net/casualuhc/arcade/events/player/PlayerTickEvent.kt
|
CasualUHC
| 621,955,934 | false | null |
package net.casualuhc.arcade.events.player
import net.minecraft.server.level.ServerPlayer
data class PlayerTickEvent(
override val player: ServerPlayer
): PlayerEvent
| 0 |
Kotlin
|
0
| 0 |
7b2e8aeb4f067434fa03d1814822fdca4ef3949b
| 172 |
Arcade
|
MIT License
|
app/src/main/java/com/fanrong/frwallet/ui/msgcenter/MsgDetailActivity.kt
|
iamprivatewallet
| 464,003,911 | false |
{"JavaScript": 2822760, "Kotlin": 1140535, "Java": 953177, "HTML": 17003}
|
package com.fanrong.frwallet.ui.msgcenter
import com.basiclib.base.BaseActivity
import com.fanrong.frwallet.R
import com.fanrong.frwallet.dao.FrConstants
import com.fanrong.frwallet.dao.database.CenterDataManager
import com.fanrong.frwallet.found.extInitCommonBgAutoBack
import com.fanrong.frwallet.tools.OpenLockAppDialogUtils
import com.fanrong.frwallet.ui.dialog.LockAppDialog
import com.fanrong.frwallet.wallet.eth.eth.QueryTransactionPageResp
import kotlinx.android.synthetic.main.activity_msg_detail.*
class MsgDetailActivity : BaseActivity() {
var _id:String = ""
override fun getLayoutId(): Int {
return R.layout.activity_msg_detail
}
override fun initView() {
var msgBeanModel = intent.getSerializableExtra(FrConstants.MSG_INFO) as? QueryTransactionPageResp.transactionItem
_id = msgBeanModel?.id.toString()
md_title.apply {
extInitCommonBgAutoBack(this@MsgDetailActivity,"详情")
}
tv_msg_title.text = msgBeanModel?.title
tv_msg_time.text = msgBeanModel?.createTime
tv_msg_body.text = msgBeanModel?.context
}
override fun loadData() {
CenterDataManager.getSystemMsgDetail(_id){
tv_msg_name.text = it?.data?.author
}
}
override fun onResume() {
super.onResume()
OpenLockAppDialogUtils.OpenDialog(this)
}
}
| 0 |
JavaScript
|
0
| 1 |
be8003e419afbe0429f2eb3fd757866e2e4b9152
| 1,373 |
PrivateWallet.Android
|
MIT License
|
xof-app/src/main/kotlin/com/github/danzx/xof/app/configuration/Profiles.kt
|
dan-zx
| 220,341,123 | false | null |
package com.github.danzx.xof.app.configuration
object Profiles {
const val LOCAL = "local"
const val HEROKU = "heroku"
const val DEFAULT = LOCAL
}
| 0 |
Kotlin
|
0
| 5 |
379eebd63fde5c645f822fb6d816f82d58d44b83
| 159 |
xof-api
|
Apache License 2.0
|
third-party/codelab-android-compose/NavigationCodelab/app/src/androidTest/java/com/example/compose/rally/NavigationTest.kt
|
vanyarachell
| 738,524,743 | false | null |
package com.example.compose.rally
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.testing.TestNavHostController
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class NavigationTest {
@get:Rule
val composeTestRule = createComposeRule()
private lateinit var navController: TestNavHostController
@Before
fun rallyNavHost() {
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
RallyNavHost(navController = navController)
}
}
@Test
fun rallyNavHost_verifyOverviewStartDestination() {
composeTestRule
.onNodeWithContentDescription("Overview Screen")
.assertIsDisplayed()
}
@Test
fun rallyNavHost_clickAllAccount_navigatesToAccounts() {
composeTestRule
.onNodeWithContentDescription("All Accounts")
.performClick()
composeTestRule
.onNodeWithContentDescription("Accounts Screen")
.assertIsDisplayed()
}
@Test
fun rallyNaVHost_clickAllBills_navigateToBills() {
composeTestRule
.onNodeWithContentDescription("All Bills")
.performScrollTo()
.performClick()
val route = navController.currentBackStackEntry?.destination?.route
assertEquals(route, "bills")
}
}
| 0 |
Kotlin
|
0
| 0 |
82cac4d64c5ce24d8c70531a69f3f8959814809f
| 1,824 |
kotlin-android-samples
|
MIT License
|
src/org/elixir_lang/debugger/node/Binding.kt
|
KronicDeth
| 22,329,177 | false |
{"Kotlin": 2461440, "Elixir": 2165417, "Java": 1582388, "Euphoria": 151683, "Lex": 69822, "HTML": 22466, "Makefile": 499}
|
package org.elixir_lang.debugger.node
import com.ericsson.otp.erlang.OtpErlangAtom
import com.ericsson.otp.erlang.OtpErlangObject
import com.ericsson.otp.erlang.OtpErlangTuple
import com.intellij.openapi.diagnostic.Logger
import org.elixir_lang.beam.term.inspect
data class Binding(val erlangName: String, val value: OtpErlangObject) : Comparable<Binding> {
val elixirName: String? by lazy {
elixirNameMatchResult?.let { matchResult ->
matchResult.groupValues[1]
}
}
val index: Int? by lazy {
elixirNameMatchResult?.let { matchResult ->
matchResult.groupValues[2].toInt()
}
}
override fun compareTo(other: Binding): Int {
val thisElixirName = this.elixirName
val otherElixirName = other.elixirName
return if (thisElixirName != null && otherElixirName != null) {
val elixirNameCompared = thisElixirName.compareTo(otherElixirName)
if (elixirNameCompared == 0) {
index!!.compareTo(other.index!!)
} else {
elixirNameCompared
}
} else {
erlangName.compareTo(other.erlangName)
}
}
private val elixirNameMatchResult by lazy {
elixirNameRegex.matchEntire(erlangName)
}
companion object {
// 1.6: V<name>@<binding>
// 1.7: _<name>@<binding>
private val elixirNameRegex = Regex("(?:V|_)(.+)@(\\d+)")
private const val ARITY = 2
private val LOGGER = Logger.getInstance(Binding::class.java)
fun from(term: OtpErlangObject): Binding? =
when (term) {
is OtpErlangTuple -> from(term)
else -> {
LOGGER.error("Binding ${inspect(term)} is not an OtpErlangTuple")
null
}
}
private fun from(tuple: OtpErlangTuple): Binding? {
val arity = tuple.arity()
return if (arity == ARITY) {
name(tuple)?.let { name ->
val value = tuple.elementAt(1)
Binding(name, value)
}
} else {
LOGGER.error("Binding (${inspect(tuple)}) arity ($arity) is not $ARITY")
null
}
}
private fun name(tuple: OtpErlangTuple): String? {
val name = tuple.elementAt(0)
return when (name) {
is OtpErlangAtom -> name.atomValue()
else -> {
LOGGER.error("name (${inspect(name)}) is not an OtpErlangAtom")
null
}
}
}
}
}
| 590 |
Kotlin
|
153
| 1,815 |
b698fdaec0ead565023bf4461d48734de135b604
| 2,712 |
intellij-elixir
|
Apache License 2.0
|
app/src/main/java/be/hogent/faith/faith/util/factory/SubGoalFactory.kt
|
hydrolythe
| 353,694,404 | false | null |
package be.hogent.faith.faith.util.factory
import be.hogent.faith.faith.models.goals.SubGoal
object SubGoalFactory {
fun makeSubGoal(numberOfActions: Int = 5): SubGoal {
val subgoal = SubGoal(
description = DataFactory.randomString()
)
repeat(numberOfActions) {
subgoal.addAction(ActionFactory.makeAction())
}
return subgoal
}
}
| 0 |
Kotlin
|
0
| 0 |
14c6aec4b3c0a42bc73a7f779964d166fffeea20
| 404 |
FAITHAndroid
|
The Unlicense
|
clara-app/src/main/kotlin/de/unistuttgart/iste/sqa/clara/aggregation/platform/kubernetes/aggregators/opentelemetry/model/Service.kt
|
SteveBinary
| 724,727,375 | false |
{"Kotlin": 149376, "Dockerfile": 180}
|
package de.unistuttgart.iste.sqa.clara.aggregation.platform.kubernetes.aggregators.opentelemetry.model
import de.unistuttgart.iste.sqa.clara.api.model.Endpoint
import de.unistuttgart.iste.sqa.clara.api.model.IpAddress
data class Service(
val name: Name?,
val hostName: HostName?,
val ipAddress: IpAddress?,
val port: Port?,
val hostIdentifier: HostIdentifier?,
val endpoints: List<Endpoint>,
) {
@JvmInline
value class Name(val value: String)
@JvmInline
value class HostName(val value: String)
@JvmInline
value class Port(val value: Int) : Comparable<Int> by value
@JvmInline
value class Endpoint(val value: String)
// Combination from hostname and port, used to create keys for maps and differentiate different applications on the same host.
@JvmInline
value class HostIdentifier(val value: String)
fun mergeWithOtherServiceObject(other: Service): Service {
val mergedName = mergeProperty(name, other.name, "name")
val mergedHostName = mergeProperty(hostName, other.hostName, "hostName")
val mergedIpAddress = mergeProperty(ipAddress, other.ipAddress, "ipAddress")
val mergedPort = mergeProperty(port, other.port, "port")
val mergedHostIdentifier = mergeProperty(hostIdentifier, other.hostIdentifier, "hostIdentifier")
val mergedEndpoints = mergeEndpoints(endpoints, other.endpoints)
return Service(
name = mergedName,
hostName = mergedHostName,
ipAddress = mergedIpAddress,
port = mergedPort,
endpoints = mergedEndpoints,
hostIdentifier = mergedHostIdentifier,
)
}
private fun <Property> mergeProperty(value1: Property?, value2: Property?, propertyName: String): Property? {
return when {
value1 != null && value2 != null -> {
if (value1 == value2) {
value1
} else {
println("Clash in $propertyName. Choosing: $value1")
value1
}
}
value1 != null -> value1
value2 != null -> value2
else -> null
}
}
private fun mergeEndpoints(endpoints1: List<Endpoint>, endpoints2: List<Endpoint>): List<Endpoint> {
val mergedEndpoints = mutableListOf<Endpoint>()
mergedEndpoints.addAll(endpoints1)
mergedEndpoints.addAll(endpoints2.filter { !endpoints1.contains(it) })
return mergedEndpoints
}
}
fun List<Service.Endpoint>.toComponentEndpoints(): List<Endpoint> = this.map { Endpoint(it.value) }
| 0 |
Kotlin
|
0
| 0 |
6f85ed251d7e1e906e10f090981eb7ff3feadd9c
| 2,641 |
clara
|
MIT License
|
app/src/main/java/eu/wawrzyczek/findflights/flights/FlightsActivity.kt
|
kamilwawrzyczek
| 155,056,287 | false | null |
package eu.wawrzyczek.findflights.flights
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import eu.wawrzyczek.findflights.R
import eu.wawrzyczek.findflights.common.SimpleDateTime
import eu.wawrzyczek.findflights.common.plusAssign
import eu.wawrzyczek.findflights.databinding.ActivityFlightsBinding
import eu.wawrzyczek.findflights.flights.model.Flight
import eu.wawrzyczek.findflights.search.model.SearchData
import eu.wawrzyczek.findflights.search.model.Station
import io.reactivex.disposables.CompositeDisposable
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import java.util.*
private const val SEARCH_DATA = "search_data"
fun startActivity(context: Context, searchData: SearchData) {
context.startActivity(Intent(context, FlightsActivity::class.java).apply {
putExtra(SEARCH_DATA, searchData)
})
}
class FlightsActivity : AppCompatActivity() {
private val flightsViewModel by viewModel<FlightsViewModel> {
parametersOf(intent.getParcelableExtra<SearchData>(SEARCH_DATA))
}
private val flightsAdapter by lazy { FlightsAdapter { flightsViewModel.flightClick(it) } }
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityFlightsBinding>(this, R.layout.activity_flights)
binding.vm = flightsViewModel
binding.tryAgain.setOnClickListener { flightsViewModel.loadFlights() }
prepareRecyclerView(binding)
val data = flightsViewModel.searchData
title = data.origin.name + " > " + data.destination.name
}
override fun onStart() {
super.onStart()
flightsViewModel.loadFlights()
disposables += flightsViewModel.flights.subscribe {
flightsAdapter.updateItems(it)
}
}
override fun onStop() {
super.onStop()
disposables.clear()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
private fun prepareRecyclerView(binding: ActivityFlightsBinding) {
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = flightsAdapter
binding.recyclerView.itemAnimator = DefaultItemAnimator()
}
}
| 1 |
Kotlin
|
0
| 0 |
d45878d151cda37bc5b35550e764448ebf8d18de
| 2,767 |
find-flights
|
Apache License 2.0
|
shared/feature/geminio-sdk/src/main/kotlin/ru/hh/plugins/geminio/sdk/recipe/parsers/expressions/RecipeExpressionParser.kt
|
hhru
| 159,637,875 | false | null |
package ru.hh.plugins.geminio.sdk.recipe.parsers.expressions
import ru.hh.plugins.geminio.sdk.recipe.models.expressions.RecipeExpression
import ru.hh.plugins.geminio.sdk.recipe.models.expressions.RecipeExpressionCommand
import ru.hh.plugins.geminio.sdk.recipe.models.expressions.RecipeExpressionModifier
import ru.hh.plugins.geminio.sdk.recipe.parsers.ParsersErrorsFactory.sectionUnknownEnumKeyErrorMessage
private const val SRC_OUT_FOLDER_NAME = "srcOut"
private const val RES_OUT_FOLDER_NAME = "resOut"
private const val MANIFEST_OUT_FOLDER_NAME = "manifestOut"
private const val ROOT_OUT_FOLDER_NAME = "rootOut"
private const val FIXED_TRUE_VALUE = "true"
private const val FIXED_FALSE_VALUE = "false"
private const val CHAR_DYNAMIC_COMMAND_START = '$'
private const val CHAR_DYNAMIC_COMMAND_END = '}'
private const val CHAR_DYNAMIC_COMMAND_SKIP = '{'
private const val CHAR_COMMAND_MODIFIER_START = '.'
private const val CHAR_COMMAND_MODIFIER_END = '('
private const val CHAR_COMMAND_MODIFIER_SKIP = ')'
/**
* Parser from recipe's expressions declarations into objects.
*/
internal fun String.toRecipeExpression(sectionName: String): RecipeExpression {
val commands = mutableListOf<RecipeExpressionCommand>()
var fixed = ""
var parameterId = ""
var modifiers = mutableListOf<RecipeExpressionModifier>()
var modifierName = ""
var startDynamic = false
var startModifier = false
for (char in this) {
when (char) {
CHAR_DYNAMIC_COMMAND_START -> {
if (fixed.isNotEmpty()) {
commands += RecipeExpressionCommand.Fixed(fixed)
}
fixed = ""
startDynamic = true
}
CHAR_COMMAND_MODIFIER_START -> {
if (startDynamic) {
startModifier = true
} else {
fixed += char
}
}
CHAR_COMMAND_MODIFIER_END -> {
RecipeExpressionModifier.fromYamlKey(modifierName)
?.let { modifiers.add(it) }
?: throw IllegalArgumentException(
sectionUnknownEnumKeyErrorMessage(
sectionName = sectionName,
key = modifierName,
acceptableValues = RecipeExpressionModifier.availableYamlKeys()
)
)
modifierName = ""
startModifier = false
}
CHAR_DYNAMIC_COMMAND_END -> {
startDynamic = false
commands += when (parameterId) {
SRC_OUT_FOLDER_NAME -> {
RecipeExpressionCommand.SrcOut
}
RES_OUT_FOLDER_NAME -> {
RecipeExpressionCommand.ResOut
}
MANIFEST_OUT_FOLDER_NAME -> {
RecipeExpressionCommand.ManifestOut
}
ROOT_OUT_FOLDER_NAME -> {
RecipeExpressionCommand.RootOut
}
else -> {
RecipeExpressionCommand.Dynamic(
parameterId = parameterId,
modifiers = modifiers.toList()
)
}
}
parameterId = ""
modifiers = mutableListOf()
}
CHAR_COMMAND_MODIFIER_SKIP, CHAR_DYNAMIC_COMMAND_SKIP -> {
// do nothing by default
}
else -> {
when {
startModifier -> {
modifierName += char
}
startDynamic -> {
parameterId += char
}
else -> {
fixed += char
}
}
}
}
}
if (fixed.isNotEmpty()) {
commands += when {
fixed == FIXED_TRUE_VALUE && commands.isEmpty() -> RecipeExpressionCommand.ReturnTrue
fixed == FIXED_FALSE_VALUE && commands.isEmpty() -> RecipeExpressionCommand.ReturnFalse
else -> RecipeExpressionCommand.Fixed(fixed)
}
}
return RecipeExpression(commands)
}
| 17 | null |
18
| 97 |
2d6c02fc814eff3934c17de77ef7ade91d3116f5
| 4,415 |
android-multimodule-plugin
|
MIT License
|
src/main/kotlin/dev/alexandrevieira/alurachallengebackend/model/converters/YearMonthDateAttributeConverter.kt
|
vieira-alexandre
| 451,146,518 | false |
{"Kotlin": 78362}
|
package dev.alexandrevieira.alurachallengebackend.model.converters
import java.sql.Date
import java.time.Instant
import java.time.LocalDate
import java.time.YearMonth
import java.time.ZoneId
import javax.persistence.AttributeConverter
class YearMonthDateAttributeConverter : AttributeConverter<YearMonth, Date> {
override fun convertToDatabaseColumn(attribute: YearMonth?): Date {
val localDate = LocalDate.of(attribute!!.year, attribute.month, 1)
return Date.valueOf(localDate)
}
override fun convertToEntityAttribute(dbData: Date?): YearMonth {
val instant = Instant.ofEpochMilli(dbData!!.time)
val localDate = LocalDate.ofInstant(instant, ZoneId.systemDefault())
return YearMonth.of(localDate.year, localDate.month)
}
}
| 1 |
Kotlin
|
0
| 0 |
75308e893488830d53cd0ed6c69bf2f1d58375d6
| 783 |
alura-challenge-backend
|
MIT License
|
src/main/java/datastructures/CArrayList.kt
|
cbisaillon
| 214,531,371 | false | null |
package clem.datastructures
import java.lang.IndexOutOfBoundsException
import java.lang.StringBuilder
/**
* Represents an ArrayList data structure
* @Author: Clement Bisaillon
* @Date: 2019-10-12
*/
class CArrayList<T>(){
private var array = arrayOfNulls<Any?>(1)
private var currentIndex = 0
//Returns the size of the array (excluding empty items)
val size: Int
get() = currentIndex
/**
* Add an element to the array. If the array is full, double
* its size.
* @param element the element of add
*/
fun add(element: T){
if(currentIndex >= array.size){
this.doubleSize()
}
array[currentIndex] = element
currentIndex++
}
/**
* Get the element at the specified index
* @param index the index to get the item from
* @return the item retrieved at index
*/
@Suppress("UNCHECKED_CAST")
fun get(index: Int): T{
if(index > currentIndex - 1){
throw IndexOutOfBoundsException()
}
return array[index] as T
}
/**
* Removes the element at a certain index
* @param index the index to remove from the array
* @return the item removed
*/
@Suppress("UNCHECKED_CAST")
fun remove(index: Int): T{
if(index > currentIndex - 1){
throw IndexOutOfBoundsException()
}
val newArray = arrayOfNulls<Any?>(array.size - 1)
val deletedItem = array[index]
var pointer = 0
//Copy each element except for index to delete
for(i in 0 until newArray.size){
if(i == index) {
pointer++
}
newArray[i] = array[pointer]
pointer++
}
currentIndex--
array = newArray
return deletedItem as T
}
/**
* Search the array for an item and removes it
* @param item the item to remove
*/
fun removeItem(item: T){
val newArray = arrayOfNulls<Any?>(array.size - 1)
var pointer = 0
for(i in 0 until newArray.size){
if(array[i]?.equals(item) == true){
pointer++
}
newArray[i] = array[pointer]
pointer++
}
currentIndex--
array = newArray
}
/**
* Clears the array
*/
fun clear(){
array = arrayOfNulls<Any?>(1)
currentIndex = 0
}
/**
* Doubles the size of the array by recreating a new
* one and copying all the elements
*/
private fun doubleSize(){
//Double the array size
val backup = array
array = arrayOfNulls<Any?>(array.size * 2)
//copy each elements
for(i in 0 until backup.size){
array[i] = backup[i]
}
}
/**
* Displays the array in a readable way
* @return the string representation of the arraylist
*/
override fun toString(): String{
val valueBuilder = StringBuilder("[")
for(i in 0 until currentIndex){
valueBuilder.append("${array[i]}")
if(i < currentIndex - 1){
valueBuilder.append(", ")
}
}
valueBuilder.append("]")
return valueBuilder.toString()
}
}
| 0 |
Kotlin
|
0
| 0 |
3660d1a5f328bd3be20b54c9f13544d9b04fccb0
| 3,285 |
interview_prep
|
MIT License
|
app/src/main/java/com/skyd/imomoe/view/adapter/SearchHistoryAdapter.kt
|
Eillot
| 349,335,156 | true |
{"Kotlin": 428256, "Java": 86537}
|
package com.skyd.imomoe.view.adapter
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.skyd.imomoe.App
import com.skyd.imomoe.R
import com.skyd.imomoe.bean.SearchHistoryBean
import com.skyd.imomoe.util.SearchHistory1ViewHolder
import com.skyd.imomoe.util.SearchHistoryHeader1ViewHolder
import com.skyd.imomoe.util.Util.showToast
import com.skyd.imomoe.util.ViewHolderUtil.Companion.getItemViewType
import com.skyd.imomoe.util.ViewHolderUtil.Companion.getViewHolder
import com.skyd.imomoe.view.activity.SearchActivity
class SearchHistoryAdapter(
val activity: SearchActivity,
private val dataList: List<SearchHistoryBean>
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun getItemViewType(position: Int): Int = getItemViewType(dataList[position])
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder =
getViewHolder(parent, viewType)
override fun getItemCount(): Int = dataList.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = dataList[position]
when (holder) {
is SearchHistoryHeader1ViewHolder -> {
holder.tvSearchHistoryHeader1Title.text = item.title
}
is SearchHistory1ViewHolder -> {
holder.tvSearchHistory1Title.text = item.title
holder.ivSearchHistory1Delete.setOnClickListener {
activity.deleteSearchHistory(position)
}
holder.itemView.setOnClickListener {
activity.search(item.title)
}
}
else -> {
holder.itemView.visibility = View.GONE
(App.context.resources.getString(R.string.unknown_view_holder) + position).showToast()
}
}
}
}
| 0 | null |
0
| 0 |
4c5a24a3e047202bcb679b1af439dad65579df46
| 1,938 |
Imomoe
|
Apache License 2.0
|
app/src/main/java/com/solarexsoft/mpandroidchartdemo/utils/MealsXAxisValueFormatter.kt
|
flyfire
| 196,355,714 | false | null |
package com.solarexsoft.mpandroidchartdemo.utils
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.formatter.ValueFormatter
import com.solarexsoft.mpandroidchartdemo.App
import com.solarexsoft.mpandroidchartdemo.R
import kotlin.math.roundToInt
/**
* <pre>
* Author: houruhou
* CreatAt: 17:00/2019-07-11
* Desc:
* </pre>
*/
class MealsXAxisValueFormatter : ValueFormatter() {
var mMeals: Array<String> = App.getApplication().resources.getStringArray(R.array.meals);
override fun getFormattedValue(value: Float, axis: AxisBase?): String {
val index = value.roundToInt();
if (index >= 0 && index < mMeals.size) {
return mMeals[index]
}
return ""
}
}
| 1 | null |
1
| 1 |
c67baf6f79809e9563789f425e7a72a61fb1ff61
| 763 |
MPAndroidChartDemo
|
MIT License
|
app/src/main/java/com/example/returnpals/composetools/ButtonManager.kt
|
BC-CS481-Capstone
| 719,299,432 | false |
{"Kotlin": 271938, "Java": 64676}
|
package com.example.returnpals.composetools
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import java.time.LocalDate
/**
* This is the button manager class. Use this class to call buttons.
*/
object ButtonManager {
@Deprecated(
message = "A better alternative exists",
replaceWith = ReplaceWith("Button", "androidx.compose.material3.Button"),
level = DeprecationLevel.WARNING)
@Composable
fun Button(
modifier: Modifier = Modifier,
onClick: () -> Unit,
enabled: Boolean = true,
color: Color = Color(0, 138, 230),
border: BorderStroke? = null,
shape: Shape = RoundedCornerShape(22.dp, 22.dp, 22.dp, 22.dp),
contentAlignment: Alignment = Alignment.Center,
content: @Composable() (BoxScope.() -> Unit)
) {
var modifier = modifier
.clickable(enabled = true, onClick = onClick)
.background(
color = color,
shape = shape
)
if (border != null) {
modifier = modifier
.border(
border = border,
shape = shape
)
}
Box(
modifier = modifier,
contentAlignment = contentAlignment,
content = content
)
}
@Composable
fun NextButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
text: String = "Next",
enabled: Boolean = true,
) {
androidx.compose.material3.Button(
modifier = modifier,
onClick = onClick,
enabled = enabled,
) {
Text(
text = text
)
}
}
@Composable
fun BackButton(
modifier: Modifier = Modifier,
onClick: () -> Unit,
text: String = "Back",
enabled: Boolean = true,
) {
OutlinedButton(
modifier = modifier,
onClick = onClick,
enabled = enabled,
) {
Text(
text = text
)
}
}
@Composable
fun WheelSelector(
selectedText: String,
previousText: String,
nextText: String,
onClickPrevious: () -> Unit,
onClickNext: () -> Unit,
modifier: Modifier = Modifier,
onClickSelected: () -> Unit = {},
horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
) {
Column(
modifier = modifier,
horizontalAlignment = horizontalAlignment,
verticalArrangement = Arrangement.Center
) {
OutlinedButton(
text = previousText,
onClick = onClickPrevious,
textColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.75f),
border = null
)
OutlinedButton(
text = selectedText,
onClick = onClickSelected,
fontWeight= FontWeight.Bold,
)
OutlinedButton(
text = nextText,
onClick = onClickNext,
textColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.75f),
border = null
)
}
}
@Composable
fun OutlinedButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
textColor: Color = MaterialTheme.colorScheme.primary,
fontWeight: FontWeight = FontWeight.Normal,
border: BorderStroke? = BorderStroke(
width = 1.dp,
color = MaterialTheme.colorScheme.primary,
),
shape: Shape = RectangleShape,
) {
OutlinedButton(
modifier = modifier,
onClick = onClick,
border = border,
shape = shape,
) {
Text(
text = text,
fontWeight = fontWeight,
color = textColor
)
}
}
@SuppressLint("NewApi")
@Composable
fun DateSelector(
modifier: Modifier = Modifier,
date: LocalDate,
onChangeDate: (LocalDate) -> Unit,
verticalAlignment: Alignment.Vertical = Alignment.Top,
horizontalArrangement: Arrangement.Horizontal = Arrangement.Center,
) {
Row(
modifier = modifier,
verticalAlignment = verticalAlignment,
horizontalArrangement = horizontalArrangement,
) {
WheelSelector(
onClickPrevious = { onChangeDate(date.minusMonths(1)) },
onClickNext = { onChangeDate(date.plusMonths(1)) },
previousText = date.minusMonths(1).month.toString(),
selectedText = date.month.toString(),
nextText = date.plusMonths(1).month.toString(),
horizontalAlignment = Alignment.End
)
Spacer(Modifier.width(5.dp))
WheelSelector(
onClickPrevious = { onChangeDate(date.minusDays(1)) },
onClickNext = { onChangeDate(date.plusDays(1)) },
previousText = date.minusDays(1).dayOfMonth.toString(),
selectedText = date.dayOfMonth.toString(),
nextText = date.plusDays(1).dayOfMonth.toString(),
)
Spacer(Modifier.width(5.dp))
WheelSelector(
onClickPrevious = { onChangeDate(date.minusYears(1)) },
onClickNext = { onChangeDate(date.plusYears(1)) },
previousText = date.minusYears(1).year.toString(),
selectedText = date.year.toString(),
nextText = date.plusYears(1).year.toString(),
horizontalAlignment = Alignment.Start
)
}
}
}
| 28 |
Kotlin
|
0
| 0 |
e857f854874211d11784260b4e2a19ffb7db8e13
| 6,886 |
ReturnPalsApp
|
MIT License
|
modules/feature/app/settings/api/src/main/kotlin/kekmech/ru/feature_app_settings_api/domain/model/AppTheme.kt
|
tonykolomeytsev
| 203,239,594 | false |
{"Kotlin": 972736, "JavaScript": 9100, "Python": 2365, "Shell": 46}
|
package kekmech.ru.feature_app_settings_api.domain.model
enum class AppTheme {
Light,
Dark,
System,
}
| 19 |
Kotlin
|
4
| 41 |
15c3c17e33d0ffffc0e269ad0cd6fe47b0bc971a
| 115 |
mpeiapp
|
MIT License
|
base/src/main/java/com/devdd/recipe/base/utils/AppCoroutineDispatchers.kt
|
deepakdawade
| 354,909,155 | false | null |
package com.devdd.recipe.base.utils
import kotlinx.coroutines.CoroutineDispatcher
data class AppCoroutineDispatchers(
val io: CoroutineDispatcher,
val computation: CoroutineDispatcher,
val main: CoroutineDispatcher
)
| 0 |
Kotlin
|
0
| 6 |
8272959b3b692bd4ee797e15e76d57282efa7ad4
| 243 |
Recipe-Finder
|
Apache License 2.0
|
game-api/src/main/java/org/runestar/client/game/api/Model.kt
|
ehsan16
| 246,016,204 | true |
{"Kotlin": 1368739, "Java": 984619}
|
package org.runestar.client.game.api
import org.runestar.client.game.api.live.Viewport
import org.runestar.client.game.api.utils.Jarvis
import org.runestar.client.game.api.utils.addNotNull
import org.runestar.client.game.raw.access.XModel
import org.runestar.client.game.raw.CLIENT
import java.awt.Color
import java.awt.Point
import java.awt.Rectangle
import java.awt.Shape
import java.awt.geom.Area
import kotlin.math.max
import kotlin.math.min
class Model internal constructor(
val accessor: XModel,
val base: Position,
val yaw: Angle
) {
private val localXMin get() = base.localX + accessor.xMid - accessor.xMidOffset
private val localXMax get() = base.localX + accessor.xMid + accessor.xMidOffset
private val localYMin get() = base.localY + accessor.zMid - accessor.zMidOffset
private val localYMax get() = base.localY + accessor.zMid + accessor.zMidOffset
private val heightMin get() = base.height - (accessor.yMid + accessor.yMidOffset)
private val heightMax get() = base.height - (accessor.yMid - accessor.yMidOffset)
private fun boundingBoxCornerPoints(projection: Projection = Viewport): List<Point> {
accessor.calculateBoundingBox(yaw.value) // todo
val list = ArrayList<Point>(8)
val xMin = localXMin
val xMax = localXMax
val yMin = localYMin
val yMax = localYMax
val hMin = heightMin
val hMax = heightMax
list.addNotNull(projection.toScreen(xMin, yMin, hMin, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMin, yMax, hMin, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMax, yMax, hMin, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMax, yMin, hMin, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMin, yMin, hMax, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMin, yMax, hMax, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMax, yMax, hMax, base.plane, base.localX, base.localY))
list.addNotNull(projection.toScreen(xMax, yMin, hMax, base.plane, base.localX, base.localY))
return list
}
fun boundingBox(projection: Projection = Viewport): Shape {
return Jarvis.convexHull(boundingBoxCornerPoints(projection))
}
fun objectClickBox(projection: Projection = Viewport): Area {
return Area(boundingBox(projection)).apply { intersect(geometryArea(projection)) }
}
fun geometryArea(projection: Projection = Viewport): Area {
val area = Area()
val tempRectangle = Rectangle()
trianglesForEach(projection) { x0, y0, x1, y1, x2, y2 ->
val xMin = min(x0, min(x1, x2)) - 4 // pad all sides by 4
val yMin = min(y0, min(y1, y2)) - 4
val xMax = max(x0, max(x1, x2)) + 4
val yMax = max(y0, max(y1, y2)) + 4
val w = xMax - xMin
val h = yMax - yMin
if (!area.contains(xMin.toDouble(), yMin.toDouble(), w.toDouble(), h.toDouble())) {
tempRectangle.setBounds(xMin, yMin, w, h)
area.add(Area(tempRectangle))
}
}
return area
}
fun drawWireFrame(
color: Color,
projection: Projection = Viewport
) {
val rgb = color.rgb
trianglesForEach(projection) { x0, y0, x1, y1, x2, y2 ->
CLIENT.Rasterizer2D_drawLine(x0, y0, x1, y1, rgb)
CLIENT.Rasterizer2D_drawLine(x0, y0, x2, y2, rgb)
CLIENT.Rasterizer2D_drawLine(x2, y2, x1, y1, rgb)
}
}
private inline fun trianglesForEach(
projection: Projection,
consumer: (Int, Int, Int, Int, Int, Int) -> Unit
) {
val tempPoint = Point()
for (i in 0 until accessor.indicesCount) {
if (!vertexToScreen(accessor.indices1[i], projection, tempPoint)) continue
val x0 = tempPoint.x
val y0 = tempPoint.y
if (!vertexToScreen(accessor.indices2[i], projection, tempPoint)) continue
val x1 = tempPoint.x
val y1 = tempPoint.y
if (!vertexToScreen(accessor.indices3[i], projection, tempPoint)) continue
val x2 = tempPoint.x
val y2 = tempPoint.y
consumer(x0, y0, x1, y1, x2, y2)
}
}
private fun vertexToScreen(i: Int, projection: Projection, result: Point): Boolean {
val vx = accessor.verticesX[i]
val vy = accessor.verticesY[i]
val vz = accessor.verticesZ[i]
val x = (vx * yaw.cosInternal + vz * yaw.sinInternal) shr 16
val y = (vz * yaw.cosInternal - vx * yaw.sinInternal) shr 16
val h = -1 * vy
val localX = base.localX + x
val localY = base.localY + y
val height = base.height + h
return projection.toScreen(localX, localY, height, base.plane, base.localX, base.localY, result)
}
}
| 0 |
Kotlin
|
0
| 0 |
d02e7a382a34af117279be02f9f54a6a70fc012b
| 5,051 |
client
|
MIT License
|
lightspark-sdk/src/commonMain/kotlin/com/lightspark/sdk/graphql/LightningFeeEstimateForNode.kt
|
lightsparkdev
| 590,703,408 | false |
{"Kotlin": 1660352, "Java": 34937, "Dockerfile": 1719, "Shell": 490}
|
package com.lightspark.sdk.graphql
import com.lightspark.sdk.model.LightningFeeEstimateOutput
const val LightningFeeEstimateForNodeQuery = """
query LightningFeeEstimateForNode(
${'$'}node_id: ID!
${'$'}destination_node_public_key: String!
${'$'}amount_msats: Long!
) {
lightning_fee_estimate_for_node(input: {
node_id: ${'$'}node_id,
destination_node_public_key: ${'$'}destination_node_public_key,
amount_msats: ${'$'}amount_msats
}) {
...LightningFeeEstimateOutputFragment
}
}
${LightningFeeEstimateOutput.FRAGMENT}
"""
| 0 |
Kotlin
|
1
| 4 |
9a954d479d28fc69a9f4a49aa52af1bd14cdd630
| 579 |
kotlin-sdk
|
Apache License 2.0
|
typescript-kotlin/src/jsMain/kotlin/typescript/LanguageServiceMode.kt
|
karakum-team
| 393,199,102 | false |
{"Kotlin": 6149909}
|
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package typescript
// language=JavaScript
@JsName("""(/*union*/{Semantic: 0, PartialSemantic: 1, Syntactic: 2}/*union*/)""")
sealed external interface LanguageServiceMode {
companion object {
val Semantic: LanguageServiceMode
val PartialSemantic: LanguageServiceMode
val Syntactic: LanguageServiceMode
}
}
| 0 |
Kotlin
|
6
| 26 |
3fcfd2c61da8774151cf121596e656cc123b37db
| 480 |
types-kotlin
|
Apache License 2.0
|
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day07.kt
|
770grappenmaker
| 434,645,245 | false |
{"Kotlin": 403844}
|
package com.grappenmaker.aoc.year21
import com.grappenmaker.aoc.PuzzleSet
import kotlin.math.abs
import kotlin.math.min
fun PuzzleSet.day7() = puzzle(day = 7) {
// Part one
val numbers = input.trim().split(",").map { it.toInt() }.sorted()
val mid = numbers.size / 2
val median = numbers[mid] + if (numbers.size % 2 != 0) numbers[mid - 1] else 0
partOne = numbers.sumOf { abs(it - median) }.s()
// Part two
val mean = numbers.sum() / numbers.size
val fuel = { i: Int -> i * (i + 1) / 2 }
val calcFuel = { meanToUse: Int -> numbers.sumOf { fuel(abs(it - meanToUse)) } }
partTwo = min(calcFuel(mean), calcFuel(mean - 1)).s()
}
| 0 |
Kotlin
|
0
| 7 |
e037dbf7c8d477549a0c81259891337a6f34cb53
| 667 |
advent-of-code
|
The Unlicense
|
sdk/src/main/kotlin/io/github/wulkanowy/sdk/exception/ApiException.kt
|
dominik-korsa
| 237,057,001 | true |
{"Kotlin": 509705, "HTML": 128700, "Shell": 505}
|
package io.github.wulkanowy.sdk.exception
import java.io.IOException
open class ApiException internal constructor(message: String, cause: Throwable? = null) : IOException(message, cause)
| 0 |
Kotlin
|
0
| 0 |
2d2b5176e6b3d5e5eb6b812441c1af740f26eeb5
| 189 |
sdk
|
Apache License 2.0
|
app/src/main/java/com/example/bookloverfinalapp/app/ui/general_screens/screen_all_students/sort_dialog/FragmentUsersSortDialog.kt
|
yusuf0405
| 484,801,816 | false | null |
package com.example.bookloverfinalapp.app.ui.general_screens.screen_all_students.sort_dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import com.example.bookloverfinalapp.app.utils.bindingLifecycleError
import com.example.bookloverfinalapp.app.utils.extensions.tuneBottomDialog
import com.example.bookloverfinalapp.app.utils.extensions.tuneLyricsDialog
import com.example.bookloverfinalapp.databinding.FragmentUserSortDialogBinding
import com.joseph.ui_core.extensions.launchWhenCreated
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class FragmentUsersSortDialog : DialogFragment(), View.OnClickListener {
private var _binding: FragmentUserSortDialogBinding? = null
val binding get() = _binding ?: bindingLifecycleError()
private val viewModel: SortingUsersOptionsViewModel by viewModels()
private var actions: Map<Int, SortingUsersOptionsMenuActions>? = null
override fun onStart() {
super.onStart()
tuneBottomDialog()
tuneLyricsDialog()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentUserSortDialogBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog?.window?.setWindowAnimations(com.joseph.ui_core.R.style.ModalPage_Animation)
setupActions()
setOnClickListeners()
observeData()
}
private fun setupActions() = with(binding) {
actions = mapOf(
sortByUserName.id to SortingUsersOptionsMenuActions.OrderByUserName,
sortByUserLastName.id to SortingUsersOptionsMenuActions.OrderByUserLastName,
sortByMoreBooks.id to SortingUsersOptionsMenuActions.OrderByMoreBooks,
sortByMoreChapters.id to SortingUsersOptionsMenuActions.OrderByMoreChapters,
sortByMorePages.id to SortingUsersOptionsMenuActions.OrderByMorePages,
)
}
private fun observeData() = with(viewModel) {
launchWhenCreated {
internalSelection.observe(::updateSelectionMark)
}
}
override fun onClick(view: View) {
if (actions == null) return
actions!![view.id]?.let(viewModel::orderUsers)
dismiss()
}
private fun setOnClickListeners() = with(binding) {
val listener = this@FragmentUsersSortDialog
sortByUserName.setOnClickListener(listener)
sortByUserLastName.setOnClickListener(listener)
sortByMoreBooks.setOnClickListener(listener)
sortByMoreChapters.setOnClickListener(listener)
sortByMorePages.setOnClickListener(listener)
}
private fun updateSelectionMark(action: SortingUsersOptionsMenuActions) = with(binding) {
userNameConnectedMark.isVisible = action == SortingUsersOptionsMenuActions.OrderByUserName
userLastNameConnectedMark.isVisible = action == SortingUsersOptionsMenuActions.OrderByUserLastName
moreBooksConnectedMark.isVisible = action == SortingUsersOptionsMenuActions.OrderByMoreBooks
moreChaptersConnectedMark.isVisible = action == SortingUsersOptionsMenuActions.OrderByMoreChapters
morePagesConnectedMark.isVisible = action == SortingUsersOptionsMenuActions.OrderByMorePages
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 1 |
Kotlin
|
1
| 2 |
6e778a25c43f85ffe25bce01788a1b5441c81880
| 3,682 |
BookLoverFinalApp
|
Apache License 1.1
|
native/commonizer/testData/callableMemberCommonization/returnTypes/original/js/package_root.kt
|
JetBrains
| 3,432,266 | false | null |
class Planet(val name: String, val diameter: Double)
val propertyWithInferredType1 = 1
val propertyWithInferredType2 = "hello"
val propertyWithInferredType3 = 42.toString()
val propertyWithInferredType4 = null
val propertyWithInferredType5 = Planet("Earth", 12742)
typealias A = Planet
typealias C = Planet
// with inferred type:
val property1 = 1
val property2 = "hello"
val property3 = Planet("Earth", 12742)
val property4 = A("Earth", 12742)
val property5 = A("Earth", 12742)
val property6 = Planet("Earth", 12742)
val property7 = C("Earth", 12742)
// with inferred type:
fun function1() = 1
fun function2() = "hello"
fun function3() = Planet("Earth", 12742)
fun function4() = A("Earth", 12742)
fun function5() = A("Earth", 12742)
fun function6() = Planet("Earth", 12742)
fun function7() = C("Earth", 12742)
val propertyWithMismatchedType1: Int = 1
val propertyWithMismatchedType2: Int = 1
val propertyWithMismatchedType3: Int = 1
val propertyWithMismatchedType4: Int = 1
val propertyWithMismatchedType5: Int = 1
fun functionWithMismatchedType1(): Int = 1
fun functionWithMismatchedType2(): Int = 1
fun functionWithMismatchedType3(): Int = 1
fun functionWithMismatchedType4(): Int = 1
fun functionWithMismatchedType5(): Int = 1
class Box<T>(val value: T)
class Fox
fun functionWithTypeParametersInReturnType1() = arrayOf(1)
fun functionWithTypeParametersInReturnType2() = arrayOf(1)
fun functionWithTypeParametersInReturnType3() = arrayOf("hello")
fun functionWithTypeParametersInReturnType4(): List<Int> = listOf(1)
fun functionWithTypeParametersInReturnType5(): List<Int> = listOf(1)
fun functionWithTypeParametersInReturnType6(): List<String> = listOf("hello")
fun functionWithTypeParametersInReturnType7() = Box(1)
fun functionWithTypeParametersInReturnType8() = Box(1)
fun functionWithTypeParametersInReturnType9() = Box("hello")
fun functionWithTypeParametersInReturnType10() = Box(Planet("Earth", 12742))
fun functionWithTypeParametersInReturnType11() = Box(Planet("Earth", 12742))
fun functionWithTypeParametersInReturnType12() = Box(Fox())
fun <T> functionWithUnsubstitutedTypeParametersInReturnType1(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType2(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType3(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType4(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType5(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType6(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType7(): T = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType8(): Box<T> = TODO()
fun <T> functionWithUnsubstitutedTypeParametersInReturnType9(): Box<T> = TODO()
class Outer<A> {
class Nested<B> {
class Nested<C>
inner class Inner<D>
}
inner class Inner<E> {
inner class Inner<F>
}
}
fun <T> returnOuter(): Outer<T> = TODO()
fun <T> returnOuterNested(): Outer.Nested<T> = TODO()
fun <T> returnOuterNestedNested(): Outer.Nested.Nested<T> = TODO()
fun <T, R> returnOuterInner(): Outer<T>.Inner<R> = TODO()
fun <T, R, S> returnOuterInnerInner(): Outer<T>.Inner<R>.Inner<S> = TODO()
| 181 | null |
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 3,205 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ef/sak/opplysninger/personopplysninger/pensjon/HistoriskPensjonClient.kt
|
navikt
| 206,805,010 | false |
{"Kotlin": 3859882, "Gherkin": 163948, "Dockerfile": 180}
|
package no.nav.familie.ef.sak.opplysninger.personopplysninger.pensjon
import no.nav.familie.http.client.AbstractRestClient
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import org.springframework.web.client.RestOperations
import org.springframework.web.util.UriComponentsBuilder
import java.net.URI
@Component
class HistoriskPensjonClient(
@Value("\${HISTORISK_PENSJON_URL}")
private val historiskPensjonUri: URI,
@Qualifier("azure") restOperations: RestOperations,
) : AbstractRestClient(restOperations, "pensjon") {
private fun lagHarPensjonUri() =
UriComponentsBuilder.fromUri(historiskPensjonUri).pathSegment("api/ensligForsoerger/harPensjonsdata")
.build().toUri()
fun harPensjon(aktivIdent: String, alleRelaterteFoedselsnummer: Set<String>): HistoriskPensjonResponse {
return postForEntity(
lagHarPensjonUri(),
EnsligForsoergerRequest(aktivIdent, alleRelaterteFoedselsnummer),
)
}
}
| 2 |
Kotlin
|
2
| 0 |
27653edb767dcb5876e98fe5501d9a7fb5356957
| 1,099 |
familie-ef-sak
|
MIT License
|
common/src/test/kotlin/io/liquidsoftware/arch/Adapters.kt
|
edreyer
| 445,325,795 | false |
{"Kotlin": 204259, "Procfile": 119}
|
package io.liquidsoftware.arch
import com.tngtech.archunit.core.domain.JavaClasses
class Adapters internal constructor(private val parentContext: HexagonalArchitecture, basePackage: String) :
ArchitectureElement(basePackage) {
private val incomingAdapterPackages: MutableList<String> = ArrayList()
private val outgoingAdapterPackages: MutableList<String> = ArrayList()
fun outgoing(packageName: String): Adapters {
incomingAdapterPackages.add(fullQualifiedPackage(packageName))
return this
}
fun incoming(packageName: String): Adapters {
outgoingAdapterPackages.add(fullQualifiedPackage(packageName))
return this
}
private fun allAdapterPackages(): List<String> {
val allAdapters: MutableList<String> = ArrayList()
allAdapters.addAll(incomingAdapterPackages)
allAdapters.addAll(outgoingAdapterPackages)
return allAdapters
}
fun and(): HexagonalArchitecture {
return parentContext
}
fun dontDependOnEachOther(classes: JavaClasses) {
val allAdapters = allAdapterPackages()
for (adapter1 in allAdapters) {
for (adapter2 in allAdapters) {
if (adapter1 != adapter2) {
denyDependency(adapter1, adapter2, classes)
}
}
}
}
fun doesNotDependOn(packageName: String, classes: JavaClasses) {
denyDependency(basePackage, packageName, classes)
}
fun doesNotContainEmptyPackages() {
denyEmptyPackages(allAdapterPackages())
}
}
| 7 |
Kotlin
|
12
| 49 |
8e006542b23bb90823c66dfe59a70476370a912c
| 1,449 |
modulith
|
MIT License
|
app/src/main/java/com/example/madcamp_week1/DataHandler.kt
|
ssook1222
| 508,576,299 | false | null |
package com.example.madcamp_week1
import android.content.Context
import androidx.core.net.toUri
import com.example.madcamp_week1.contacts.Contacts
import com.example.madcamp_week1.diaries.Diary
import com.example.madcamp_week1.photos.ChoicePhotos
import org.json.JSONArray
import org.json.JSONTokener
import java.io.File
class DataHandler(val context: Context?) {
fun getContactsList(): ArrayList<Contacts> {
val diaryJsonFile = File(context!!.filesDir, "contacts.json")
val contactsList = ArrayList<Contacts>()
if (diaryJsonFile.exists()) {
val contactsJsonString = diaryJsonFile.readText()
if (contactsJsonString.isNotEmpty()) {
val contactsJsonArray = JSONTokener(contactsJsonString).nextValue() as JSONArray
for (i in 0 until contactsJsonArray.length()) {
// Refer to Contacts.kt for correct member names!
val name = contactsJsonArray.getJSONObject(i).getString("contactName")
val phoneNumber = contactsJsonArray.getJSONObject(i).getString("phoneNumber")
val startDate = contactsJsonArray.getJSONObject(i).getString("startDate")
contactsList.add(Contacts(name, phoneNumber, startDate))
}
}
}
return contactsList
}
fun writeContactsList(newData: String) {
val diaryJsonFile = File(context!!.filesDir, "contacts.json")
if (!diaryJsonFile.exists()) {
context.openFileOutput("contacts.json", Context.MODE_PRIVATE)
}
diaryJsonFile.writeText(newData)
}
fun getChoicePhotosList(): ArrayList<ChoicePhotos> {
val imageJsonFile = File(context!!.filesDir, "images.json")
val choicePhotosList = ArrayList<ChoicePhotos>()
if (imageJsonFile.exists()) {
val imageJsonString = imageJsonFile.readText()
if (imageJsonString.isNotEmpty()) {
val imageJsonArray = JSONTokener(imageJsonString).nextValue() as JSONArray
for (i in 0 until imageJsonArray.length()) {
val name = imageJsonArray.getJSONObject(i).getString("contactName")
val uri = imageJsonArray.getJSONObject(i).getString("uri").toUri()
choicePhotosList.add(ChoicePhotos(uri, name))
}
}
}
return choicePhotosList
}
fun getDiariesList(): ArrayList<Diary> {
val diaryJsonFile = File(context!!.filesDir, "diaries.json")
val diaryList = ArrayList<Diary>()
if (diaryJsonFile.exists()) {
val diaryJsonString = diaryJsonFile.readText()
if (diaryJsonString.isNotEmpty()) {
val diaryJsonArray = JSONTokener(diaryJsonString).nextValue() as JSONArray
for (i in 0 until diaryJsonArray.length()) {
val date = diaryJsonArray.getJSONObject(i).getString("date")
val name = diaryJsonArray.getJSONObject(i).getString("name")
val rawUri = diaryJsonArray.getJSONObject(i).getString("uri")
val title = diaryJsonArray.getJSONObject(i).getString("title")
diaryList.add(Diary(date, name, rawUri.toUri(), title))
}
}
}
return diaryList
}
fun writeDiariesList(newData: String) {
val diaryJsonFile = File(context!!.filesDir, "diaries.json")
if (!diaryJsonFile.exists()) {
context.openFileOutput("diaries.json", Context.MODE_PRIVATE)
}
diaryJsonFile.writeText(newData)
}
}
| 0 |
Kotlin
|
0
| 0 |
7e14867995a4389b4699caa458fd2e55b93faa6d
| 3,658 |
madcamp_week1
|
MIT License
|
src/main/kotlin/com/skillw/asahi/api/member/parser/prefix/namespacing/PrefixCreator.kt
|
Glom-c
| 396,683,163 | false | null |
package com.skillw.asahi.api.member.parser.prefix.namespacing
import com.skillw.asahi.api.member.lexer.AsahiLexer
import com.skillw.asahi.api.member.parser.prefix.namespacing.PrefixParser.Companion.prefixParser
import com.skillw.asahi.api.member.quest.Quester
/**
* @className PrefixCreator
*
* 用来快速创建前缀解释器的接口
*
* @author Glom
* @date 2023/1/14 11:07 Copyright 2024 Glom.
*/
interface PrefixCreator<R> {
/**
* 解释器执行内容
*
* @return 结果
*/
fun PrefixParser<R>.parse(): Quester<R>
/**
* 向命名空间注册前缀解释器
*
* @param key 名字
* @param alias 名字
* @param namespace 命名空间
*/
fun register(
key: String,
vararg alias: String,
namespace: String = "common",
) {
object : BasePrefix<R>(key, *alias, namespace = namespace) {
override fun AsahiLexer.parse(): Quester<R> {
return [email protected] { prefixParser<R>().parse() }
}
}.register()
}
}
| 3 | null |
8
| 9 |
35b93485f5f4c2d5c534a2765ff7cfb8f34dd737
| 991 |
Pouvoir
|
MIT License
|
app/src/main/java/eu/darken/androidstarter/common/debug/autoreport/DebugSettings.kt
|
d4rken
| 367,445,682 | false | null |
package eu.darken.androidstarter.common.debug.autoreport
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import eu.darken.androidstarter.common.datastore.PreferenceScreenData
import eu.darken.androidstarter.common.datastore.PreferenceStoreMapper
import eu.darken.androidstarter.common.datastore.createValue
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DebugSettings @Inject constructor(
@ApplicationContext private val context: Context,
) : PreferenceScreenData {
private val Context.dataStore by preferencesDataStore(name = "debug_settings")
override val dataStore: DataStore<Preferences>
get() = context.dataStore
val isAutoReportingEnabled = dataStore.createValue("debug.bugreport.automatic.enabled", true)
override val mapper = PreferenceStoreMapper(
isAutoReportingEnabled,
)
}
| 0 |
Kotlin
|
4
| 22 |
3461b281ccc9c6fc392b09ce97b71055e2f861af
| 1,054 |
android-starter-v4
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.