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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
auth/src/main/java/com/development/gocipes/auth/presentation/forgot/ForgotPasswordFragment.kt | BeCipes | 717,700,454 | false | {"Kotlin": 231408} | package com.development.gocipes.auth.presentation.forgot
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.development.gocipes.auth.databinding.FragmentForgotPasswordBinding
import com.development.gocipes.core.utils.Result
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ForgotPasswordFragment : Fragment() {
private var _binding: FragmentForgotPasswordBinding? = null
private val binding get() = _binding
private val viewModel by viewModels<ForgotViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentForgotPasswordBinding.inflate(layoutInflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupView()
}
private fun setupView() {
binding?.contentForgot?.apply {
btnRegister.setOnClickListener {
val email = tilEmail.editText?.text.toString().trim()
forgotObserver(email)
}
}
}
private fun forgotObserver(
email: String
) {
viewModel.forgotPassword(email)
.observe(viewLifecycleOwner) { result ->
when (result) {
is Result.Error -> {
Toast.makeText(requireActivity(), result.message, Toast.LENGTH_SHORT).show()
}
is Result.Loading -> {}
is Result.Success -> {
navigateToLogin()
Toast.makeText(
requireActivity(),
"Reset Password Berhasil, Silahkan Periksa Email Anda",
Toast.LENGTH_SHORT
).show()
}
}
}
}
private fun navigateToLogin() {
val action =
ForgotPasswordFragmentDirections.actionForgotPasswordFragmentToLoginFragment()
findNavController().navigate(action)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
} | 0 | Kotlin | 1 | 0 | 4559d6c57777adc40d1c2d15c102a54f138ad45d | 2,493 | Mobile-Development | Apache License 2.0 |
app/src/test/java/com/movietrivia/filmfacts/viewmodel/AuthenticationViewModelTest.kt | jlynchsd | 631,418,923 | false | {"Kotlin": 524037} | package com.movietrivia.filmfacts.viewmodel
import com.movietrivia.filmfacts.model.AuthenticationRepository
import com.movietrivia.filmfacts.model.UserDataRepository
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class AuthenticationViewModelTest {
private lateinit var authenticationRepository: AuthenticationRepository
private lateinit var userDataRepository: UserDataRepository
private lateinit var viewModel: AuthenticationViewModel
@Before
fun setup() {
authenticationRepository = mockk(relaxed = true)
userDataRepository = mockk(relaxed = true)
viewModel = AuthenticationViewModel(authenticationRepository, userDataRepository)
}
@Test
fun `When consuming expired auth request returns null`() {
every {
authenticationRepository.hasAuthRequestExpired()
} returns true
Assert.assertNull(viewModel.consumeAuthRequest())
}
@Test
fun `When consuming valid auth request delegates to the auth repository`() {
every {
authenticationRepository.hasAuthRequestExpired()
} returns false
every {
authenticationRepository.consumeAuthRequest()
} returns null
viewModel.consumeAuthRequest()
verify { authenticationRepository.consumeAuthRequest() }
}
@Test
fun `When preparing auth session delegates to auth repository`() = runViewModelScope {
viewModel.prepareAuthenticationSession()
coVerify { authenticationRepository.prepareAuthenticationSession() }
}
@Test
fun `When getting new authentication token delegates to user repository`() = runTest {
viewModel.getNewAuthenticationToken()
coVerify { userDataRepository.getNewAuthenticationToken() }
}
@Test
fun `When setting pending session delegates to user repository`() {
val token = "foo"
viewModel.setPendingSession(token)
verify { userDataRepository.setPendingSession(token) }
}
@Test
fun `When creating pending session delegates to user repository`() = runTest {
viewModel.createPendingSession()
coVerify { userDataRepository.createPendingSession() }
}
@Test
fun `When getting if there is an active session delegates to user repository`() {
viewModel.hasSession()
verify { userDataRepository.hasSession() }
}
@Test
fun `When deleting session delegates to user repository`() = runViewModelScope {
viewModel.deleteSession()
coVerify { userDataRepository.deleteSession() }
}
} | 0 | Kotlin | 0 | 0 | 9a6c9ae5bc2f7a743c9399a64d0c9edf5c7e0d84 | 2,747 | FilmFacts | Apache License 2.0 |
daemon/src/main/kotlin/dev/krud/boost/daemon/messaging/ApplicationDeletedEventMessage.kt | krud-dev | 576,882,508 | false | null | package dev.krud.boost.daemon.messaging
import dev.krud.boost.daemon.base.annotations.GenerateTypescript
import dev.krud.boost.daemon.websocket.WebsocketTopics
import dev.krud.boost.daemon.websocket.replay.webSocketHeaders
import java.util.*
@GenerateTypescript
class ApplicationDeletedEventMessage(payload: Payload) : AbstractMessage<ApplicationDeletedEventMessage.Payload>(
payload,
*webSocketHeaders(
WebsocketTopics.APPLICATION_DELETION,
payload.applicationId.toString()
)
) {
data class Payload(
val applicationId: UUID,
val discovered: Boolean
)
} | 41 | TypeScript | 6 | 251 | 1f3db028ac7d60faa6c30daabbb41482e814d23f | 607 | ostara | Apache License 2.0 |
core/src/main/kotlin/com/seventh_root/guildfordgamejam/screen/MainScreen.kt | alyphen | 72,883,027 | false | null | package com.seventh_root.guildfordgamejam.screen
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Family
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.ScreenAdapter
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType.Filled
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType.Line
import com.badlogic.gdx.math.Vector3
import com.seventh_root.guildfordgamejam.GuildfordGameJam
import com.seventh_root.guildfordgamejam.component.*
import com.seventh_root.guildfordgamejam.level.Level
import com.seventh_root.guildfordgamejam.system.*
class MainScreen(game: GuildfordGameJam): ScreenAdapter() {
val engine = Engine()
val shapeRenderer = ShapeRenderer()
val playerFamily: Family = Family.all(PlayerComponent::class.java).get()
val grappleFamily: Family = Family.all(GrappleComponent::class.java).get()
val finishFamily: Family = Family.all(FinishComponent::class.java).get()
val finishEffectFamily: Family = Family.all(FinishEffectComponent::class.java).get()
val camera = OrthographicCamera()
val orbitSound: Sound = Gdx.audio.newSound(Gdx.files.internal("orbit.ogg"))
val pluck1Sound: Sound = Gdx.audio.newSound(Gdx.files.internal("pluck1.ogg"))
val pluck2Sound: Sound = Gdx.audio.newSound(Gdx.files.internal("pluck2.ogg"))
val pluck3Sound: Sound = Gdx.audio.newSound(Gdx.files.internal("pluck3.ogg"))
val pluck4Sound: Sound = Gdx.audio.newSound(Gdx.files.internal("pluck4.ogg"))
val popSound: Sound = Gdx.audio.newSound(Gdx.files.internal("pop.ogg"))
val levelCompletePlucks: Sound = Gdx.audio.newSound(Gdx.files.internal("level_complete_plucks.ogg"))
val font = BitmapFont(Gdx.files.internal("m5x7.fnt"))
val spriteBatch = SpriteBatch()
init {
camera.setToOrtho(true)
engine.addSystem(MovementSystem())
engine.addSystem(FrictionSystem())
engine.addSystem(GravitySystem())
engine.addSystem(PullSystem())
engine.addSystem(PlayerSizeSystem())
engine.addSystem(PlayerColorSystem())
engine.addSystem(FinishSystem(game))
engine.addSystem(RadiusScalingSystem())
engine.addSystem(ColorCollectionSystem())
engine.addSystem(PlayerSoundSystem(game))
engine.addSystem(TimerSystem())
}
override fun show() {
Gdx.input.inputProcessor = object: InputAdapter() {
override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
engine.getEntitiesFor(playerFamily).forEach { player ->
if (velocity.get(player).x == 0F && velocity.get(player).y == 0F) {
val startX = position.get(player).x
val startY = position.get(player).y
val endX = Gdx.input.x.toFloat() + camera.position.x - (Gdx.graphics.width / 2)
val endY = Gdx.input.y.toFloat() + camera.position.y - (Gdx.graphics.height / 2)
val h2 = 8F
val o1 = endY - startY
val a1 = endX - startX
val theta = Math.atan((o1 / a1).toDouble()) + if (endX < startX) Math.PI else 0.0
val a2 = Math.cos(theta) * h2
val o2 = Math.sin(theta) * h2
velocity.get(player).x = a2.toFloat()
velocity.get(player).y = o2.toFloat()
orbitSound.play()
}
}
return true
}
}
}
override fun hide() {
Gdx.input.inputProcessor = null
}
override fun render(delta: Float) {
Gdx.gl.glClearColor(0.toFloat(), 0.toFloat(), 0.toFloat(), 0.toFloat())
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
engine.update(delta)
val playerEntity = engine.getEntitiesFor(playerFamily).first()
camera.position.set(Vector3((camera.position.x * (15F/16F)) + (position.get(playerEntity).x * (1F/16F)), (camera.position.y * (15F/16F)) + (position.get(playerEntity).y * (1F/16F)), 0.toFloat()))
camera.update()
shapeRenderer.projectionMatrix = camera.combined
shapeRenderer.color = color.get(playerEntity).color
shapeRenderer.begin(Line)
shapeRenderer.circle(position.get(playerEntity).x, position.get(playerEntity).y, radius.get(playerEntity).radius)
shapeRenderer.end()
shapeRenderer.begin(Line)
val startX = position.get(playerEntity).x
val startY = position.get(playerEntity).y
val endX = Gdx.input.x.toFloat() + camera.position.x - (Gdx.graphics.width / 2)
val endY = Gdx.input.y.toFloat() + camera.position.y - (Gdx.graphics.height / 2)
val h2 = 64F
val o1 = endY - startY
val a1 = endX - startX
val theta = Math.atan((o1 / a1).toDouble()) + if (endX < startX) Math.PI else 0.0
val a2 = Math.cos(theta) * h2
val o2 = Math.sin(theta) * h2
val x2 = startX + a2
val y2 = startY + o2
shapeRenderer.line(startX, startY, x2.toFloat(), y2.toFloat())
shapeRenderer.end()
engine.getEntitiesFor(grappleFamily).forEach { grappleEntity ->
if (collectedColors.get(playerEntity).colors.contains(color.get(grappleEntity).color)) {
shapeRenderer.color = Color.WHITE
} else {
shapeRenderer.color = color.get(grappleEntity).color
}
shapeRenderer.begin(Filled)
shapeRenderer.circle(position.get(grappleEntity).x, position.get(grappleEntity).y, radius.get(grappleEntity).radius)
shapeRenderer.end()
}
engine.getEntitiesFor(finishFamily).forEach { finishEntity ->
shapeRenderer.color = color.get(finishEntity).color
shapeRenderer.begin(Line)
shapeRenderer.circle(position.get(finishEntity).x, position.get(finishEntity).y, radius.get(finishEntity).radius)
shapeRenderer.end()
}
engine.getEntitiesFor(finishEffectFamily).forEach { finishEffectEntity ->
shapeRenderer.color = color.get(finishEffectEntity).color
shapeRenderer.begin(Line)
shapeRenderer.circle(position.get(finishEffectEntity).x, position.get(finishEffectEntity).y, radius.get(finishEffectEntity).radius)
shapeRenderer.end()
}
spriteBatch.begin()
font.draw(spriteBatch, "${collectedColors.get(playerEntity).colors.size}/${engine.getEntitiesFor(grappleFamily).filter { grapple -> color.get(grapple).color != Color.WHITE }.size}", 16F, 32F)
font.draw(spriteBatch, String.format("%.2f", timer.get(playerEntity).time), 16F, 64F)
spriteBatch.end()
}
override fun dispose() {
shapeRenderer.dispose()
orbitSound.dispose()
pluck1Sound.dispose()
pluck2Sound.dispose()
pluck3Sound.dispose()
pluck4Sound.dispose()
popSound.dispose()
levelCompletePlucks.dispose()
font.dispose()
spriteBatch.dispose()
}
fun displayLevel(level: Level) {
engine.removeAllEntities()
level.entities.forEach { entity -> engine.addEntity(entity) }
}
} | 0 | Kotlin | 0 | 1 | a55ec8d4525d0e2c938d376b476eba6b5e32132b | 7,621 | guildford-game-jam-2016 | Apache License 2.0 |
projecteuler/src/problem4.kt | sleddog | 133,080,668 | false | null | package projecteuler
//A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
//
//Find the largest palindrome made from the product of two 3-digit numbers.
fun problem4() : Int? {
var myList: MutableList<Int> = mutableListOf<Int>()
for (i in 100..999) {
for (j in 100..999) {
var p = i * j
if(isPalidrome(p)) {
myList.add(p)
}
}
}
var max = maxInt(myList.toIntArray())
return max
}
fun isPalidrome(num : Int) : Boolean {
var s = num.toString()
var reverse = s.reversed()
return s == reverse
}
fun maxInt(nums : IntArray) : Int? {
return nums.max()
} | 0 | Kotlin | 0 | 0 | 5c68db5208c1dc5815638ca2ab0de47030017e0a | 739 | kotlin | MIT License |
app/src/main/java/kasem/sm/delightplayground/di/NetworkModule.kt | Sagar19RaoRane | 410,922,426 | true | {"Kotlin": 48406} | package kasem.sm.delightplayground.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
import kasem.sm.delightplayground.datasource.network.RocketService
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideRocketService(): RocketService {
return RocketService()
}
}
| 0 | null | 0 | 0 | a460b209501fe732cbd3a82fcbb24712b62929ab | 445 | RocketXDelight-Playground | Apache License 2.0 |
livekit-android-sdk/src/main/java/io/livekit/android/room/track/LocalVideoTrack.kt | zeerakMush | 726,791,824 | false | {"Gradle": 5, "Markdown": 3, "Java Properties": 2, "Shell": 2, "Text": 2, "Ignore List": 3, "Batchfile": 1, "INI": 2, "Proguard": 2, "XML": 21, "Kotlin": 51, "Java": 164, "Makefile": 2, "C++": 1, "C": 1, "Protocol Buffer": 6, "Go Checksums": 1, "Go": 31, "Go Module": 1, "JSON": 1} | package io.livekit.android.room.track
import android.content.Context
import io.livekit.android.util.LKLog
import org.webrtc.Camera1Enumerator
import org.webrtc.Camera2Enumerator
import org.webrtc.CameraEnumerator
import org.webrtc.EglBase
import org.webrtc.PeerConnectionFactory
import org.webrtc.RtpSender
import org.webrtc.RtpTransceiver
import org.webrtc.SurfaceTextureHelper
import org.webrtc.VideoCapturer
import org.webrtc.VideoSource
import java.util.*
/**
* A representation of a local video track (generally input coming from camera or screen).
*
* [startCapture] should be called before use.
*/
class LocalVideoTrack(
private var capturer: VideoCapturer,
private var source: VideoSource,
name: String,
var options: LocalVideoTrackOptions,
rtcTrack: org.webrtc.VideoTrack,
private val peerConnectionFactory: PeerConnectionFactory,
private val context: Context,
private val eglBase: EglBase,
) : VideoTrack(name, rtcTrack) {
override var rtcTrack: org.webrtc.VideoTrack = rtcTrack
internal set
/**
* Note: these dimensions are only requested params, and may differ
* from the actual capture format used by the camera.
*/
val dimensions: Dimensions
get() = Dimensions(options.captureParams.width, options.captureParams.height)
internal var transceiver: RtpTransceiver? = null
private val sender: RtpSender?
get() = transceiver?.sender
fun startCapture() {
capturer.startCapture(
options.captureParams.width,
options.captureParams.height,
options.captureParams.maxFps
)
}
override fun stop() {
capturer.stopCapture()
super.stop()
}
fun restartTrack(options: LocalVideoTrackOptions = LocalVideoTrackOptions()) {
val newTrack = createTrack(
peerConnectionFactory,
context,
name,
options,
eglBase
)
val oldCapturer = capturer
val oldSource = source
val oldRtcTrack = rtcTrack
oldCapturer.stopCapture()
oldCapturer.dispose()
oldSource.dispose()
// sender owns rtcTrack, so it'll take care of disposing it.
oldRtcTrack.setEnabled(false)
// migrate video sinks to the new track
for (sink in sinks) {
oldRtcTrack.removeSink(sink)
newTrack.addRenderer(sink)
}
capturer = newTrack.capturer
source = newTrack.source
rtcTrack = newTrack.rtcTrack
this.options = options
startCapture()
sender?.setTrack(newTrack.rtcTrack, true)
}
companion object {
internal fun createTrack(
peerConnectionFactory: PeerConnectionFactory,
context: Context,
name: String,
options: LocalVideoTrackOptions,
rootEglBase: EglBase,
): LocalVideoTrack {
val source = peerConnectionFactory.createVideoSource(options.isScreencast)
val capturer = createVideoCapturer(context, options.position) ?: TODO()
capturer.initialize(
SurfaceTextureHelper.create("VideoCaptureThread", rootEglBase.eglBaseContext),
context,
source.capturerObserver
)
val track = peerConnectionFactory.createVideoTrack(UUID.randomUUID().toString(), source)
return LocalVideoTrack(
capturer = capturer,
source = source,
options = options,
name = name,
rtcTrack = track,
peerConnectionFactory = peerConnectionFactory,
context = context,
eglBase = rootEglBase,
)
}
private fun createVideoCapturer(context: Context, position: CameraPosition): VideoCapturer? {
val videoCapturer: VideoCapturer? = if (Camera2Enumerator.isSupported(context)) {
createCameraCapturer(Camera2Enumerator(context), position)
} else {
createCameraCapturer(Camera1Enumerator(true), position)
}
if (videoCapturer == null) {
LKLog.d { "Failed to open camera" }
return null
}
return videoCapturer
}
private fun createCameraCapturer(enumerator: CameraEnumerator, position: CameraPosition): VideoCapturer? {
val deviceNames = enumerator.deviceNames
for (deviceName in deviceNames) {
if (enumerator.isFrontFacing(deviceName) && position == CameraPosition.FRONT) {
LKLog.v { "Creating front facing camera capturer." }
val videoCapturer = enumerator.createCapturer(deviceName, null)
if (videoCapturer != null) {
return videoCapturer
}
} else if (enumerator.isBackFacing(deviceName) && position == CameraPosition.BACK) {
LKLog.v { "Creating back facing camera capturer." }
val videoCapturer = enumerator.createCapturer(deviceName, null)
if (videoCapturer != null) {
return videoCapturer
}
}
}
return null
}
}
} | 1 | Java | 1 | 1 | a51feb51275e809baf09e6ceef9dd0d86b290cd2 | 5,372 | RIOT-livekit | Apache License 2.0 |
2nd Course/Projects/Programacion Multimedia y Dispositivos/BLOQUE 1/EjerciciosBloque2_2/src/main/kotlin/Rectangulo.kt | stanmkr | 505,510,534 | false | {"Java": 915903, "C#": 86315, "Python": 56896, "Kotlin": 32374, "HTML": 22653, "CSS": 6768, "XQuery": 3005} | import java.text.DecimalFormat
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Created by <NAME>
* EjerciciosBloque2_2 -
* Date: Octubre / 2022
*
* Realizar un programa que solicite las dimensiones de los lados de un rectángulo y nos pida si
queremos calcular su perímetro, superficie, la diagonal trazada entre dos vértices opuestos o el área
del triángulo formado al trazar esta diagonal
*/
fun main() {
print("Introduce la base del rectángulo: ")
val base = readln().toDouble()
print("Introduce la altura del rectángulo: ")
val altura = readln().toDouble()
menu()
when (readln()) {
// perimetro
"1" -> {
println("\nEl perímetro del rectángulo es ${2 * base + 2 * altura}")
}
// superficie
"2" -> {
println("\nLa superficie del rectángulo es ${base * altura}")
}
// diagonal trazada entre dos vertices opuestos
"3" -> {
val diagonal = sqrt(altura.pow(2.0) + base.pow(2.0))
val formato2Decimales = DecimalFormat("#.00")
val diagonalFormateado = formato2Decimales.format(diagonal)
println("La diagonal es $diagonalFormateado")
}
// area
"4" -> {
print("El área del triangulo formado al trazar esta diagonal es ${(base * altura) / 2}")
}
else -> {
println("Opción desconocida.")
}
}
}
private fun menu() {
println(
"\nELIGE QUE QUIERES CALCULAR\n" +
"1. Perimetro\n" +
"2. Superficie\n" +
"3. Diagonal trazada entre dos vértices opuestos\n" +
"4. Área del triángulo formado al trazar esta diagonal.\n"
)
print("Introduce opcion: ")
} | 1 | null | 1 | 1 | 1442b56b9363210583086461157d67ebc67c2f18 | 1,768 | IES-Thiar | MIT License |
app/src/main/java/repo/CheckInRepo.kt | TonyTangAndroid | 754,476,574 | false | {"Java Properties": 1, "Gradle Kotlin DSL": 24, "Markdown": 9, "Shell": 2, "Batchfile": 1, "Text": 3, "Ignore List": 2, "Java": 151, "CODEOWNERS": 1, "JSON5": 1, "YAML": 1, "JSON": 2, "TOML": 1, "INI": 1, "Proguard": 2, "Kotlin": 62, "XML": 16} | package repo
import app.AppContext
import app.DemoApp
import io.opentelemetry.api.baggage.Baggage
import io.opentelemetry.context.Context
import io.reactivex.Single
import network.CheckInResult
import network.LocationModel
class CheckInRepo(private val appContext: AppContext) {
fun checkingIn(locationModel: LocationModel, context: Context): Single<CheckInResult> {
val otelContext = context.with(attachedSendingNetwork(context))
val token = TokenStore(appContext).token()
return DemoApp.appScope(appContext).singleApi().checkIn(otelContext, locationModel, token)
}
private fun attachedSendingNetwork(context: Context): Baggage {
return Baggage.fromContext(context).toBuilder()
.put("sending_network", System.currentTimeMillis().toString())
.build()
}
}
| 1 | null | 1 | 1 | 640f472bc7101057b9e761299e73afad917fec08 | 843 | openTelemetryAndroidSdk | Apache License 2.0 |
app/src/main/java/com/paysafe/hackathon/thesesame/ui/fragments/myArtItems/MyArtItemsFragment.kt | Bzahov98 | 300,816,174 | false | null | package com.paysafe.hackathon.thesesame.ui.fragments.myArtItems
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.paysafe.hackathon.thesesame.R
import com.paysafe.hackathon.thesesame.data.model.ArtItemData
import com.paysafe.hackathon.thesesame.internal.utils.gone
import com.paysafe.hackathon.thesesame.internal.utils.show
import com.paysafe.hackathon.thesesame.ui.fragments.addNew.AddNewOfferDialogFragment
import com.paysafe.hackathon.thesesame.ui.fragments.addNew.CallbackListener
import com.paysafe.hackathon.thesesame.ui.fragments.home.HomeViewModelFactory
import com.paysafe.hackathon.thesesame.ui.fragments.myArtItems.recyclerview.ArtListItem
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.dialog_fullscreen_add_new.*
import kotlinx.android.synthetic.main.fragment_art_list_my.*
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.closestKodein
import org.kodein.di.generic.instance
import java.util.function.Consumer
class MyArtItemsFragment : Fragment(),KodeinAware, CallbackListener {
private val TAG = "UploadOfferFragment"
override val kodein by closestKodein()
private lateinit var viewModel: MyArtItemsViewModel
private lateinit var groupAdapter: GroupAdapter<ViewHolder>
private lateinit var recyclerView: RecyclerView
private lateinit var customAlertDialogView : View
private lateinit var materialAlertDialogBuilder: MaterialAlertDialogBuilder
private val factory: MyArtItemsViewModelFactory by instance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
materialAlertDialogBuilder = MaterialAlertDialogBuilder(requireContext())
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = ViewModelProvider(this, factory).get(MyArtItemsViewModel::class.java)
// val textView: TextView = root.findViewById(R.id.text_notifications)
// uploadOfferViewModel.text.observe(viewLifecycleOwner, Observer {
// textView.text = it
// })
return inflater.inflate(R.layout.fragment_art_list_my, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initRecyclerView()
myItemsListAddNewFAB.setOnClickListener{
// Inflate Custom alert dialog view
showDialog()
}
updateReceivedData()
}
private fun initRecyclerView() {
groupAdapter = GroupAdapter<ViewHolder>()
recyclerView = myItemsListRecyclerView.apply {
layoutManager = LinearLayoutManager([email protected])
adapter = groupAdapter
}
groupAdapter.setOnItemClickListener { item, view ->
val itemDetail = (item as ArtListItem).data
Toast.makeText(
[email protected],
"Clicked: ${itemDetail.title}",
Toast.LENGTH_SHORT
).show()
//startPlaceDetailActivity(requireContext(), itemDetail.id)
Log.e(TAG, "\n\nGroupAdapter.setOnItemClickListener ${itemDetail}\n")
//showWeatherDetail(itemDetail.dtTxt, view)
}
}
private fun updateReceivedData() {
val listItem = HashSet<ArtListItem>()
viewModel.listData.observe(
viewLifecycleOwner,
Observer { t ->
run {
listItem.clear()
t.forEach(Consumer { place ->
if( place == null) return@Consumer
listItem.add(ArtListItem(place))
})
clearUpdateRecyclerViewData(listItem)
}
})
}
private fun showDialog() {
val dialogFragment = AddNewOfferDialogFragment(this)
dialogFragment.show(requireActivity().supportFragmentManager, "signature")
}
private fun clearUpdateRecyclerViewData(items: Set<ArtListItem>?) { // null only to clear data
groupAdapter.clear()
if (!items.isNullOrEmpty()) {
groupAdapter.apply { addAll(items) }
myItemsListNoResults.gone()
}else{
myItemsListNoResults.show()
}
groupAdapter.notifyDataSetChanged()
}
override fun onDataReceived(data: ArtItemData) {
Log.d(TAG, "onDataReceived: ${data.title}\n$data")
viewModel.createNewItem(data)
}
} | 1 | Kotlin | 1 | 0 | ee80502a10790d7d55526ff4989aeb2f4758e55a | 5,031 | TheSesame | MIT License |
codebase/android/feature/settings/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/settings/screen/SettingsScreenUIState.kt | Abhimanyu14 | 429,663,688 | false | null | package com.makeappssimple.abhimanyu.financemanager.android.feature.settings.screen
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@Stable
class SettingsScreenUIState(
data: SettingsScreenUIData,
val settingsBottomSheetType: SettingsBottomSheetType,
val setSettingsBottomSheetType: (SettingsBottomSheetType) -> Unit,
) {
val isLoading: Boolean = data.isLoading
val appVersion: String? = data.appVersion
val resetBottomSheetType: () -> Unit = {
setSettingsBottomSheetType(SettingsBottomSheetType.NONE)
}
}
@Composable
fun rememberSettingsScreenUIState(
data: SettingsScreenUIData,
): SettingsScreenUIState {
val (settingsBottomSheetType: SettingsBottomSheetType, setSettingsBottomSheetType: (SettingsBottomSheetType) -> Unit) = remember {
mutableStateOf(
value = SettingsBottomSheetType.NONE,
)
}
return remember(
data,
settingsBottomSheetType,
setSettingsBottomSheetType,
) {
SettingsScreenUIState(
data = data,
settingsBottomSheetType = settingsBottomSheetType,
setSettingsBottomSheetType = setSettingsBottomSheetType,
)
}
}
| 0 | Kotlin | 0 | 0 | ad9e8d4a2e74a010949cde1315dedb0d294acec8 | 1,317 | finance-manager | Apache License 2.0 |
src/test/kotlin/ui/settings/reducer/ChangeSubdirectoryReducerTest.kt | gmatyszczak | 171,290,380 | false | {"Kotlin": 192668} | package ui.settings.reducer
import app.cash.turbine.test
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.runBlockingTest
import model.Category
import model.CategoryScreenElements
import model.ScreenElement
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import ui.settings.SettingsAction
import ui.settings.SettingsAction.ChangeFileName
import ui.settings.SettingsAction.UpdateScreenElement
import ui.settings.SettingsState
class ChangeFileNameReducerTest {
val state = MutableStateFlow(SettingsState())
val actionFlow = MutableSharedFlow<SettingsAction>()
lateinit var reducer: ChangeFileNameReducer
@BeforeEach
fun setup() {
reducer = ChangeFileNameReducer(state, actionFlow)
}
@Test
fun `if selected element not null on invoke`() = runBlockingTest {
state.value = SettingsState(
categories = listOf(
CategoryScreenElements(
Category(),
listOf(ScreenElement())
)
),
selectedElementIndex = 0,
selectedCategoryIndex = 0
)
actionFlow.test {
reducer.invoke(ChangeFileName("test"))
awaitItem() shouldBeEqualTo UpdateScreenElement(ScreenElement(fileNameTemplate = "test"))
cancelAndIgnoreRemainingEvents()
}
}
}
| 6 | Kotlin | 28 | 147 | baf6d12b12c210e835e2513d9e6d6c1e279c8115 | 1,495 | screen-generator-plugin | Apache License 2.0 |
app/src/main/java/com/example/sandbox/core/di/NetworkModule.kt | rafikFares | 516,824,362 | false | null | package com.example.sandbox.core.di
import com.example.sandbox.BuildConfig
import com.example.sandbox.core.api.ServiceApi
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import okhttp3.Cache
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import retrofit2.Retrofit
private const val CACHE_SIZE = 10 * 1024 * 1024L // 10 MB
private const val DEFAULT_TIMEOUT = 15L // seconds
private const val CONTENT_TYPE = "application/json"
@OptIn(ExperimentalSerializationApi::class)
val networkModule = module {
// provide HttpLoggingInterceptor
single<HttpLoggingInterceptor> {
val logging = HttpLoggingInterceptor()
logging.level =
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BASIC else HttpLoggingInterceptor.Level.NONE
logging
}
// provide OkHttpClient
single<OkHttpClient> {
val httpLoggingInterceptor: HttpLoggingInterceptor = get()
OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor) // Logging Interceptor
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) // Timeout
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) // Timeout
.cache(Cache(File(androidContext().cacheDir, "okhttp"), CACHE_SIZE)) // Cache
.build()
}
// provide default json
single<Json> {
fun provideJson(
_prettyPrint: Boolean = false,
_encodeDefaults: Boolean = false
) = Json {
prettyPrint = _prettyPrint
ignoreUnknownKeys = true
coerceInputValues = true
encodeDefaults = _encodeDefaults
useAlternativeNames = false
}
provideJson(true, true)
}
// provide Retrofit
single<Retrofit> {
val defaultJson: Json = get()
val okHttpClient: OkHttpClient = get()
val contentType = CONTENT_TYPE.toMediaType()
Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(defaultJson.asConverterFactory(contentType))
.build()
}
// provide Api
single<ServiceApi> {
val retrofit: Retrofit = get()
retrofit.create(ServiceApi::class.java)
}
}
| 0 | Kotlin | 0 | 0 | bfca442f6df73482be443c6c799df907e9b4c0de | 2,571 | Sandbox_v1 | Apache License 2.0 |
src/main/kotlin/mainscreen_boxes/PingBoxesB.kt | hispanicdevian | 720,999,284 | false | {"Kotlin": 116998} | package mainscreen_boxes
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import custom_resources.CustomGrayA
import custom_resources.CustomRedA
import custom_resources.MainColorA
import engine_logic.*
import sub_views.settingFontSize
import sub_views.settingOnOffBoxes
import sub_views.settingPingBoxes
import views.settingScreen
//////////////////////////////////////////////////////////// Ping boxes shown in the first column of the main screen
@Composable
@Preview
fun pingBoxesA(pingSuccessfulA0: Boolean, pingSuccessfulA1: Boolean, pingSuccessfulA2: Boolean, pingSuccessfulA3: Boolean) {
// Ram for active View/Screen
val currentScreen by remember { mutableStateOf<Navi>(Navi.MainScn) }
// Pass through ram for ping state
val pingSuccessfulList = listOf(pingSuccessfulA0, pingSuccessfulA1, pingSuccessfulA2, pingSuccessfulA3)
// Title list ram, need to be replaced so that the user can modify it live
val titleList = listOf(ipTitle00, ipTitle01, ipTitle02, ipTitle03)
// Font size ram
val fontSizedA by remember { mutableStateOf(loadFontSizeV1A().sp) }
// Loads the last state of On/Off settings
val visibilityList = remember {
val currentState = SLOnOffHandlerA.loadOnOffFileA()
if (currentState.isNotEmpty()) {
currentState.split(",").map { it.toBoolean() }
} else {
listOf(true, true, true, true)
}
}
//////////////////////////////////////////////////////////// UI container
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.height(15.dp))
//////////////////////////////////////////////////////////// Navi head
when (currentScreen) {
is Navi.MainScn -> {
////////////////////////////// Creates boxes based on # of titles, and its visibility based on settings file
for (index in titleList.indices) {
if (visibilityList[index]) {
Box(
modifier = Modifier
/*
.background(color = ErgoGray, shape = AbsoluteRoundedCornerShape(8.dp))
.padding(5.dp)
*/
.weight(1f)
.aspectRatio(1.5f)
.background((if (pingSuccessfulList[index]) MainColorA else CustomRedA), shape = AbsoluteRoundedCornerShape(8.dp)),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = titleList[index],
color = CustomGrayA,
fontWeight = FontWeight.W900,
fontSize = fontSizedA,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = if (pingSuccessfulList[index]) "On" else "Off",
color = CustomGrayA,
fontWeight = FontWeight.W800,
fontSize = fontSizedA,
textAlign = TextAlign.Center
)
}
}
Spacer(modifier = Modifier.height(15.dp))
}
}
}
//////////////////////////////////////////////////////////// Navi tail
Navi.SettingFontSz -> settingFontSize()
Navi.SettingPingBxs -> settingPingBoxes()
Navi.SettingScn -> settingScreen()
Navi.SettingOnOffBxs -> settingOnOffBoxes()
}
}
}
| 0 | Kotlin | 0 | 1 | 121d7003abf47b1dff2bdcd479a0ed6a9745623e | 4,801 | MonithorClient | MIT License |
app/src/main/java/com/petko/fruitapp/FruitApplication.kt | petkomik | 760,632,924 | false | {"Kotlin": 48630} | package com.petko.fruitapp
import android.app.Application
import com.petko.fruitapp.data.AppContainer
import com.petko.fruitapp.data.DefaultAppContainer
class FruitApplication : Application() {
lateinit var container: AppContainer
override fun onCreate() {
super.onCreate()
container = DefaultAppContainer(this)
}
}
| 0 | Kotlin | 0 | 0 | 3859338f6cfa58c029d7c8f5c739d78722ab59d6 | 347 | fruitapp | The Unlicense |
NevigationDrawer/app/src/main/java/com/example/navigationdrawer/MainActivity.kt | codecraft732 | 850,277,349 | false | {"Kotlin": 177234} | package com.example.navigationdrawer
import android.os.Bundle
import android.view.Menu
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.navigation.NavigationView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import com.example.navigationdrawer.databinding.ActivityMainBinding
//we choose nevigation drawer and this code is already written we did'nt write it
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//blue action bar set
setSupportActionBar(binding.appBarMain.toolbar)
binding.appBarMain.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null)
.setAnchorView(R.id.fab).show()
}
val drawerLayout: DrawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_content_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
//after clicking hamburgar menu pass home gallery slideshow
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow
), drawerLayout
)
//mostly in apps we hide action bar but in fragment when we change it shows so set it here
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
// write this piece of code for show action bar
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
} | 0 | Kotlin | 0 | 0 | f0cdbbac2bf5463cfaa7fd4b7b2b7e1dfe466608 | 2,706 | Android-Genius-Mastery | MIT License |
features/gallery/src/main/kotlin/io/plastique/gallery/GalleryFragment.kt | technoir42 | 251,129,452 | true | {"Kotlin": 1006812, "Shell": 4132, "FreeMarker": 3362} | package io.plastique.gallery
import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.PopupMenu
import androidx.core.text.HtmlCompat
import androidx.core.text.htmlEncode
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.technoir42.android.extensions.disableChangeAnimations
import com.github.technoir42.android.extensions.instantiate
import com.github.technoir42.glide.preloader.ListPreloader
import com.github.technoir42.kotlin.extensions.plus
import com.github.technoir42.rxjava2.extensions.pairwiseWithPrevious
import com.google.android.flexbox.FlexboxLayoutManager
import io.plastique.core.BaseFragment
import io.plastique.core.ExpandableToolbarLayout
import io.plastique.core.ScrollableToTop
import io.plastique.core.content.ContentStateController
import io.plastique.core.content.EmptyView
import io.plastique.core.dialogs.ConfirmationDialogFragment
import io.plastique.core.dialogs.InputDialogFragment
import io.plastique.core.dialogs.OnConfirmListener
import io.plastique.core.dialogs.OnInputDialogResultListener
import io.plastique.core.dialogs.ProgressDialogController
import io.plastique.core.image.ImageLoader
import io.plastique.core.image.TransformType
import io.plastique.core.lists.EndlessScrollListener
import io.plastique.core.lists.GridParams
import io.plastique.core.lists.GridParamsCalculator
import io.plastique.core.lists.IndexedItem
import io.plastique.core.lists.ItemSizeCallback
import io.plastique.core.lists.ListItem
import io.plastique.core.lists.ListUpdateData
import io.plastique.core.lists.calculateDiff
import io.plastique.core.mvvm.viewModel
import io.plastique.core.navigation.navigationContext
import io.plastique.core.snackbar.SnackbarController
import io.plastique.deviations.list.DeviationItem
import io.plastique.deviations.list.ImageDeviationItem
import io.plastique.deviations.list.ImageHelper
import io.plastique.gallery.GalleryEvent.CreateFolderEvent
import io.plastique.gallery.GalleryEvent.DeleteFolderEvent
import io.plastique.gallery.GalleryEvent.LoadMoreEvent
import io.plastique.gallery.GalleryEvent.RefreshEvent
import io.plastique.gallery.GalleryEvent.RetryClickEvent
import io.plastique.gallery.GalleryEvent.SnackbarShownEvent
import io.plastique.gallery.GalleryEvent.UndoDeleteFolderEvent
import io.plastique.gallery.folders.Folder
import io.plastique.inject.getComponent
import io.plastique.main.MainPage
import io.plastique.util.Size
import io.reactivex.android.schedulers.AndroidSchedulers
class GalleryFragment : BaseFragment(R.layout.fragment_gallery),
MainPage,
ScrollableToTop,
OnConfirmListener,
OnInputDialogResultListener {
private val viewModel: GalleryViewModel by viewModel()
private val navigator: GalleryNavigator get() = viewModel.navigator
private lateinit var refreshLayout: SwipeRefreshLayout
private lateinit var emptyView: EmptyView
private lateinit var adapter: GalleryAdapter
private lateinit var galleryView: RecyclerView
private lateinit var contentStateController: ContentStateController
private lateinit var progressDialogController: ProgressDialogController
private lateinit var snackbarController: SnackbarController
private lateinit var onScrollListener: EndlessScrollListener
override fun onAttach(context: Context) {
super.onAttach(context)
navigator.attach(navigationContext)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val displayMetrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
val folderGridParams = GridParamsCalculator.calculateGridParams(
width = displayMetrics.widthPixels,
minItemWidth = resources.getDimensionPixelSize(R.dimen.gallery_folder_min_width),
itemSpacing = resources.getDimensionPixelOffset(R.dimen.gallery_folder_spacing),
heightToWidthRatio = 0.75f)
val deviationGridParams = GridParamsCalculator.calculateGridParams(
width = displayMetrics.widthPixels,
minItemWidth = resources.getDimensionPixelSize(R.dimen.deviations_list_min_cell_size),
itemSpacing = resources.getDimensionPixelOffset(R.dimen.deviations_grid_spacing))
val imageLoader = ImageLoader.from(this)
adapter = GalleryAdapter(
imageLoader = imageLoader,
itemSizeCallback = GalleryItemSizeCallback(folderGridParams, deviationGridParams),
onFolderClick = { folderId, folderName -> navigator.openGalleryFolder(folderId, folderName) },
onFolderLongClick = { folder, itemView ->
showFolderPopupMenu(folder, itemView)
true
},
onDeviationClick = { deviationId -> navigator.openDeviation(deviationId) })
galleryView = view.findViewById(R.id.gallery)
galleryView.adapter = adapter
galleryView.layoutManager = FlexboxLayoutManager(context)
galleryView.disableChangeAnimations()
onScrollListener = EndlessScrollListener(LOAD_MORE_THRESHOLD_ROWS * deviationGridParams.columnCount) { viewModel.dispatch(LoadMoreEvent) }
galleryView.addOnScrollListener(onScrollListener)
createPreloader(imageLoader, adapter, folderGridParams, deviationGridParams)
.subscribeToLifecycle(lifecycle)
.attach(galleryView)
refreshLayout = view.findViewById(R.id.refresh)
refreshLayout.setOnRefreshListener { viewModel.dispatch(RefreshEvent) }
emptyView = view.findViewById(android.R.id.empty)
emptyView.onButtonClick = { viewModel.dispatch(RetryClickEvent) }
contentStateController = ContentStateController(this, R.id.refresh, android.R.id.progress, android.R.id.empty)
progressDialogController = ProgressDialogController(requireContext(), childFragmentManager)
snackbarController = SnackbarController(this, refreshLayout)
snackbarController.onActionClick = { actionData -> viewModel.dispatch(UndoDeleteFolderEvent(actionData as String)) }
snackbarController.onSnackbarShown = { viewModel.dispatch(SnackbarShownEvent) }
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val username = arguments?.getString(ARG_USERNAME)
viewModel.init(username)
viewModel.state
.pairwiseWithPrevious()
.map { it + calculateDiff(it.second?.listState?.items, it.first.listState.items) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe { renderState(it.first, it.third) }
.disposeOnDestroy()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_gallery, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.gallery_action_create_folder -> {
showCreateFolderDialog()
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onConfirm(dialog: ConfirmationDialogFragment) {
when (dialog.tag) {
DIALOG_DELETE_FOLDER -> {
val folderId = dialog.requireArguments().getString(ARG_DIALOG_FOLDER_ID)!!
val folderName = dialog.requireArguments().getString(ARG_DIALOG_FOLDER_NAME)!!
viewModel.dispatch(DeleteFolderEvent(folderId, folderName))
}
}
}
override fun onInputDialogResult(dialog: InputDialogFragment, text: String) {
when (dialog.tag) {
DIALOG_CREATE_FOLDER -> viewModel.dispatch(CreateFolderEvent(text.trim()))
}
}
private fun renderState(state: GalleryViewState, listUpdateData: ListUpdateData<ListItem>) {
setHasOptionsMenu(state.showMenu)
contentStateController.state = state.contentState
emptyView.state = state.emptyState
listUpdateData.applyTo(adapter)
onScrollListener.isEnabled = state.listState.isPagingEnabled
refreshLayout.isRefreshing = state.listState.isRefreshing
progressDialogController.isShown = state.showProgressDialog
state.snackbarState?.let(snackbarController::showSnackbar)
}
private fun showFolderPopupMenu(folder: Folder, itemView: View) {
if (!folder.isDeletable) return
val popup = PopupMenu(requireContext(), itemView)
popup.inflate(R.menu.gallery_folder_popup)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.gallery_action_delete_folder -> {
if (folder.isNotEmpty) {
showDeleteFolderDialog(folder)
} else {
viewModel.dispatch(DeleteFolderEvent(folder.id.id, folder.name))
}
true
}
else -> false
}
}
popup.show()
}
private fun showCreateFolderDialog() {
val dialog = childFragmentManager.fragmentFactory.instantiate<InputDialogFragment>(requireContext(), args = InputDialogFragment.newArgs(
title = R.string.gallery_action_create_folder,
hint = R.string.gallery_folder_name_hint,
positiveButton = R.string.gallery_button_create,
maxLength = FOLDER_NAME_MAX_LENGTH))
dialog.show(childFragmentManager, DIALOG_CREATE_FOLDER)
}
private fun showDeleteFolderDialog(folder: Folder) {
val dialog = childFragmentManager.fragmentFactory.instantiate<ConfirmationDialogFragment>(requireContext(), args = ConfirmationDialogFragment.newArgs(
titleId = R.string.gallery_dialog_delete_folder_title,
message = HtmlCompat.fromHtml(getString(R.string.gallery_dialog_delete_folder_message, folder.name.htmlEncode(),
resources.getQuantityString(R.plurals.common_deviations, folder.size, folder.size)), 0),
positiveButtonTextId = R.string.common_button_delete,
negativeButtonTextInt = R.string.common_button_cancel
).apply {
putString(ARG_DIALOG_FOLDER_ID, folder.id.id)
putString(ARG_DIALOG_FOLDER_NAME, folder.name)
})
dialog.show(childFragmentManager, DIALOG_DELETE_FOLDER)
}
private fun createPreloader(
imageLoader: ImageLoader,
adapter: GalleryAdapter,
folderGridParams: GridParams,
deviationsGridParams: GridParams
): ListPreloader {
val callback = ListPreloader.Callback { position, preloader ->
when (val item = adapter.items[position]) {
is FolderItem -> {
item.folder.thumbnailUrl?.let { thumbnailUrl ->
val itemSize = folderGridParams.getItemSize(item.index)
val request = imageLoader.load(thumbnailUrl)
.params {
transforms += TransformType.CenterCrop
}
.createPreloadRequest()
preloader.preload(request, itemSize.width, itemSize.height)
}
}
is ImageDeviationItem -> {
val itemSize = deviationsGridParams.getItemSize(item.index)
val image = ImageHelper.chooseThumbnail(item.thumbnails, itemSize.width)
val request = imageLoader.load(image.url)
.params {
cacheSource = true
}
.createPreloadRequest()
preloader.preload(request, itemSize.width, itemSize.height)
}
}
}
return ListPreloader(imageLoader.glide, callback, MAX_PRELOAD_ROWS * deviationsGridParams.columnCount)
}
override fun getTitle(): Int = R.string.gallery_title
override fun createAppBarViews(parent: ExpandableToolbarLayout) {
}
override fun scrollToTop() {
galleryView.scrollToPosition(0)
}
override fun injectDependencies() {
getComponent<GalleryFragmentComponent>().inject(this)
}
private class GalleryItemSizeCallback(private val folderParams: GridParams, private val deviationParams: GridParams) : ItemSizeCallback {
override fun getColumnCount(item: IndexedItem): Int = when (item) {
is FolderItem -> folderParams.columnCount
is DeviationItem -> deviationParams.columnCount
else -> throw IllegalArgumentException("Unexpected item ${item.javaClass}")
}
override fun getItemSize(item: IndexedItem): Size = when (item) {
is FolderItem -> folderParams.getItemSize(item.index)
is DeviationItem -> deviationParams.getItemSize(item.index)
else -> throw IllegalArgumentException("Unexpected item ${item.javaClass}")
}
}
companion object {
private const val ARG_USERNAME = "username"
private const val ARG_DIALOG_FOLDER_ID = "folder_id"
private const val ARG_DIALOG_FOLDER_NAME = "folder_name"
private const val DIALOG_CREATE_FOLDER = "dialog.create_folder"
private const val DIALOG_DELETE_FOLDER = "dialog.delete_folder"
private const val FOLDER_NAME_MAX_LENGTH = 50
private const val LOAD_MORE_THRESHOLD_ROWS = 4
private const val MAX_PRELOAD_ROWS = 4
fun newArgs(username: String? = null): Bundle {
return Bundle().apply {
putString(ARG_USERNAME, username)
}
}
}
}
| 0 | null | 0 | 0 | 8497a205808c89b775c3d1fdc75f05ff010e206e | 13,978 | plastique | Apache License 2.0 |
spring-boot-oauth2-react-client/spring-boot-oauth2-react-client-backend/src/main/kotlin/com/onlyteo/sandbox/service/GreetingService.kt | onlyteo | 692,402,826 | false | {"Kotlin": 89389, "HTML": 23401, "TypeScript": 14871, "CSS": 3610} | package com.onlyteo.sandbox.service
import com.onlyteo.sandbox.model.Greeting
import com.onlyteo.sandbox.model.Person
import com.onlyteo.sandbox.model.toGreeting
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
class GreetingService {
private val logger: Logger = LoggerFactory.getLogger(GreetingService::class.java)
fun getGreeting(person: Person): Greeting {
logger.info("Returning greeting to {}", person.name)
return person.toGreeting()
}
} | 0 | Kotlin | 0 | 0 | 300ecaed463cff610899f4845420966b2231571b | 537 | spring-boot-sandbox | Apache License 2.0 |
app/src/main/java/com/mouredev/weeklychallenge2022/Challenge37.kt | mouredev | 440,606,306 | false | {"Kotlin": 111136} | package com.mouredev.weeklychallenge2022
import java.text.SimpleDateFormat
import java.util.*
/*
* Reto #37
* LOS LANZAMIENTOS DE "THE LEGEND OF ZELDA"
* Fecha publicación enunciado: 14/09/22
* Fecha publicación resolución: 19/09/22
* Dificultad: MEDIA
*
* Enunciado: ¡Han anunciado un nuevo "The Legend of Zelda"! Se llamará "Tears of the Kingdom"
* y se lanzará el 12 de mayo de 2023.
* Pero, ¿recuerdas cuánto tiempo ha pasado entre los distintos "The Legend of Zelda" de la historia?
* Crea un programa que calcule cuántos años y días hay entre 2 juegos de Zelda que tú selecciones.
* - Debes buscar cada uno de los títulos y su día de lanzamiento (si no encuentras el día exacto
* puedes usar el mes, o incluso inventártelo)
*
* Información adicional:
* - Usa el canal de nuestro Discord (https://mouredev.com/discord) "🔁reto-semanal"
* para preguntas, dudas o prestar ayuda a la comunidad.
* - Tienes toda la información sobre los retos semanales en
* https://retosdeprogramacion.com/semanales2022.
*
*/
fun main() {
println(ZeldaGame.THE_LEGEND_OF_ZELDA.timeBetweenRelease(ZeldaGame.TEARS_OF_THE_KINGDOM))
println(ZeldaGame.TEARS_OF_THE_KINGDOM.timeBetweenRelease(ZeldaGame.THE_LEGEND_OF_ZELDA))
println(ZeldaGame.THE_LEGEND_OF_ZELDA.timeBetweenRelease(ZeldaGame.THE_ADVENTURE_OF_LINK))
println(ZeldaGame.THE_ADVENTURE_OF_LINK.timeBetweenRelease(ZeldaGame.THE_LEGEND_OF_ZELDA))
println(ZeldaGame.THE_LEGEND_OF_ZELDA.timeBetweenRelease(ZeldaGame.THE_LEGEND_OF_ZELDA))
println(ZeldaGame.ORACLE_OF_SEASONS.timeBetweenRelease(ZeldaGame.ORACLE_OF_AGES))
}
enum class ZeldaGame(val title: String) {
THE_LEGEND_OF_ZELDA("The Legend of Zelda"),
THE_ADVENTURE_OF_LINK("Zelda II: The Adventure of Link"),
A_LINK_TO_THE_PAST("The Legend of Zelda: A Link to the Past"),
LINKS_AWAKENING("The Legend of Zelda: Link's Awakening"),
OCARINA_OF_TIME("The Legend of Zelda: Ocarina of Time"),
MAJORAS_MASK("Zelda: Majora's Mask"),
ORACLE_OF_SEASONS("The Legend of Zelda: Oracle of Seasons"),
ORACLE_OF_AGES("The Legend of Zelda: Oracle of Ages"),
FOUR_SWORDS("The Legend of Zelda: Four Swords"),
THE_WIND_WAKER("The Legend of Zelda: The Wind Waker"),
FOUR_SWORDS_ADVENTURES("The Legend of Zelda: Four Swords Adventures"),
THE_MINISH_CUP("The Legend of Zelda: The Minish Cap"),
TWILIGHT_PRINCES("The Legend of Zelda: Twilight Princess"),
PHANTHOM_HOURGLASS("The Legend of Zelda: Phantom Hourglass"),
SPIRIT_TRACKS("The Legend of Zelda: Spirit Tracks"),
SKYWARD_SWORD("The Legend of Zelda: Skyward Sword"),
A_LINK_BETWEEN_WORLDS("The Legend of Zelda: A Link Between Worlds"),
TRI_FORCE_HEROES("The Legend of Zelda: Tri Force Heroes"),
BREATH_OF_THE_WILD("The Legend of Zelda: Breath of the Wild"),
TEARS_OF_THE_KINGDOM("The Legend of Zelda: Tears of the Kingdom");
private var releaseDate: Date? = null
get() {
val formatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
return when (this) {
THE_LEGEND_OF_ZELDA -> formatter.parse("21/02/1986")
THE_ADVENTURE_OF_LINK -> formatter.parse("14/01/1987")
A_LINK_TO_THE_PAST -> formatter.parse("21/11/1991")
LINKS_AWAKENING -> formatter.parse("06/06/1993")
OCARINA_OF_TIME -> formatter.parse("21/11/1998")
MAJORAS_MASK -> formatter.parse("27/04/2000")
ORACLE_OF_SEASONS, ORACLE_OF_AGES -> formatter.parse("27/02/2001")
FOUR_SWORDS -> formatter.parse("03/12/2002")
THE_WIND_WAKER -> formatter.parse("13/12/2002")
FOUR_SWORDS_ADVENTURES -> formatter.parse("18/03/2004")
THE_MINISH_CUP -> formatter.parse("04/11/2004")
TWILIGHT_PRINCES -> formatter.parse("19/11/2006")
PHANTHOM_HOURGLASS -> formatter.parse("23/06/2007")
SPIRIT_TRACKS -> formatter.parse("07/12/2009")
SKYWARD_SWORD -> formatter.parse("18/11/2011")
A_LINK_BETWEEN_WORLDS -> formatter.parse("23/11/2013")
TRI_FORCE_HEROES -> formatter.parse("11/10/2015")
BREATH_OF_THE_WILD -> formatter.parse("03/03/2017")
TEARS_OF_THE_KINGDOM -> formatter.parse("12/05/2023")
}
}
fun timeBetweenRelease(game: ZeldaGame): String {
if (this == game) {
return "Se está intentando comparar el mismo juego"
}
this.releaseDate?.let { currentReleaseDate ->
game.releaseDate?.let { newReleaseDate ->
val startDate = if (currentReleaseDate < newReleaseDate) currentReleaseDate else newReleaseDate
val endDate = if (newReleaseDate > currentReleaseDate) newReleaseDate else currentReleaseDate
val startCalendar = Calendar.getInstance()
startCalendar.time = startDate
val startReleaseYear = startCalendar.get(Calendar.YEAR)
val endCalendar = Calendar.getInstance()
endCalendar.time = endDate
val endReleaseYear = endCalendar.get(Calendar.YEAR)
var years = endReleaseYear - startReleaseYear
startCalendar.set(Calendar.YEAR, endReleaseYear)
// Nos encontramos con un día y un mes en la fecha inicial posterior a la final
if (startCalendar.timeInMillis > endCalendar.timeInMillis) {
startCalendar.set(Calendar.YEAR, endReleaseYear - 1)
years -= 1
}
val startMillis = if (startCalendar.timeInMillis < endCalendar.timeInMillis) startCalendar.timeInMillis else endCalendar.timeInMillis
val endMillis = if (endCalendar.timeInMillis > startCalendar.timeInMillis) endCalendar.timeInMillis else startCalendar.timeInMillis
val days = (endMillis - startMillis) / (60 * 60 * 24 * 1000)
return "Entre la fecha de lanzamiento de ${this.title} y ${game.title} hay $years años y $days días"
}
}
return "No se ha podido calcular el tiempo entre fechas de lanzamiento"
}
} | 791 | Kotlin | 1068 | 2,043 | 211814959bd8e98566b2440e3e4237dd210a74f2 | 6,234 | Weekly-Challenge-2022-Kotlin | Apache License 2.0 |
src/jsMain/kotlin/materialui/toggleButton.kt | lucgirardin | 290,413,324 | true | {"Kotlin": 1134726, "C++": 479123, "JavaScript": 365308, "GLSL": 120375, "C": 100546, "CMake": 25514, "HTML": 10796, "CSS": 10322, "Shell": 663} | package materialui
import kotlinext.js.jsObject
import kotlinx.html.BUTTON
import kotlinx.html.Tag
import kotlinx.html.TagConsumer
import kotlinx.html.attributes.Attribute
import kotlinx.html.attributes.BooleanAttribute
import kotlinx.html.attributes.TickerAttribute
import materialui.components.button.enums.ButtonStyle
import materialui.components.buttonbase.ButtonBaseProps
import react.RBuilder
import react.RClass
import react.ReactElement
@JsModule("@material-ui/lab/ToggleButton")
private external val toggleButtonModule: dynamic
external interface ToggleButtonProps : ButtonBaseProps {
var label: ReactElement?
val selected: Boolean?
}
@Suppress("UnsafeCastFromDynamic")
private val toggleButtonComponent: RClass<ToggleButtonProps> = toggleButtonModule.default
fun RBuilder.toggleButton(vararg classMap: Pair<ButtonStyle, String>, block: ToggleButtonElementBuilder<BUTTON>.() -> Unit)
= child(ToggleButtonElementBuilder(toggleButtonComponent, classMap.toList()) { BUTTON(mapOf(), it) }.apply(block).create())
fun RBuilder.toggleButton(
attrs: ToggleButtonProps.() -> Unit,
children: RBuilder.() -> Any
): ReactElement =
child(toggleButtonComponent, jsObject<ToggleButtonProps>().apply { attrs() },
RBuilder().apply { children() }.childList)
fun <T : Tag> RBuilder.toggleButton(
vararg classMap: Pair<ToggleButtonStyle, String>,
factory: (TagConsumer<Unit>) -> T,
block: ToggleButtonElementBuilder<T>.() -> Unit
) = child(ToggleButtonElementBuilder(toggleButtonComponent, classMap.toList(), factory).apply(block).create())
internal val attributeBooleanBoolean : Attribute<Boolean> = BooleanAttribute()
val attributeBooleanTicker : Attribute<Boolean> = TickerAttribute()
var BUTTON.selected : Boolean
get() = attributeBooleanBoolean.get(this, "selected")
set(newValue) = attributeBooleanBoolean.set(this, "selected", newValue)
@Suppress("EnumEntryName")
enum class ToggleButtonStyle {
root,
expanded,
group,
content,
iconContainer,
label
} | 0 | null | 0 | 0 | 80865b7141d4ab8fcaafcc1c58402afb02561ecc | 2,035 | sparklemotion | MIT License |
src/jsMain/kotlin/materialui/toggleButton.kt | lucgirardin | 290,413,324 | true | {"Kotlin": 1134726, "C++": 479123, "JavaScript": 365308, "GLSL": 120375, "C": 100546, "CMake": 25514, "HTML": 10796, "CSS": 10322, "Shell": 663} | package materialui
import kotlinext.js.jsObject
import kotlinx.html.BUTTON
import kotlinx.html.Tag
import kotlinx.html.TagConsumer
import kotlinx.html.attributes.Attribute
import kotlinx.html.attributes.BooleanAttribute
import kotlinx.html.attributes.TickerAttribute
import materialui.components.button.enums.ButtonStyle
import materialui.components.buttonbase.ButtonBaseProps
import react.RBuilder
import react.RClass
import react.ReactElement
@JsModule("@material-ui/lab/ToggleButton")
private external val toggleButtonModule: dynamic
external interface ToggleButtonProps : ButtonBaseProps {
var label: ReactElement?
val selected: Boolean?
}
@Suppress("UnsafeCastFromDynamic")
private val toggleButtonComponent: RClass<ToggleButtonProps> = toggleButtonModule.default
fun RBuilder.toggleButton(vararg classMap: Pair<ButtonStyle, String>, block: ToggleButtonElementBuilder<BUTTON>.() -> Unit)
= child(ToggleButtonElementBuilder(toggleButtonComponent, classMap.toList()) { BUTTON(mapOf(), it) }.apply(block).create())
fun RBuilder.toggleButton(
attrs: ToggleButtonProps.() -> Unit,
children: RBuilder.() -> Any
): ReactElement =
child(toggleButtonComponent, jsObject<ToggleButtonProps>().apply { attrs() },
RBuilder().apply { children() }.childList)
fun <T : Tag> RBuilder.toggleButton(
vararg classMap: Pair<ToggleButtonStyle, String>,
factory: (TagConsumer<Unit>) -> T,
block: ToggleButtonElementBuilder<T>.() -> Unit
) = child(ToggleButtonElementBuilder(toggleButtonComponent, classMap.toList(), factory).apply(block).create())
internal val attributeBooleanBoolean : Attribute<Boolean> = BooleanAttribute()
val attributeBooleanTicker : Attribute<Boolean> = TickerAttribute()
var BUTTON.selected : Boolean
get() = attributeBooleanBoolean.get(this, "selected")
set(newValue) = attributeBooleanBoolean.set(this, "selected", newValue)
@Suppress("EnumEntryName")
enum class ToggleButtonStyle {
root,
expanded,
group,
content,
iconContainer,
label
} | 0 | null | 0 | 0 | 80865b7141d4ab8fcaafcc1c58402afb02561ecc | 2,035 | sparklemotion | MIT License |
plugin/src/test/kotlin/dev/aga/gradle/versioncatalogs/mock/ArtifactCollection.kt | austinarbor | 679,523,691 | false | {"Kotlin": 83528} | package dev.aga.gradle.versioncatalogs.mock
import org.gradle.api.artifacts.ArtifactCollection
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import org.gradle.api.file.FileCollection
import org.gradle.api.provider.Provider
internal class ArtifactCollection(val result: ResolvedArtifactResult) : ArtifactCollection {
override fun iterator(): MutableIterator<ResolvedArtifactResult> {
return mutableListOf(result).iterator()
}
override fun getArtifactFiles(): FileCollection {
TODO("Not yet implemented")
}
override fun getArtifacts(): MutableSet<ResolvedArtifactResult> {
return mutableSetOf(result)
}
override fun getResolvedArtifacts(): Provider<MutableSet<ResolvedArtifactResult>> {
TODO("Not yet implemented")
}
override fun getFailures(): MutableCollection<Throwable> {
TODO("Not yet implemented")
}
}
| 3 | Kotlin | 0 | 8 | 2a1a03df12676ab4adaa4c4d793961d49be0dd32 | 908 | version-catalog-generator | Apache License 2.0 |
app/src/main/java/uk/ac/aber/dcs/cs31620/faa/ui/cats/CatsScreen.kt | chriswloftus | 575,770,254 | false | {"Kotlin": 74196} | package uk.ac.aber.dcs.cs31620.faa.ui.cats
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import kotlinx.coroutines.launch
import uk.ac.aber.dcs.cs31620.faa.R
import uk.ac.aber.dcs.cs31620.faa.model.Cat
import uk.ac.aber.dcs.cs31620.faa.model.CatSearch
import uk.ac.aber.dcs.cs31620.faa.model.CatsViewModel
import uk.ac.aber.dcs.cs31620.faa.ui.components.CatCard
import uk.ac.aber.dcs.cs31620.faa.ui.components.DefaultSnackbar
import uk.ac.aber.dcs.cs31620.faa.ui.components.SearchArea
import uk.ac.aber.dcs.cs31620.faa.ui.components.TopLevelScaffold
import uk.ac.aber.dcs.cs31620.faa.ui.theme.FAATheme
/**
* Represents the cats screen. For this version we have a search area that allows us to
* choose cat breed, cat age, cat gender and how far we are willing to travel.
* These are all OutlinedButtons sitting on a Card. The breed, age and gender are
* implemented using dropdown menus from data hard coded in strings.xml.
* The distance to travel is implemented an AlertDialog that has a Slider to
* control how far we want to search.
* There is also a Floating Action Button that currently only displays a
* Snackbar when tapped. Eventually, the FAB will enable the adding of a new
* Cat.
* The search area displays a scrollable grid of cats where the data comes from a
* ViewModel tied to a repository
* @author Chris Loftus
*/
@Composable
fun CatsScreenTopLevel(
navController: NavHostController,
catsViewModel: CatsViewModel = viewModel()
) {
val catList by catsViewModel.catList.observeAsState(listOf())
CatsScreen(
catsList = catList,
catSearch = catsViewModel.catSearch,
updateSearchCriteria = { catSearch ->
catsViewModel.updateCatSearch(catSearch)
},
navController = navController
)
}
@Composable
fun CatsScreen(
catsList: List<Cat> = listOf(),
catSearch: CatSearch = CatSearch(),
updateSearchCriteria: (CatSearch) -> Unit = {},
navController: NavHostController
) {
val coroutineScope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
TopLevelScaffold(
navController = navController,
floatingActionButton = {
FloatingActionButton(
onClick = {
coroutineScope.launch {
snackbarHostState.showSnackbar(
message = "Add cat",
actionLabel = "Undo"
)
}
},
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = stringResource(R.string.add_cat)
)
}
},
snackbarContent = { data ->
DefaultSnackbar(
data = data,
modifier = Modifier.padding(bottom = 4.dp),
onDismiss = {
// An opportunity to do work such as undoing the
// add cat operation. We'll just dismiss the snackbar
data.dismiss()
}
)
},
coroutineScope = coroutineScope,
snackbarHostState = snackbarHostState
)
{ innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
) {
val breedList = stringArrayResource(id = R.array.breed_array).toList()
val genderList = stringArrayResource(id = R.array.gender_array).toList()
val ageList = stringArrayResource(id = R.array.age_range_array).toList()
val state = rememberLazyGridState() // new
val context = LocalContext.current
SearchArea(
catSearch = catSearch,
breedList = breedList,
genderList = genderList,
ageList = ageList
) {
updateSearchCriteria(it)
}
LazyVerticalGrid(
columns = GridCells.Fixed(2),
state = state, // new
contentPadding = PaddingValues(bottom = 64.dp), // Add some space at the end so that FAB not hidden
modifier = Modifier
.weight(1f)
.padding(start = 4.dp)
) {
items(catsList) {
CatCard(
cat = it,
modifier = Modifier
.padding(end = 4.dp, top = 4.dp),
selectAction = { cat ->
Toast.makeText(context, "Selected ${cat.name}", Toast.LENGTH_LONG)
.show()
},
deleteAction = { cat ->
Toast.makeText(context, "Delete ${cat.name}", Toast.LENGTH_LONG).show()
}
)
}
}
}
}
}
@Preview
@Composable
private fun CatsScreenPreview() {
val navController = rememberNavController()
FAATheme(dynamicColor = false) {
CatsScreen(navController = navController)
}
} | 0 | Kotlin | 0 | 0 | 8f2e5255d5dd979030ecf6441448b4f88b95b42e | 6,520 | feline-adoption-agency-v9 | MIT License |
kmath-functions/src/commonMain/kotlin/space/kscience/kmath/integration/UnivariateIntegrand.kt | therealansh | 373,284,570 | true | {"Kotlin": 1071813, "ANTLR": 887} | /*
* Copyright 2018-2021 KMath contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package space.kscience.kmath.integration
import space.kscience.kmath.misc.UnstableKMathAPI
import kotlin.jvm.JvmInline
import kotlin.reflect.KClass
public class UnivariateIntegrand<T : Any> internal constructor(
private val features: Map<KClass<*>, IntegrandFeature>,
public val function: (Double) -> T,
) : Integrand {
@Suppress("UNCHECKED_CAST")
override fun <T : IntegrandFeature> getFeature(type: KClass<T>): T? = features[type] as? T
public operator fun <F : IntegrandFeature> plus(pair: Pair<KClass<out F>, F>): UnivariateIntegrand<T> =
UnivariateIntegrand(features + pair, function)
public operator fun <F : IntegrandFeature> plus(feature: F): UnivariateIntegrand<T> =
plus(feature::class to feature)
}
@Suppress("FunctionName")
public fun <T : Any> UnivariateIntegrand(
function: (Double) -> T,
vararg features: IntegrandFeature,
): UnivariateIntegrand<T> = UnivariateIntegrand(features.associateBy { it::class }, function)
public typealias UnivariateIntegrator<T> = Integrator<UnivariateIntegrand<T>>
@JvmInline
public value class IntegrationRange(public val range: ClosedRange<Double>) : IntegrandFeature
public val <T : Any> UnivariateIntegrand<T>.value: T? get() = getFeature<IntegrandValue<T>>()?.value
/**
* A shortcut method to integrate a [function] in [range] with additional [features].
* The [function] is placed in the end position to allow passing a lambda.
*/
@UnstableKMathAPI
public fun UnivariateIntegrator<Double>.integrate(
range: ClosedRange<Double>,
vararg features: IntegrandFeature,
function: (Double) -> Double,
): Double = integrate(
UnivariateIntegrand(function, IntegrationRange(range), *features)
).value ?: error("Unexpected: no value after integration.")
/**
* A shortcut method to integrate a [function] in [range] with additional [features].
* The [function] is placed in the end position to allow passing a lambda.
*/
@UnstableKMathAPI
public fun UnivariateIntegrator<Double>.integrate(
range: ClosedRange<Double>,
function: (Double) -> Double,
featureBuilder: (MutableList<IntegrandFeature>.() -> Unit) = {},
): Double {
//TODO use dedicated feature builder class instead or add extensions to MutableList<IntegrandFeature>
val features = buildList {
featureBuilder()
add(IntegrationRange(range))
}
return integrate(
UnivariateIntegrand(function, *features.toTypedArray())
).value ?: error("Unexpected: no value after integration.")
}
| 0 | null | 0 | 0 | 4065466be339017780b0ac4b98a9eda2cc2378e4 | 2,680 | kmath | Apache License 2.0 |
src/test/kotlin/com/personio/synthetics/config/ConfigurationLoaderTest.kt | personio | 527,513,649 | false | {"Kotlin": 288527} | package com.personio.synthetics.config
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class ConfigurationLoaderTest {
@Test
fun `loadConfiguration loads the dd api key from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals("apiKey", Config.testConfig.credentials.ddApiKey)
}
@Test
fun `loadConfiguration loads the dd app key from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals("appKey", Config.testConfig.credentials.ddAppKey)
}
@Test
fun `loadConfiguration loads the datadog credentials aws arn from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals("awsArn", Config.testConfig.credentials.datadogCredentialsAwsArn)
}
@Test
fun `loadConfiguration loads the aws region from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals("eu-central-1", Config.testConfig.credentials.awsRegion)
}
@Test
fun `loadConfiguration loads the datadog api host from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals("datadoghq.eu", Config.testConfig.datadogApiHost)
}
@Test
fun `loadConfiguration loads the test frequency from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals(1, Config.testConfig.defaults.testFrequency)
}
@Test
fun `loadConfiguration loads the min failure duration from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals(2, Config.testConfig.defaults.minFailureDuration)
}
@Test
fun `loadConfiguration loads the min location failed from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals(3, Config.testConfig.defaults.minLocationFailed)
}
@Test
fun `loadConfiguration loads the retry count from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals(4, Config.testConfig.defaults.retryCount)
}
@Test
fun `loadConfiguration loads the retry interval from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals(5.0, Config.testConfig.defaults.retryInterval)
}
@Test
fun `loadConfiguration loads the run locations from the config file into the config object`() {
loadConfiguration("config-unit-test.yaml")
assertEquals(listOf("aws:eu-central-1"), Config.testConfig.defaults.runLocations)
}
}
| 1 | Kotlin | 4 | 24 | 032e36834a37014c67aa7a14201ed871f33ea46b | 2,845 | datadog-synthetic-test-support | MIT License |
spring-app/src/main/kotlin/pl/starchasers/up/data/dto/VerifyUploadSizeResponseDTO.kt | Starchasers | 255,645,145 | false | null | package pl.starchasers.up.data.dto
data class VerifyUploadSizeResponseDTO(
/**
* True, if file can be uploaded
*/
val valid: Boolean,
/**
* Maximum allowed upload size in KB
*/
val maxUploadSize: Long
)
| 26 | Kotlin | 0 | 9 | 90759d835f3be8fbcb9403dd20ca0e13f18bcfbc | 241 | up | MIT License |
kotlin-electron/src/jsMain/generated/electron/WillNavigateEvent.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron
typealias WillNavigateEvent = electron.core.WillNavigateEvent
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 134 | kotlin-wrappers | Apache License 2.0 |
Tutorial1-1Basics/src/main/java/com/smarttoolfactory/tutorial1_1basics/chapter6_graphics/colorpicker/ColorPickerWheel.kt | SmartToolFactory | 326,400,374 | false | {"Kotlin": 2849459} | package com.smarttoolfactory.tutorial1_1basics.chapter6_graphics.colorpicker
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.smarttoolfactory.tutorial1_1basics.chapter5_gesture.gesture.pointerMotionEvents
import com.smarttoolfactory.tutorial1_1basics.ui.gradientColors
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.roundToInt
import kotlin.math.sqrt
@Composable
fun ColorPickerWheel(
modifier: Modifier = Modifier,
selectionRadius: Dp = (-1).dp,
onChange: (Int) -> Unit
) {
BoxWithConstraints(modifier) {
val density = LocalDensity.current.density
// Check if user touches between the valid area of circle
var isTouched by remember { mutableStateOf(false) }
// Angle from center is required to get Hue which is between 0-360
var angle by remember { mutableStateOf(0) }
// Center position of color picker
var center by remember { mutableStateOf(Offset.Zero) }
var radiusOuter by remember { mutableStateOf(0f) }
var radiusInner by remember { mutableStateOf(0f) }
/**
* Circle selector radius for setting [angle] which sets hue
*/
val selectorRadius =
if (selectionRadius > 0.dp) selectionRadius.value * density else radiusInner * 2 * .04f
val colorPickerModifier = modifier
.clipToBounds()
.pointerMotionEvents(
onDown = {
val position = it.position
// Distance from center to touch point
val distance = calculateDistanceFromCenter(center, position)
// if distance is between inner and outer radius then we touched valid area
isTouched = (distance in radiusInner..radiusOuter)
if (isTouched) {
angle = calculateAngleFomLocalCoordinates(center, position)
onChange(angle)
}
},
onMove = {
if (isTouched) {
val position = it.position
angle = calculateAngleFomLocalCoordinates(center, position)
onChange(angle)
}
},
onUp = {
isTouched = false
},
delayAfterDownInMillis = 20
)
Canvas(modifier = colorPickerModifier) {
val canvasWidth = this.size.width
val canvasHeight = this.size.height
val cX = canvasWidth / 2
val cY = canvasHeight / 2
val canvasRadius = canvasWidth.coerceAtMost(canvasHeight) / 2f
center = Offset(cX, cY)
radiusOuter = canvasRadius * .9f
radiusInner = canvasRadius * .65f
val strokeWidth = (radiusOuter - radiusInner)
drawCircle(
brush = Brush.sweepGradient(colors = gradientColors, center = center),
radius = radiusInner + strokeWidth / 2,
style = Stroke(
width = strokeWidth
)
)
// Stroke draws half in and half out of the current radius.
// with 200 radius 20 stroke width starts from 190 and ends at 210
drawCircle(Color.Black, radiusInner - 7f, style = Stroke(width = 14f))
drawCircle(Color.Black, radiusOuter + 7f, style = Stroke(width = 14f))
// rotate selection circle based on hue value
withTransform(
{
rotate(degrees = -angle.toFloat())
}
) {
// draw hue selection circle
drawCircle(
Color.White,
radius = selectorRadius,
center = Offset(center.x + radiusInner + strokeWidth / 2f, center.y),
style = Stroke(width = selectorRadius / 2)
)
}
}
}
}
/**
* Calculate distance from center to touch position
*/
private fun calculateDistanceFromCenter(center: Offset, position: Offset): Float {
val dy = center.y - position.y
val dx = position.x - center.x
return sqrt(dx * dx + dy * dy)
}
/**
* Get angle between 0 and 360 degrees from local coordinate system of a composable
* Local coordinates of touch are equal to Composable position when in bounds, when
* touch position is above this composable it returns minus in y axis.
*/
private fun calculateAngleFomLocalCoordinates(center: Offset, position: Offset): Int {
if (center == Offset.Unspecified || position == Offset.Unspecified) return -1
val dy = center.y - position.y
val dx = position.x - center.x
return ((360 + ((atan2(dy, dx) * 180 / PI))) % 360).roundToInt()
}
/**
* Get angle between 0 and 360 degrees using coordinates of the root composable. Root composable
* needs to cover whole screen to return correct results.
*/
private fun calculateAngleFromRootCoordinates(center: Offset, position: Offset): Int {
if (center == Offset.Unspecified || position == Offset.Unspecified) return -1
val dy = (position.y - center.y)
val dx = (center.x - position.x)
return ((360 + ((atan2(dy, dx) * 180 / PI))) % 360).roundToInt()
}
| 4 | Kotlin | 312 | 3,006 | efea98b63e63a85b80f7dc1bd4ca6d769e35905d | 5,865 | Jetpack-Compose-Tutorials | Apache License 2.0 |
Camera/app/src/main/java/com/example/camera/ShowingSavedImages.kt | Advaitgaur004 | 764,270,744 | false | {"Kotlin": 37189, "Python": 2421} | package com.example.camera
import android.content.Context
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Environment
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.camera.core.CameraSelector
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cameraswitch
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
@Composable
fun ImageListScreen(context : Context,
lam : () -> Unit
) {
var toShow by remember { mutableStateOf(false) }
if (toShow) {
BackHandler(onBack = { toShow = false })
}
IconButton(
onClick = {
toShow = !toShow
lam()
},
modifier = Modifier
.offset(250.dp, 778.dp)
) {
Icon(
imageVector = Icons.Default.Image,
contentDescription = "Switch camera",
tint = Color.White
)
}
if(toShow) {
val images = getSavedImages(context)
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.Black
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(text = "Saved Images")
Spacer(modifier = Modifier.height(16.dp))
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
if (images.isEmpty()) {
// Text(text = "Oh ho No Photo Captured")
} else {
items(images) {
SavedImageItem(image = it)
}
}
}
}
}
}
}
@Composable
fun SavedImageItem(image: ImageBitmap) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Image(
bitmap = image,
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f),
contentScale = ContentScale.Crop
)
}
}
fun getSavedImages(context: Context): List<ImageBitmap> {
val images = mutableListOf<ImageBitmap>()
val directory = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Environment.DIRECTORY_PICTURES
} else {
Environment.DIRECTORY_DCIM
}
val directoryPath = Environment.getExternalStoragePublicDirectory(directory)
val files = directoryPath.listFiles()
files?.forEach { file ->
if (file.isFile && file.extension == "jpg") {
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
bitmap?.let {
images.add(it.asImageBitmap())
}
}
}
return images
} | 0 | Kotlin | 2 | 0 | 6cce4225a4a068dc79c10b097ed075c1d44e45c8 | 4,423 | Auto-Capture-Selfie-with-Custom-Gesture | MIT License |
app/src/main/java/com/chatspring/appworkshop/CardAdapter.kt | goatpang | 642,752,766 | false | {"Kotlin": 134006} | package com.chatspring.appworkshop
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chatspring.R
/*
这段代码定义了一个RecyclerView的Adapter用于显示卡片列表。它做了以下工作:
1. 接收列表数据items和点击监听器listener
2. 实现OnItemClickListener接口,定义了onItemClick()点击方法
3. 在onCreateViewHolder()中使用LayoutInflater加载card_item布局,并返回ViewHolder
4. 在onBindViewHolder()中为每个列表项绑定数据,设置点击监听器调用onItemClick()
5. 获取列表总数getItemCount()
6. 定义内部ViewHolder类,找到布局中的视图并缓存
*/
//创建一个卡片适配器类,用于将数据模型类中的数据绑定到CardView布局中的视图。
class CardAdapter(private val items: List<CardData>, private val listener: OnItemClickListener) :
RecyclerView.Adapter<CardAdapter.ViewHolder>() {
interface OnItemClickListener {
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.card_app_workshop, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.icon.setImageResource(item.iconRes)
holder.title.text = item.title
holder.description.text = item.description
holder.itemView.setOnClickListener { listener.onItemClick(position) }
}
override fun getItemCount(): Int = items.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val icon: ImageView = itemView.findViewById(R.id.icon)
val title: TextView = itemView.findViewById(R.id.title)
val description: TextView = itemView.findViewById(R.id.description)
}
} | 0 | Kotlin | 1 | 1 | 23f41e7014704d6298d683b1904b884faddb1a8c | 1,756 | ChatSpring | Apache License 2.0 |
plugin/src/org/jetbrains/haskell/psi/TypeDeclaration.kt | CRogers | 20,376,614 | true | {"Kotlin": 200571, "Java": 100777, "Haskell": 4139} | package org.jetbrains.haskell.psi
import com.intellij.lang.ASTNode
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.haskell.parser.ElementFactory
/**
* Created by atsky on 4/11/14.
*/
public class TypeDeclaration(node : ASTNode) : Declaration(node) {
class object : ElementFactory {
override fun create(node: ASTNode) = TypeDeclaration(node)
}
fun getTypeName() : TypeName? {
val simpleType = findChildByClass(javaClass<SimpleType>())
return simpleType?.getNameElement()
}
override fun getDeclarationName(): String? {
val simpleType = findChildByClass(javaClass<SimpleType>())
return simpleType?.getNameElement()?.getText()
}
} | 0 | Kotlin | 0 | 0 | f4a452bd8865c4bc9785b22264e3fa4e8dc312f6 | 768 | haskell-idea-plugin | Apache License 2.0 |
src/main/java/network/xyo/sdkcorekotlin/hashing/basic/XyoBasicHashBase.kt | MichielCuijpers | 150,070,434 | true | {"Kotlin": 172008} | package network.xyo.sdkcorekotlin.hashing.basic
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import network.xyo.sdkcorekotlin.data.XyoByteArrayReader
import network.xyo.sdkcorekotlin.data.XyoObject
import network.xyo.sdkcorekotlin.hashing.XyoHash
import java.security.MessageDigest
/**
* A base class for fixed size hashes.
*
* @param hash, the created hash.
*/
abstract class XyoBasicHashBase (override val hash : ByteArray): XyoHash() {
override val sizeIdentifierSize: Int? = null
/**
* A base class for creating Standard Java hashes supported by MessageDigest.
*/
abstract class XyoBasicHashBaseProvider : XyoHashProvider() {
/**
* The MessageDigest instance key. e.g. "SHA-256"
*/
abstract val standardDigestKey : String
override val sizeOfBytesToGetSize: Int? = 0
override fun createHash (data: ByteArray) : Deferred<XyoHash> {
return async {
return@async object : XyoBasicHashBase(hash(data)) {
override val id: ByteArray
get() = byteArrayOf(major, minor)
}
}
}
private fun hash(data: ByteArray): ByteArray {
return MessageDigest.getInstance(standardDigestKey).digest(data)
}
override fun createFromPacked(byteArray: ByteArray): XyoObject {
val hash = XyoByteArrayReader(byteArray).read(0, byteArray.size)
return object : XyoBasicHashBase(hash) {
override val id: ByteArray
get() = byteArrayOf(major, minor)
}
}
}
} | 0 | Kotlin | 0 | 0 | de78c94aef53c12c3f98c2b22ceb360241f4e107 | 1,680 | sdk-core-kotlin | MIT License |
src/main/kotlin/HighwayToolsProcess.kt | Natan515 | 367,178,337 | true | {"Kotlin": 101147} | import baritone.api.process.IBaritoneProcess
import baritone.api.process.PathingCommand
import baritone.api.process.PathingCommandType
import com.lambda.client.util.math.CoordinateConverter.asString
/**
* @author Avanatiker
* @since 26/08/20
*/
object HighwayToolsProcess : IBaritoneProcess {
override fun isTemporary(): Boolean {
return true
}
override fun priority(): Double {
return 2.0
}
override fun onLostControl() {}
override fun displayName0(): String {
val lastTask = HighwayTools.lastTask
val processName = if (!HighwayTools.anonymizeStats) {
HighwayTools.goal?.goalPos?.asString()
?: lastTask?.toString()
?: "Thinking"
} else {
"Running"
}
return "HighwayTools: $processName"
}
override fun isActive(): Boolean {
return HighwayTools.isActive()
}
override fun onTick(p0: Boolean, p1: Boolean): PathingCommand {
return HighwayTools.goal?.let {
PathingCommand(it, PathingCommandType.SET_GOAL_AND_PATH)
} ?: PathingCommand(null, PathingCommandType.REQUEST_PAUSE)
}
} | 0 | Kotlin | 0 | 0 | fff6fc1ed6d8495eb5dd32480ce310addc6fd80b | 1,177 | HighwayTools | FSF All Permissive License |
sharedUI/src/commonMain/kotlin/com/prof18/feedflow/shared/ui/home/components/EmptyFeedView.kt | prof18 | 600,257,020 | false | {"Kotlin": 535563, "SCSS": 161629, "HTML": 161490, "Swift": 100500, "CSS": 16810, "Shell": 1753, "JavaScript": 1214} | package com.prof18.feedflow.shared.ui.home.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.prof18.feedflow.MR
import com.prof18.feedflow.core.model.FeedFilter
import com.prof18.feedflow.core.utils.TestingTag
import com.prof18.feedflow.shared.ui.style.Spacing
import com.prof18.feedflow.shared.ui.utils.tagForTesting
import dev.icerock.moko.resources.compose.stringResource
@Composable
fun EmptyFeedView(
currentFeedFilter: FeedFilter,
onReloadClick: () -> Unit,
onBackToTimelineClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
val emptyMessage = when (currentFeedFilter) {
is FeedFilter.Read -> stringResource(resource = MR.strings.read_articles_empty_screen_message)
is FeedFilter.Bookmarks -> stringResource(resource = MR.strings.bookmarked_articles_empty_screen_message)
else -> stringResource(resource = MR.strings.empty_feed_message)
}
Text(
modifier = Modifier
.tagForTesting(TestingTag.NO_ITEMS_MESSAGE),
text = emptyMessage,
style = MaterialTheme.typography.bodyMedium,
)
val buttonAction = if (currentFeedFilter is FeedFilter.Read || currentFeedFilter is FeedFilter.Bookmarks) {
onBackToTimelineClick
} else {
onReloadClick
}
val buttonText = when (currentFeedFilter) {
is FeedFilter.Read, is FeedFilter.Bookmarks -> {
stringResource(resource = MR.strings.empty_screen_back_to_timeline)
}
else -> {
stringResource(resource = MR.strings.refresh_feeds)
}
}
Button(
modifier = Modifier
.padding(top = Spacing.regular)
.tagForTesting(TestingTag.REFRESH_FEEDS_BUTTON),
onClick = buttonAction,
) {
Text(buttonText)
}
}
}
| 22 | Kotlin | 10 | 225 | f08b35998dfd56722b324da20f5df029d7c72816 | 2,522 | feed-flow | Apache License 2.0 |
orders/src/main/kotlin/org/bastanchu/churiservices/orders/internal/core/WebConfig.kt | vellebue | 723,669,515 | false | {"Kotlin": 174351} | package org.bastanchu.churiservices.orders.internal.core
import org.bastanchu.churiservices.core.api.config.BaseWebConfig
import org.springframework.context.annotation.Configuration
@Configuration
class WebConfig : BaseWebConfig() {
} | 0 | Kotlin | 0 | 0 | 8a719ff8091df86f61d632ce43c0ce18e697a343 | 237 | churiservices | Apache License 2.0 |
src/main/kotlin/scene/SceneRectangle.kt | Thalonius | 107,757,317 | true | {"Kotlin": 277846, "HTML": 262} | package spr5.scene;
import spr5.util.assert
class SceneRectangle(var faces: Array<SceneTriangle>, override var color: Rgba) : WebGLDrawable {
init {
assert(faces.size == 2, "faces.size == 2");
}
override fun getVertices(): Array<Float> {
return faces.fold(emptyArray()) {
vertices, face -> vertices + face.getVertices()
};
}
override fun getColors(): Array<Float> {
return faces.fold(emptyArray()) {
colors, face -> colors + face.getColors()
}
}
}
fun createSquare(direction: Direction, leftTop: Coordinate, size: Float, color: Rgba): SceneRectangle {
// First build a list of coordinates for this square depending on square orientation
// Then use the coordinates to make two triangles
// Coordinate list:
// left top, right top
// left bottom, right bottom
val coordinates: Array<Coordinate>;
// a square oriented in X-Z plane
if (direction == Direction.Horizontal) {
coordinates = arrayOf(
leftTop,
Coordinate(leftTop.x + size, leftTop.y, leftTop.z), // right top
Coordinate(leftTop.x, leftTop.y, leftTop.z + size), // left bottom
Coordinate(leftTop.x + size, leftTop.y, leftTop.z + size) // right bottom
);
// a square oriented in X-Y plane
} else if (direction == Direction.Vertical) {
coordinates = arrayOf(
leftTop,
Coordinate(leftTop.x + size, leftTop.y, leftTop.z),
Coordinate(leftTop.x, leftTop.y - size, leftTop.z),
Coordinate(leftTop.x + size, leftTop.y - size, leftTop.z)
);
} else {
throw IllegalArgumentException("Unsupported direction: " + direction);
}
val faces = arrayOf(
SceneTriangle(arrayOf(coordinates[0], coordinates[1], coordinates[2]), color),
SceneTriangle(arrayOf(coordinates[1], coordinates[2], coordinates[3]), color)
);
return SceneRectangle(faces, color);
} | 0 | Kotlin | 0 | 0 | 4bdf6bdcd29d3b4023c1b840e84462c59826ec3f | 2,046 | 3d-playground | Apache License 2.0 |
app/src/main/java/com/hadi/minimalnotes/data/repository/Repository.kt | unaisulhadi | 435,369,043 | false | {"Kotlin": 49830} | package com.hadi.minimalnotes.data.repository
import com.hadi.minimalnotes.NoteDatabase
import com.squareup.sqldelight.runtime.coroutines.asFlow
import com.squareup.sqldelight.runtime.coroutines.mapToList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import notedb.NoteEntity
import javax.inject.Inject
class Repository @Inject constructor(private val db: NoteDatabase) {
private val queries = db.noteEntityQueries
fun getAllNotes() = queries.getAllNotes().asFlow().mapToList()
suspend fun getNoteById(id: Long): NoteEntity? {
return withContext(Dispatchers.IO) {
queries.getNoteById(id).executeAsOneOrNull()
}
}
suspend fun insertNote(title: String, content: String, date: String, id: Long? = null) {
withContext(Dispatchers.IO) {
queries.insertNote(id, title, content, date)
}
}
suspend fun deleteNoteById(id: Long) {
withContext(Dispatchers.IO) {
queries.deleteNoteById(id)
}
}
fun searchNote(keyword: String): Flow<List<NoteEntity>> {
return queries.searchNotes(keyword).asFlow().mapToList()
}
} | 0 | Kotlin | 2 | 22 | 3c60aac740c9643fefd624b0e214e47b882752c4 | 1,207 | MinimalNotes | MIT License |
src/main/kotlin/model/queue/QueueSortKey.kt | Ather | 161,568,528 | false | null | /*
* Copyright 2018 Michael Haas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.ather.radarr.model.queue
import app.ather.radarr.model.paging.SortKey
import com.squareup.moshi.Json
enum class QueueSortKey : SortKey {
@Json(name = "timeleft")
Time,
@Json(name = "sizeleft")
Size
} | 0 | Kotlin | 0 | 0 | 7313476abe3a0a2db135ffce1c91b3a5f206b74e | 826 | radarr-kotlin | Apache License 2.0 |
mewwalletkit/src/main/java/com/myetherwallet/mewwalletkit/bip/bip39/BIP39.kt | MyEtherWallet | 225,455,950 | false | null | package com.myetherwallet.mewwalletkit.bip.bip39
import com.myetherwallet.mewwalletkit.bip.bip39.exception.*
import com.myetherwallet.mewwalletkit.bip.bip39.wordlist.BaseWordlist
import com.myetherwallet.mewwalletkit.bip.bip39.wordlist.EnglishWordlist
import com.myetherwallet.mewwalletkit.core.data.Bit
import com.myetherwallet.mewwalletkit.core.data.BitArray
import com.myetherwallet.mewwalletkit.core.extension.sha256
import com.myetherwallet.mewwalletkit.core.extension.toBits
import com.myetherwallet.mewwalletkit.core.extension.toByteArray
import com.myetherwallet.mewwalletkit.core.util.PKCS5
import java.security.SecureRandom
import java.text.Normalizer
/**
* Created by BArtWell on 10.05.2019.
*/
private const val BIP39Salt = "mnemonic"
class BIP39 {
private var inputEntropy: ByteArray? = null
val entropy: ByteArray? by lazy {
inputEntropy?.let {
return@lazy it
}
inputMnemonic?.let {
try {
toEntropy(it)
} catch (e: Exception) {
null
}
}
}
private var inputMnemonic: List<String>? = null
val mnemonic: List<String>? by lazy {
inputMnemonic?.let {
return@lazy it
}
inputEntropy?.let {
try {
toMnemonic(it)
} catch (e: Exception) {
null
}
}
}
private var language: BaseWordlist
constructor(bitsOfEntropy: Int = 256, language: BaseWordlist = EnglishWordlist()) {
this.language = language
inputEntropy = generateEntropy(bitsOfEntropy)
}
constructor(mnemonic: List<String>, language: BaseWordlist = EnglishWordlist()) {
this.language = language
inputMnemonic = mnemonic
}
constructor(entropy: ByteArray, language: BaseWordlist = EnglishWordlist()) {
this.language = language
inputEntropy = entropy
}
fun seed(password: String = ""): ByteArray? {
mnemonic?.let {
if (it.isNotEmpty()) {
return seed(it, password)
}
}
throw InvalidMnemonicException()
}
private fun seed(mnemonic: List<String>, password: String = ""): ByteArray? {
if (entropy == null) {
throw InvalidEntropyException()
}
val mnemonicData = Normalizer.normalize(mnemonic.joinToString(" "), Normalizer.Form.NFKD)
if (mnemonicData.isEmpty()) {
throw InvalidMnemonicException()
}
val salt = BIP39Salt + password
val saltData = Normalizer.normalize(salt, Normalizer.Form.NFKD).toByteArray()
if (saltData.isEmpty()) {
throw InvalidSaltException()
}
return PKCS5.pbkdf2(mnemonicData, saltData, 2048, 64, PKCS5.Algorithm.PBKDF2WithHmacSHA512)
}
private fun generateEntropy(bitsOfEntropy: Int = 256): ByteArray {
if (bitsOfEntropy < 128 || bitsOfEntropy > 256 || bitsOfEntropy % 32 != 0) {
throw InvalidBitsOfEntropyException()
}
val random = SecureRandom()
val entropy = ByteArray(bitsOfEntropy / 8)
random.nextBytes(entropy)
return entropy
}
fun toMnemonic(entropy: ByteArray): List<String> {
if (entropy.size < 16 || entropy.size > 32 || entropy.size % 4 != 0) {
throw InvalidEntropyException()
}
val checksum = entropy.sha256()
val checksumBits = entropy.size * 8 / 32
val fullEntropy = mutableListOf<Byte>()
fullEntropy.addAll(entropy.toList())
val checksumPart = checksum.slice(0 until (checksumBits + 7) / 8)
fullEntropy.addAll(checksumPart)
val wordList = mutableListOf<String>()
for (i in 0 until fullEntropy.size * 8 / 11) {
val position = i * 11
val index = fullEntropy.toByteArray().toBits(position until position + 11)
if (index == null || language.words.count() < index) {
throw InvalidEntropyException()
}
val word = language.words[index]
wordList.add(word)
}
return wordList
}
fun toEntropy(mnemonic: List<String>): ByteArray {
if (mnemonic.count() < 12 && mnemonic.count() % 3 != 0) {
throw InvalidMnemonicException()
}
val bitsList = mutableListOf<Bit>()
for (word in mnemonic) {
val index = language.words.indexOf(word)
if (index == -1) {
throw InvalidMnemonicException()
}
val positionBits = index.toShort().toByteArray().flatMap { BitArray(it) }
if (positionBits.count() != 16) {
throw InvalidMnemonicException()
}
bitsList.addAll(positionBits.slice(5..15))
}
if (bitsList.count() % 33 != 0) {
throw InvalidMnemonicException()
}
val bits = BitArray(bitsList)
val entropyBits = bits.slice(0 until (bits.count() - bits.count() / 33))
val checksumBits = bits.slice((bits.count() - bits.count() / 33) until bits.count())
val entropy = entropyBits.toBytes()
val checksum = entropy.sha256().toBits(0, checksumBits.count()) ?: throw InvalidChecksumException()
if (checksumBits.toByte() != checksum.toByte()) {
throw InvalidChecksumException()
}
return entropy
}
} | 0 | Kotlin | 4 | 7 | 1a6a77751de522a40504b6850254ea7dd5fa422c | 5,438 | mew-wallet-android-kit | MIT License |
src/main/kotlin/no/nav/syfo/client/krr/KRRClientMetric.kt | navikt | 160,816,361 | false | null | package no.nav.syfo.client.krr
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.Counter.builder
import no.nav.syfo.application.metric.METRICS_NS
import no.nav.syfo.application.metric.METRICS_REGISTRY
const val CALL_KRR_BASE = "${METRICS_NS}_call_krr"
const val CALL_KRR_KONTAKTINFORMASJON_BASE = "${CALL_KRR_BASE}_kontaktinformasjon"
const val CALL_KRR_KONTAKTINFORMASJON_SUCCESS = "${CALL_KRR_KONTAKTINFORMASJON_BASE}_success_count"
const val CALL_KRR_KONTAKTINFORMASJON_FAIL = "${CALL_KRR_KONTAKTINFORMASJON_BASE}_fail_count"
val COUNT_CALL_KRR_KONTAKTINFORMASJON_SUCCESS: Counter = builder(CALL_KRR_KONTAKTINFORMASJON_SUCCESS)
.description("Counts the number of successful calls to KRR - Kontaktinformasjon")
.register(METRICS_REGISTRY)
val COUNT_CALL_KRR_KONTAKTINFORMASJON_FAIL: Counter = builder(CALL_KRR_KONTAKTINFORMASJON_FAIL)
.description("Counts the number of failed calls to KRR - Kontaktinformasjon")
.register(METRICS_REGISTRY)
| 2 | Kotlin | 0 | 1 | 3633d2e20be7e389543b8d9ae77a49b6451f3fd0 | 996 | syfoperson | MIT License |
app/src/main/java/com/example/moviemaster/data/remote/movies/model/movie/ApiSingleMovieGenre.kt | AntonDavidson | 831,711,015 | false | {"Kotlin": 89490} | package com.example.moviemaster.data.remote.movies.model.movie
import com.google.gson.annotations.SerializedName
data class ApiSingleMovieGenre(
@SerializedName("id") val id: Int?,
@SerializedName("name") val name: String?
)
| 0 | Kotlin | 0 | 0 | f28bde0da36e02b65654ad9e6996e71560bacacd | 227 | Movie-Master | MIT License |
app/src/main/java/org/simple/clinic/scanid/ScanSimpleIdEvent.kt | tomka88 | 286,309,326 | true | {"Kotlin": 3803641, "Shell": 3616, "Python": 3162} | package org.simple.clinic.scanid
import org.simple.clinic.patient.Patient
import org.simple.clinic.util.Optional
import org.simple.clinic.widgets.UiEvent
import java.util.UUID
sealed class ScanSimpleIdEvent : UiEvent
object ShowKeyboard : ScanSimpleIdEvent() {
override val analyticsName: String
get() = "Scan Simple Card:Show keyboard"
}
object HideKeyboard : ScanSimpleIdEvent() {
override val analyticsName: String
get() = "Scan Simple Card:Hide keyboard"
}
object ShortCodeChanged : ScanSimpleIdEvent() {
override val analyticsName: String
get() = "Scan Simple Card:Short code changed"
}
data class ShortCodeValidated(val result: ShortCodeValidationResult) : ScanSimpleIdEvent()
data class ShortCodeSearched(val shortCode: ShortCodeInput) : ScanSimpleIdEvent() {
override val analyticsName: String
get() = "Scan Simple Card:Short code searched"
}
data class PatientSearchCompleted(val patient: Optional<Patient>, val scannedId: UUID) : ScanSimpleIdEvent()
data class ScanSimpleIdScreenQrCodeScanned(val text: String) : ScanSimpleIdEvent() {
override val analyticsName = "Scan Simple Card:QR code scanned"
}
| 0 | null | 0 | 0 | 7164ff6d7beed61460cc7e151e6e461a5563b5d9 | 1,146 | simple-android | MIT License |
data/RF02604/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF02604"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 7
87 to 92
}
value = "#8595ed"
}
color {
location {
12 to 15
81 to 84
}
value = "#525245"
}
color {
location {
18 to 20
77 to 79
}
value = "#89366c"
}
color {
location {
21 to 27
69 to 75
}
value = "#594ba9"
}
color {
location {
28 to 30
35 to 37
}
value = "#06bf95"
}
color {
location {
38 to 48
52 to 62
}
value = "#e4e87f"
}
color {
location {
103 to 114
126 to 137
}
value = "#9b437e"
}
color {
location {
116 to 117
122 to 123
}
value = "#3eef53"
}
color {
location {
141 to 147
206 to 212
}
value = "#163d31"
}
color {
location {
150 to 154
197 to 201
}
value = "#8b1b72"
}
color {
location {
163 to 166
193 to 196
}
value = "#1d41ad"
}
color {
location {
169 to 177
182 to 190
}
value = "#c34c88"
}
color {
location {
8 to 11
85 to 86
}
value = "#9f9b50"
}
color {
location {
16 to 17
80 to 80
}
value = "#ea9d2c"
}
color {
location {
21 to 20
76 to 76
}
value = "#d51d15"
}
color {
location {
28 to 27
38 to 37
63 to 68
}
value = "#27bbd1"
}
color {
location {
31 to 34
}
value = "#194821"
}
color {
location {
49 to 51
}
value = "#cdfceb"
}
color {
location {
115 to 115
124 to 125
}
value = "#c9c4d6"
}
color {
location {
118 to 121
}
value = "#273cdd"
}
color {
location {
148 to 149
202 to 205
}
value = "#abca86"
}
color {
location {
155 to 162
197 to 196
}
value = "#1b571a"
}
color {
location {
167 to 168
191 to 192
}
value = "#31c5f2"
}
color {
location {
178 to 181
}
value = "#069acb"
}
color {
location {
1 to 1
}
value = "#5cfee0"
}
color {
location {
93 to 102
}
value = "#8a6786"
}
color {
location {
138 to 140
}
value = "#b3c9fb"
}
color {
location {
213 to 214
}
value = "#ac00b0"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 4,208 | Rfam-for-RNArtist | MIT License |
src/test/kotlin/co/mateocontreras/dagobah/controllers/ExerciseControllerTest.kt | jmcontreras10 | 869,857,308 | false | {"Kotlin": 13018, "JavaScript": 850, "Dockerfile": 671, "Makefile": 370} | package co.mateocontreras.dagobah.controllers
import co.mateocontreras.dagobah.builders.dtos.ExerciseDtoBuilder
import co.mateocontreras.dagobah.services.ExerciseService
import org.bson.types.ObjectId
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.whenever
import kotlin.test.assertEquals
@ExtendWith(MockitoExtension::class)
internal class ExerciseControllerTest {
@Mock
lateinit var exerciseService: ExerciseService
@InjectMocks
lateinit var exerciseController: ExerciseController
@Test
fun `getExercises should return all exercises`() {
val exercises = listOf(
ExerciseDtoBuilder().build(),
ExerciseDtoBuilder(id = ObjectId.get().toString(), name = "Inclined Chest Press").build(),
)
whenever(exerciseService.getExercises()).thenReturn(exercises)
val response = exerciseController.getExercises()
assertEquals(exercises, response.body)
}
@Nested
inner class GetExerciseById {
@Test
fun `getExerciseById should return the specified exercise`() {
val id = ObjectId.get().toString()
val exerciseDto = ExerciseDtoBuilder(id=id).build()
whenever(exerciseService.getExerciseById(id)).thenReturn(exerciseDto)
val response = exerciseController.getExerciseById(id)
assertEquals(exerciseDto, response.body)
}
@Test
fun `getExerciseById should throw an exception if the exercise does not exist`() {
val id = ObjectId.get().toString()
whenever(exerciseService.getExerciseById(id)).thenThrow(NoSuchElementException())
assertThrows<NoSuchElementException> { exerciseController.getExerciseById(id) }
}
}
} | 0 | Kotlin | 0 | 1 | ce2bb3977085391981a0a6dbca52d97aef102400 | 1,995 | Dagobah | Apache License 2.0 |
app/src/main/java/io/geeteshk/hyper/util/ui/Styles.kt | geeteshk | 67,724,412 | false | null | /*
* Copyright 2016 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.geeteshk.hyper.util.ui
import android.content.Context
import io.geeteshk.hyper.R
import io.geeteshk.hyper.util.Prefs.defaultPrefs
import io.geeteshk.hyper.util.Prefs.get
object Styles {
fun getThemeInt(context: Context): Int {
val prefs = defaultPrefs(context)
return if (prefs["dark_theme", false]!!) {
R.style.Hyper_Dark
} else {
R.style.Hyper
}
}
}
| 0 | Kotlin | 9 | 21 | fc492e0d9d1c112f851163d15dadf2977436123b | 1,032 | Hyper | Apache License 2.0 |
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/musicbrainz/MusicBrainzClient.kt | OurFriendIrony | 87,706,649 | false | null | package uk.co.ourfriendirony.medianotifier.clients.musicbrainz
import com.fasterxml.jackson.databind.ObjectMapper
import uk.co.ourfriendirony.medianotifier.clients.AbstractClient
import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.get.ArtistGet
import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.get.ArtistGetReleaseGroup
import uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.search.ArtistSearch
import uk.co.ourfriendirony.medianotifier.general.Helper
import uk.co.ourfriendirony.medianotifier.mediaitem.MediaItem
import uk.co.ourfriendirony.medianotifier.mediaitem.artist.Artist
import uk.co.ourfriendirony.medianotifier.mediaitem.artist.Release
import java.io.IOException
class MusicBrainzClient : AbstractClient() {
private var payload: String? = null
@Throws(IOException::class)
fun queryArtist(artist: String?): List<MediaItem> {
payload = httpGetRequest(
Helper.replaceTokens(URL_ARTIST_QUERY, "@NAME@", Helper.cleanUrl(artist!!))
)
val mediaItems: MutableList<MediaItem> = ArrayList()
try {
val rawSearch = OBJECT_MAPPER.readValue(payload, ArtistSearch::class.java)
for (a in rawSearch.artists!!) {
mediaItems.add(Artist(a))
}
} catch (e: Exception) {
System.err.println(e.message)
}
return mediaItems
}
@Throws(IOException::class)
fun getArtist(artistID: String?): MediaItem {
payload = httpGetRequest(
Helper.replaceTokens(URL_ARTIST_ID, "@ID@", artistID!!)
)
val ag = OBJECT_MAPPER.readValue(payload, ArtistGet::class.java)
val artist = Artist(ag)
val releases: MutableList<MediaItem> = ArrayList()
for (rawRelease in ag.releaseGroups!!) {
if (isWanted(rawRelease) && hasADate(rawRelease)) {
releases.add(Release(rawRelease, artist))
}
}
artist.children = releases
return artist
}
private fun hasADate(rawRelease: ArtistGetReleaseGroup): Boolean {
return rawRelease.firstReleaseDate != null
}
private fun isWanted(agrg: ArtistGetReleaseGroup): Boolean {
val releaseTypes = mutableListOf(agrg.primaryType)
releaseTypes.addAll(agrg.secondaryTypes!!)
for (releaseType in releaseTypes) {
if (RELEASE_TYPES_UNWANTED.contains(releaseType)) {
return false
}
}
return true
}
companion object {
private const val HOST = "https://musicbrainz.org/ws/2/"
private const val URL_ARTIST_QUERY = HOST + "artist/?query=artist:@NAME@&fmt=json"
private const val URL_ARTIST_ID = HOST + "artist/@ID@/?inc=release-groups&fmt=json"
private const val URL_ARTIST_RELEASE_ID = HOST + "release/@ID@?inc=recordings&fmt=json"
private val OBJECT_MAPPER = ObjectMapper()
private val RELEASE_TYPES_UNWANTED: ArrayList<String> = object : ArrayList<String>() {
init {
add("Compilation")
add("EP")
add("Live")
add("Single")
add("Demo")
}
}
}
} | 2 | Kotlin | 0 | 1 | 2fe4f780474dd6756a527e5cf1609c7bc27fa2a8 | 3,233 | MediaNotifier | Apache License 2.0 |
lib_common/src/main/java/com/logan/common/provider/MainServiceProvider.kt | logan0817 | 790,127,966 | false | {"Kotlin": 367382, "Java": 13225} | package com.logan.common.provider
import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.launcher.ARouter
import com.logan.common.constant.MAIN_SERVICE_HOME
import com.logan.common.service.IMainService
/**
* @author logan.gan
* @date 2024/04/15
* @desc MainService提供类,对外提供相关能力
* 任意模块就能通过MainServiceProvider使用对外暴露的能力
*/
object MainServiceProvider {
@Autowired(name = MAIN_SERVICE_HOME)
lateinit var mainService: IMainService
init {
ARouter.getInstance().inject(this)
}
/**
* 跳转主页
* @param context
* @param index tab位置
*/
fun toMain(context: Context, index: Int = 0) {
mainService.toMain(context, index)
}
/**
* 跳转文章详情
* @param context
* @param url 文章链接
* @param title 标题
*/
fun toArticleDetail(context: Context, url: String, title: String) {
mainService.toArticleDetail(context, url, title)
}
} | 0 | Kotlin | 0 | 2 | 20b74ca8af06dea1f48b5f188f86f31944826aa0 | 991 | BleExplorer | Apache License 2.0 |
vpn-main/src/main/java/com/duckduckgo/mobile/android/vpn/di/DeviceShieldTileServiceComponent.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2021 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.mobile.android.vpn.di
import com.duckduckgo.di.scopes.AppObjectGraph
import com.duckduckgo.di.scopes.VpnObjectGraph
import com.duckduckgo.mobile.android.vpn.service.DeviceShieldTileService
import com.squareup.anvil.annotations.ContributesTo
import com.squareup.anvil.annotations.MergeSubcomponent
import dagger.Binds
import dagger.Module
import dagger.Subcomponent
import dagger.android.AndroidInjector
import dagger.binding.TileServiceBingingKey
import dagger.multibindings.ClassKey
import dagger.multibindings.IntoMap
@VpnScope
@MergeSubcomponent(
scope = VpnObjectGraph::class
)
interface DeviceShieldTileServiceComponent : AndroidInjector<DeviceShieldTileService> {
@Subcomponent.Factory
interface Factory : AndroidInjector.Factory<DeviceShieldTileService>
}
@ContributesTo(AppObjectGraph::class)
interface DeviceShieldTileServiceComponentProvider {
fun provideDeviceShieldTileServiceComponentFactory(): DeviceShieldTileServiceComponent.Factory
}
@Module
@ContributesTo(AppObjectGraph::class)
abstract class DeviceShieldTileServiceBindingModule {
@Binds
@IntoMap
// We don't use the DeviceShieldTileService::class as binding key because TileService (Android) class does not
// exist in all APIs, and so using it DeviceShieldTileService::class as key would compile but immediately crash
// at startup when Java class loader tries to resolve the TileService::class upon Dagger setup
@ClassKey(TileServiceBingingKey::class)
abstract fun bindDeviceShieldTileServiceComponentFactory(factory: DeviceShieldTileServiceComponent.Factory): AndroidInjector.Factory<*>
}
| 38 | Kotlin | 642 | 2,220 | e259cb7a4e04e164f66dbc464a9eefeff4b127fd | 2,233 | Android | Apache License 2.0 |
app/src/main/java/com/manishpatole/playapplication/base/BaseAdapter.kt | devmanishpatole | 308,805,265 | false | null | package com.devmanishpatole.imagecommenter.base
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<T, VH : BaseItemViewHolder<T, out BaseItemViewModel<T>>>(
parentLifecycle: Lifecycle,
protected val dataList: ArrayList<T>
) : RecyclerView.Adapter<VH>() {
init {
parentLifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onParentDestroy() {
recyclerView?.run {
for (i in 0 until childCount) {
getChildAt(i)?.let {
(getChildViewHolder(it) as BaseItemViewHolder<*, *>).run {
onDestroy()
viewModel.onManualClear()
}
}
}
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onParentStop() {
recyclerView?.run {
for (i in 0 until childCount) {
getChildAt(i)?.let {
(getChildViewHolder(it) as BaseItemViewHolder<*, *>).onStop()
}
}
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onParentStart() {
recyclerView?.run {
if (layoutManager is LinearLayoutManager) {
val layoutManager = layoutManager as LinearLayoutManager
val first = layoutManager.findFirstVisibleItemPosition()
val last = layoutManager.findLastVisibleItemPosition()
if (first in 0..last) {
for (i in first..last) {
findViewHolderForAdapterPosition(i)?.let {
(it as BaseItemViewHolder<*, *>).onStart()
}
}
}
}
}
}
})
}
private var recyclerView: RecyclerView? = null
override fun onViewAttachedToWindow(holder: VH) {
super.onViewAttachedToWindow(holder)
holder.onStart()
}
override fun onViewDetachedFromWindow(holder: VH) {
super.onViewDetachedFromWindow(holder)
holder.onStop()
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
this.recyclerView = recyclerView
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
this.recyclerView = null
}
override fun getItemCount() = dataList.size
override fun onBindViewHolder(holder: VH, position: Int) {
holder.bind(dataList[position])
}
fun appendData(dataList: ArrayList<T>) {
val oldCount = itemCount
this.dataList.addAll(dataList)
val newCount = itemCount
if (oldCount == 0 && newCount > 0) {
notifyDataSetChanged()
} else if (oldCount in 1 until newCount) {
notifyItemRangeChanged(oldCount - 1, newCount - oldCount)
}
}
fun replaceData(dataList: ArrayList<T>) {
this.dataList.clear()
this.dataList.addAll(dataList)
notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 0 | e34d88dea184b465f93c492102cd8ad8b9e86005 | 3,657 | PlayApplication | The Unlicense |
app/src/main/java/io/github/hirorocky/utasora/model/Phrase.kt | hirorocky | 795,022,484 | false | {"Kotlin": 94327, "Shell": 1379, "Ruby": 1229} | package io.github.hirorocky.utasora.model
import java.util.Date
data class Phrase(
val id: String = "",
val text: String = "",
val createdAt: Date = Date(),
)
| 0 | Kotlin | 0 | 0 | 952c4c4cff0c027b054ed89e07c031f6bb16227e | 173 | utasora-android | Apache License 2.0 |
modules/kenerator/configuration/src/main/kotlin/com/flipperdevices/ifrmvp/generator/config/category/api/DvdCategoryConfigGenerator.kt | flipperdevices | 824,125,673 | false | {"Kotlin": 207380, "Dockerfile": 695} | package com.flipperdevices.ifrmvp.generator.config.category.api
import com.flipperdevices.ifrmvp.backend.model.CategoryConfiguration
import com.flipperdevices.ifrmvp.backend.model.CategoryType
import com.flipperdevices.ifrmvp.backend.model.DeviceKey
import com.flipperdevices.ifrmvp.generator.config.category.api.DeviceKeyExt.getAllowedCategories
import com.flipperdevices.ifrmvp.model.buttondata.IconButtonData
import com.flipperdevices.ifrmvp.model.buttondata.PowerButtonData
import com.flipperdevices.ifrmvp.model.buttondata.ShutterButtonData
import com.flipperdevices.ifrmvp.model.buttondata.TextButtonData
object DvdCategoryConfigGenerator {
@Suppress("LongMethod")
fun generate(): CategoryConfiguration {
var i = 0
return CategoryConfiguration(
orders = listOf(
CategoryConfiguration.OrderModel(
data = PowerButtonData(),
message = "Does %s turns on?",
key = DeviceKey.PWR,
index = ++i,
),
CategoryConfiguration.OrderModel(
message = "Does it open next channel?",
data = TextButtonData(text = "CH+"),
key = DeviceKey.CH_UP,
index = ++i,
),
CategoryConfiguration.OrderModel(
message = "Does it open previous channel?",
data = TextButtonData(text = "CH-"),
key = DeviceKey.CH_DOWN,
index = ++i,
),
CategoryConfiguration.OrderModel(
message = "Does volume go up?",
data = IconButtonData(iconId = IconButtonData.IconType.VOL_UP),
key = DeviceKey.VOL_UP,
index = ++i,
),
CategoryConfiguration.OrderModel(
message = "Does volume go down?",
data = IconButtonData(iconId = IconButtonData.IconType.VOL_DOWN),
key = DeviceKey.VOL_DOWN,
index = ++i,
),
CategoryConfiguration.OrderModel(
message = "Is it muted?",
data = IconButtonData(iconId = IconButtonData.IconType.MUTE),
key = DeviceKey.MUTE,
index = ++i,
),
CategoryConfiguration.OrderModel(
message = "Is it ejected?",
data = IconButtonData(iconId = IconButtonData.IconType.EJECT),
key = DeviceKey.EJECT,
index = ++i,
),
)
)
}
fun generate(categoryType: CategoryType): CategoryConfiguration {
val configuration = generate()
return CategoryConfiguration(
orders = configuration.orders.filter {
it.key.getAllowedCategories().contains(categoryType)
}
)
}
}
| 0 | Kotlin | 0 | 1 | 370dd431f9d196f6d92ffb1cbdde107c121bb4fd | 3,024 | IRDB-Backend | MIT License |
app/src/main/java/com/example/fitfinder/ui/messages/MessagesFragment.kt | OmriGawi | 618,447,164 | false | {"Kotlin": 235146} | package com.example.fitfinder.ui.messages
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.example.fitfinder.R
import com.example.fitfinder.data.repository.messages.MatchesRepository
import com.example.fitfinder.databinding.FragmentMessagesBinding
import com.example.fitfinder.util.SharedPreferencesUtil
import com.example.fitfinder.viewmodel.ViewModelFactory
import com.example.fitfinder.viewmodel.messages.MatchesViewModel
class MessagesFragment : Fragment() {
// Variables
private lateinit var binding: FragmentMessagesBinding
private lateinit var matchesViewModel: MatchesViewModel
private lateinit var matchesAdapter: MatchesAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentMessagesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Initialize view models
matchesViewModel = ViewModelProvider(requireActivity(), ViewModelFactory(MatchesRepository()))[MatchesViewModel::class.java]
// Initialize adapters
matchesAdapter = MatchesAdapter(emptyList())
// Setup RecyclerView
setupRecyclerView()
// Fetch matches and users
val userId = SharedPreferencesUtil.getUserId(requireContext()).toString()
matchesViewModel.fetchMatchesAndUsersForUser(userId)
matchesViewModel.matchesWithUsers.observe(viewLifecycleOwner) { matchesWithUsers ->
matchesAdapter.updateData(matchesWithUsers)
}
matchesAdapter.onMatchClickListener = { match, potentialUser ->
matchesViewModel.selectMatchWithUser(match, potentialUser)
navigateToChat()
}
// Set up Listeners
matchesViewModel.observeMatchesUpdates(userId)
}
private fun setupRecyclerView() {
binding.rvChats.adapter = matchesAdapter
}
private fun navigateToChat() {
val chatFragment = ChatFragment()
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout, chatFragment)
.addToBackStack(null)
.commit()
}
}
| 0 | Kotlin | 0 | 0 | 928b348a3c2b4fd80531a42e083eb366f3e92550 | 2,455 | FitFinder | MIT License |
medusalib/src/main/java/com/trendyol/medusalib/navigator/FragmentStackState.kt | Trendyol | 156,667,108 | false | {"Kotlin": 93427, "Java": 4938} | package com.trendyol.medusalib.navigator
import com.trendyol.medusalib.common.extensions.insertToBottom
import com.trendyol.medusalib.common.extensions.moveToTop
import com.trendyol.medusalib.navigator.data.StackItem
import java.util.*
data class FragmentStackState constructor(
val fragmentTagStack: MutableList<Stack<StackItem>> = mutableListOf(),
val tabIndexStack: Stack<Int> = Stack()
) {
fun getSelectedTabIndex(): Int {
return if (tabIndexStack.size != 0) {
tabIndexStack.peek()
} else {
0
}
}
fun isSelectedTabEmpty() = isTabEmpty(getSelectedTabIndex())
fun isTabEmpty(index: Int) = fragmentTagStack[index].isEmpty()
fun notifyStackItemAdd(tabIndex: Int, stackItem: StackItem) {
val stack = fragmentTagStack.get(tabIndex)
stack.push(stackItem)
}
fun notifyStackItemAddToCurrentTab(stackItem: StackItem) {
notifyStackItemAdd(getSelectedTabIndex(), stackItem)
}
fun setStackCount(size: Int) {
for (index in 0 until size) {
fragmentTagStack.add(Stack())
}
}
fun clear() {
fragmentTagStack.clear()
tabIndexStack.clear()
}
fun switchTab(tabIndex: Int) {
if (tabIndexStack.contains(tabIndex).not()) {
tabIndexStack.push(tabIndex)
} else {
tabIndexStack.moveToTop(tabIndex)
}
}
fun isSelectedTab(tabIndex: Int) = getSelectedTabIndex() == tabIndex
fun hasOnlyRoot(tabIndex: Int) = fragmentTagStack[tabIndex].size <= 1
fun hasSelectedTabOnlyRoot() = fragmentTagStack[getSelectedTabIndex()].size <= 1
fun peekItemFromSelectedTab() =
fragmentTagStack[getSelectedTabIndex()].takeIf { it.isNotEmpty() }?.peek()
fun popItem(tabIndex: Int): StackItem {
val item = fragmentTagStack.get(tabIndex).pop()
if (isTabEmpty(tabIndex) && tabIndex == getSelectedTabIndex() && tabIndexStack.size > 1) {
popSelectedTab()
}
return item
}
fun popItemsFromNonEmptyTabs(): List<StackItem> {
return fragmentTagStack
.filter { it.isNotEmpty() }
.flatMap { stackItem -> stackItem.map { it } }
.also { fragmentTagStack.clear() }
}
fun insertTabToBottom(tabIndex: Int) {
tabIndexStack.insertToBottom(tabIndex)
}
fun popItems(groupName: String): List<StackItem> {
val currentTabIndex = getSelectedTabIndex()
val currentTabStack = fragmentTagStack.get(getSelectedTabIndex())
val updatedTabStack = Stack<StackItem>()
updatedTabStack.push(currentTabStack[0])
val deletedStackItems = arrayListOf<StackItem>()
for (i in 1 until currentTabStack.size) {
val stackItem = currentTabStack[i]
if (groupName == stackItem.groupName) {
deletedStackItems.add(stackItem)
} else {
updatedTabStack.push(stackItem)
}
}
if (deletedStackItems.isEmpty().not()) {
fragmentTagStack[currentTabIndex] = updatedTabStack
}
return deletedStackItems
}
fun hasTabStack() = tabIndexStack.size == 1
fun setStackState(stackState: FragmentStackState) {
fragmentTagStack.addAll(stackState.fragmentTagStack)
tabIndexStack.addAll(stackState.tabIndexStack)
}
fun peekItem(tabIndex: Int) = fragmentTagStack.get(tabIndex).peek()
fun popItemFromSelectedTab() = popItem(getSelectedTabIndex())
fun popSelectedTab(): Int {
return tabIndexStack.pop()
}
} | 12 | Kotlin | 60 | 486 | 99db3212ba8dac426966b93300b3175dc470b019 | 3,608 | medusa | Apache License 2.0 |
components/repository/src/main/kotlin/com/sample/application/components/repository/Either.kt | Raghuramchowdary-tech | 363,732,877 | false | null | package com.sample.application.components.repository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ProducerScope
sealed class Either<out F, out S> {
data class Failure<out F>(val data: F) : Either<F, Nothing>()
data class Success<out S>(val data: S) : Either<Nothing, S>()
}
fun <F, S> Either<F, S>.onFailure(failureCallback: (failure: F) -> Unit): Either<F, S> =
this.apply { if (this is Either.Failure) failureCallback(data) }
fun <F, S> Either<F, S>.onFailurePass(failureCallback: (failure: Either.Failure<F>) -> Unit): Either<F, S> =
this.apply { if (this is Either.Failure) failureCallback(this) }
@OptIn(ExperimentalCoroutinesApi::class)
fun <F, S> Either<F, S>.onFailurePass(failureCallback: ProducerScope<Either.Failure<F>>): Either<F, S> =
this.apply {
if (this is Either.Failure) {
failureCallback.offer(this)
failureCallback.close()
}
}
fun <F, S> Either<F, S>.onSuccess(successCallback: (success: S) -> Unit): Either<F, S> =
this.apply { if (this is Either.Success) successCallback(data) }
fun <F, S> Either<F, S>.onSuccessPass(successCallback: (success: Either.Success<S>) -> Unit): Either<F, S> =
this.apply { if (this is Either.Success) successCallback(this) }
@OptIn(ExperimentalCoroutinesApi::class)
fun <F, S> Either<F, S>.onSuccessPass(successCallback: ProducerScope<Either.Success<S>>): Either<F, S> =
this.apply {
if (this is Either.Success) {
successCallback.offer(this)
successCallback.close()
}
}
| 0 | Kotlin | 0 | 0 | 76910ece9b3e3ec8627052d20f4c0b93514bbd1e | 1,592 | Task | Apache License 2.0 |
app/src/main/kotlin/com/dvinc/notepad/data/repository/note/NoteDataRepository.kt | NexusLove | 227,261,517 | true | {"Kotlin": 68948} | /*
* Copyright (c) 2018 by <NAME> (<EMAIL>)
* All rights reserved.
*/
package com.dvinc.notepad.data.repository.note
import com.dvinc.notepad.data.database.dao.note.NoteDao
import com.dvinc.notepad.data.mapper.note.NoteDataMapper
import com.dvinc.notepad.domain.model.note.Note
import com.dvinc.notepad.domain.repository.note.NoteRepository
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import javax.inject.Inject
class NoteDataRepository @Inject constructor(
private val noteDao: NoteDao,
private val noteMapper: NoteDataMapper
) : NoteRepository {
override fun getNotes(): Flowable<List<Note>> {
return noteDao.getNotes()
.map { noteMapper.fromEntityToDomain(it) }
}
override fun addNote(note: Note): Completable {
return Single.just(noteMapper.fromDomainToEntity(note))
.flatMapCompletable {
Completable.fromAction { noteDao.addNote(it) }
}
}
override fun deleteNoteById(id: Long): Completable {
return Completable.fromAction { noteDao.deleteNoteById(id) }
}
override fun getNoteById(id: Long): Single<Note> {
return Single.fromCallable { noteDao.getNoteById(id) }
.map { noteMapper.fromEntityToDomain(it) }
}
}
| 0 | null | 0 | 0 | c62d3cb5a2bf7934c9c67c80e61c77cdff4f98df | 1,331 | Notepad | MIT License |
communication/src/main/kotlin/io/github/mmolosay/datalayercommunication/communication/server/Server.kt | mmolosay | 594,482,339 | false | null | package io.github.mmolosay.datalayercommunication.communication.requests.server
/**
* Serves appropriate [Response] for specified [Request].
*/
interface Server<Request, Response> {
suspend fun reciprocate(request: Request): Response
} | 0 | null | 1 | 9 | 8ec2f23b76606c8a48efc23b77a0c07d759c8b25 | 242 | DataLayerCommunication | Apache License 2.0 |
client/android/app/src/main/java/org/devtcg/robotrc/mainui/MainActivity.kt | jasta | 462,495,183 | false | null | package org.devtcg.robotrc.mainui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.devtcg.robotrc.databinding.MainActivityBinding
import org.devtcg.robotrc.robotdata.bridge.RobotSelectorBridge
import org.devtcg.robotrc.robotselection.ui.RobotSelectionInitiationAgent
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
class MainActivity : AppCompatActivity() {
private lateinit var binding: MainActivityBinding
private lateinit var robotSelectionAgent: RobotSelectionInitiationAgent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = MainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar!!.setDisplayShowTitleEnabled(false)
robotSelectionAgent = RobotSelectionInitiationAgent(
this,
supportFragmentManager,
binding.robotTargetButton,
RobotSelectorBridge.instance)
robotSelectionAgent.onCreate()
}
}
| 0 | Kotlin | 0 | 0 | 8f2a755e1ff6b745f934a56ccfaea12b8a91c418 | 1,117 | ev3-remote-control | MIT License |
core/src/test/kotlin/model/CommentTest.kt | TillmannBerg | 224,526,859 | true | {"Kotlin": 617380, "Groovy": 7613, "CSS": 4374, "Java": 3014} | package org.jetbrains.dokka.tests
import org.junit.Test
import org.junit.Assert.*
import org.jetbrains.dokka.*
abstract class BaseCommentTest(val analysisPlatform: Platform) {
val defaultModelConfig = ModelConfig(analysisPlatform = analysisPlatform)
@Test fun codeBlockComment() {
checkSourceExistsAndVerifyModel("testdata/comments/codeBlockComment.kt", defaultModelConfig) { model ->
with(model.members.single().members.first()) {
assertEqualsIgnoringSeparators("""[code lang=brainfuck]
|
|++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
|
|[/code]
|""".trimMargin(),
content.toTestString())
}
with(model.members.single().members.last()) {
assertEqualsIgnoringSeparators("""[code]
|
|a + b - c
|
|[/code]
|""".trimMargin(),
content.toTestString())
}
}
}
@Test fun emptyDoc() {
checkSourceExistsAndVerifyModel("testdata/comments/emptyDoc.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals(Content.Empty, content)
}
}
}
@Test fun emptyDocButComment() {
checkSourceExistsAndVerifyModel("testdata/comments/emptyDocButComment.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals(Content.Empty, content)
}
}
}
@Test fun multilineDoc() {
checkSourceExistsAndVerifyModel("testdata/comments/multilineDoc.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("doc1", content.summary.toTestString())
assertEquals("doc2\ndoc3", content.description.toTestString())
}
}
}
@Test fun multilineDocWithComment() {
checkSourceExistsAndVerifyModel("testdata/comments/multilineDocWithComment.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("doc1", content.summary.toTestString())
assertEquals("doc2\ndoc3", content.description.toTestString())
}
}
}
@Test fun oneLineDoc() {
checkSourceExistsAndVerifyModel("testdata/comments/oneLineDoc.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("doc", content.summary.toTestString())
}
}
}
@Test fun oneLineDocWithComment() {
checkSourceExistsAndVerifyModel("testdata/comments/oneLineDocWithComment.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("doc", content.summary.toTestString())
}
}
}
@Test fun oneLineDocWithEmptyLine() {
checkSourceExistsAndVerifyModel("testdata/comments/oneLineDocWithEmptyLine.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("doc", content.summary.toTestString())
}
}
}
@Test fun emptySection() {
checkSourceExistsAndVerifyModel("testdata/comments/emptySection.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("Summary", content.summary.toTestString())
assertEquals(1, content.sections.count())
with (content.findSectionByTag("one")!!) {
assertEquals("One", tag)
assertEquals("", toTestString())
}
}
}
}
@Test fun quotes() {
checkSourceExistsAndVerifyModel("testdata/comments/quotes.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("it's \"useful\"", content.summary.toTestString())
}
}
}
@Test fun section1() {
checkSourceExistsAndVerifyModel("testdata/comments/section1.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("Summary", content.summary.toTestString())
assertEquals(1, content.sections.count())
with (content.findSectionByTag("one")!!) {
assertEquals("One", tag)
assertEquals("section one", toTestString())
}
}
}
}
@Test fun section2() {
checkSourceExistsAndVerifyModel("testdata/comments/section2.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("Summary", content.summary.toTestString())
assertEquals(2, content.sections.count())
with (content.findSectionByTag("one")!!) {
assertEquals("One", tag)
assertEquals("section one", toTestString())
}
with (content.findSectionByTag("two")!!) {
assertEquals("Two", tag)
assertEquals("section two", toTestString())
}
}
}
}
@Test fun multilineSection() {
checkSourceExistsAndVerifyModel("testdata/comments/multilineSection.kt", defaultModelConfig) { model ->
with(model.members.single().members.single()) {
assertEquals("Summary", content.summary.toTestString())
assertEquals(1, content.sections.count())
with (content.findSectionByTag("one")!!) {
assertEquals("One", tag)
assertEquals("""line one
line two""", toTestString())
}
}
}
}
@Test fun directive() {
checkSourceExistsAndVerifyModel("testdata/comments/directive.kt", defaultModelConfig) { model ->
with(model.members.single().members.first()) {
assertEquals("Summary", content.summary.toTestString())
with (content.description) {
assertEqualsIgnoringSeparators("""
|[code lang=kotlin]
|if (true) {
| println(property)
|}
|[/code]
|[code lang=kotlin]
|if (true) {
| println(property)
|}
|[/code]
|[code lang=kotlin]
|if (true) {
| println(property)
|}
|[/code]
|[code lang=kotlin]
|if (true) {
| println(property)
|}
|[/code]
|""".trimMargin(), toTestString())
}
}
}
}
}
class JSCommentTest: BaseCommentTest(Platform.js)
class JVMCommentTest: BaseCommentTest(Platform.jvm)
class CommonCommentTest: BaseCommentTest(Platform.common) | 0 | null | 0 | 0 | de2f32d91fb6f564826ddd7644940452356e2080 | 7,620 | dokka | Apache License 2.0 |
shopping_list/src/main/java/com/zizohanto/android/tobuy/shopping_list/ui/products/adapter/ProductViewHolder.kt | zizoh | 292,960,353 | false | null | package com.zizohanto.android.tobuy.shopping_list.ui.products.adapter
import android.view.inputmethod.EditorInfo
import androidx.core.view.isVisible
import com.zizohanto.android.tobuy.shopping_list.databinding.ItemProductEditableBinding
import com.zizohanto.android.tobuy.shopping_list.presentation.models.ProductsViewItem.ProductModel
import com.zizohanto.android.tobuy.shopping_list.ui.products.DEBOUNCE_PERIOD
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import reactivecircus.flowbinding.android.widget.textChanges
class ProductViewHolder(
private val binding: ItemProductEditableBinding
) : TextChangeViewHolder(binding.root) {
fun bind(product: ProductModel, listener: ProductViewListener?, scope: CoroutineScope) {
binding.productName.setOnFocusChangeListener { _, hasFocus ->
binding.remove.isVisible = hasFocus
}
binding.productName.setText(product.name)
binding.productName
.textChanges()
.debounce(DEBOUNCE_PERIOD)
.drop(1)
.map {
listener?.onProductEdit(product.copy(name = it.trim().toString()))
}.launchIn(scope)
binding.remove.setOnClickListener {
listener?.onProductDelete(product)
}
binding.productName.setOnEditorActionListener { _, action, _ ->
if (action == EditorInfo.IME_ACTION_DONE) {
if (product.name.isNotEmpty()) {
listener?.onAddNewProduct(product.position)
}
true
} else false
}
}
} | 0 | Kotlin | 2 | 7 | 71336809fe008ff1db3cd4724b6c890d206a3ab5 | 1,732 | Shopping-List-MVI | Apache License 2.0 |
src/main/kotlin/org/vitrivr/cottontail/execution/operators/definition/DropSchemaOperator.kt | vitrivr | 160,775,368 | false | null | package org.vitrivr.cottontail.execution.operators.definition
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import org.vitrivr.cottontail.database.catalogue.CatalogueTx
import org.vitrivr.cottontail.database.catalogue.DefaultCatalogue
import org.vitrivr.cottontail.execution.TransactionContext
import org.vitrivr.cottontail.execution.operators.basics.Operator
import org.vitrivr.cottontail.model.basics.Name
import org.vitrivr.cottontail.model.basics.Record
import kotlin.time.ExperimentalTime
import kotlin.time.measureTimedValue
/**
* An [Operator.SourceOperator] used during query execution. Drops a [Schema]
*
* @author <NAME>
* @version 1.1.0
*/
@ExperimentalTime
class DropSchemaOperator(val catalogue: DefaultCatalogue, val name: Name.SchemaName) : AbstractDataDefinitionOperator(name, "DROP SCHEMA") {
override fun toFlow(context: TransactionContext): Flow<Record> {
val txn = context.getTx(this.catalogue) as CatalogueTx
return flow {
val timedTupleId = measureTimedValue {
txn.dropSchema([email protected])
}
emit([email protected](timedTupleId.duration))
}
}
} | 8 | null | 11 | 14 | b5546015ae69013649b25a75b261b2a835469d0a | 1,218 | cottontaildb | MIT License |
app/src/main/java/com/test/moviehub/data/model/GetDetailsResponse.kt | AlirezaGoshayesh | 356,847,083 | false | null | package com.test.moviehub.data.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class GetDetailsResponse(
@SerializedName("adult")
val adult: Boolean,
@SerializedName("backdrop_path")
val backdropPath: Any,
@SerializedName("belongs_to_collection")
val belongsToCollection: Any,
@SerializedName("budget")
val budget: Int,
@SerializedName("genres")
val genres: List<Genre>,
@SerializedName("homepage")
val homepage: String,
@SerializedName("id")
val id: Int,
@SerializedName("imdb_id")
val imdbId: String,
@SerializedName("original_language")
val originalLanguage: String,
@SerializedName("original_title")
val originalTitle: String,
@SerializedName("overview")
val overview: String?,
@SerializedName("popularity")
val popularity: Double,
@SerializedName("poster_path")
val posterPath: Any,
@SerializedName("production_companies")
val productionCompanies: List<Any>,
@SerializedName("production_countries")
val productionCountries: List<Any>,
@SerializedName("release_date")
val releaseDate: String,
@SerializedName("revenue")
val revenue: Int,
@SerializedName("runtime")
val runtime: Int,
@SerializedName("spoken_languages")
val spokenLanguages: List<Any>,
@SerializedName("status")
val status: String,
@SerializedName("tagline")
val tagline: String,
@SerializedName("title")
val title: String,
@SerializedName("video")
val video: Boolean,
@SerializedName("vote_average")
val voteAverage: Double,
@SerializedName("vote_count")
val voteCount: Int
) : Serializable {
/**
* get a usable string from genres.
*/
fun getGenresString(): String {
var mGenres = ""
val genresMap = genres.map { it.name }
genresMap.forEach {
mGenres += "$it - "
}
return mGenres.subSequence(0, mGenres.length - 2).toString()
}
/**
* get a usable string from summary.
*/
fun getSummary(): String {
return if (overview.isNullOrEmpty())
"No summary available"
else
overview
}
} | 0 | Kotlin | 0 | 6 | 9caa62375681fc4dae9a740fd9ecc56bad8e01c7 | 2,226 | MovieHub | Apache License 2.0 |
src/main/kotlin/com/daveme/chocolateCakePHP/controller/ControllerFieldTypeProvider.kt | dmeybohm | 95,393,362 | false | null | package com.daveme.chocolateCakePHP.controller
import com.daveme.chocolateCakePHP.Settings
import com.daveme.chocolateCakePHP.componentOrModelTypeFromFieldName
import com.daveme.chocolateCakePHP.isControllerClass
import com.daveme.chocolateCakePHP.startsWithUppercaseCharacter
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.jetbrains.php.lang.psi.elements.FieldReference
import com.jetbrains.php.lang.psi.elements.PhpNamedElement
import com.jetbrains.php.lang.psi.resolve.types.PhpType
import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4
class ControllerFieldTypeProvider : PhpTypeProvider4 {
override fun getKey(): Char {
return '\u8312'
}
override fun complete(str: String?, project: Project?): PhpType? = null
override fun getType(psiElement: PsiElement): PhpType? {
if (psiElement !is FieldReference) {
return null
}
val settings = Settings.getInstance(psiElement.project)
if (!settings.enabled) {
return null
}
val classReference = psiElement.classReference ?: return null
val referenceType = classReference.type
if (!referenceType.isComplete) {
return null
}
val fieldReferenceName = psiElement.name ?: return null
// don't add types for nested types ($this->FooBar->FooBar):
if (psiElement.firstChild is FieldReference) {
return null
}
if (!fieldReferenceName.startsWithUppercaseCharacter()) {
return null
}
for (type in referenceType.types) {
if (type.isControllerClass()) {
return componentOrModelTypeFromFieldName(settings, fieldReferenceName)
}
}
return null
}
override fun getBySignature(
expression: String,
set: Set<String>,
i: Int,
project: Project
): Collection<PhpNamedElement> {
// We use the default signature processor exclusively:
return emptyList()
}
}
| 8 | Kotlin | 0 | 13 | 2aedc8d9487ebd670e29a993e54dec135f302ea2 | 2,073 | chocolate-cakephp | MIT License |
UnicornFilePicker/src/main/java/abhishekti7/unicorn/filepicker/storage/StorageNaming.kt | darkmat13r | 338,381,468 | true | {"Kotlin": 45885, "Java": 31765} | package abhishekti7.unicorn.filepicker.storage
import androidx.annotation.IntDef
import java.io.File
object StorageNaming {
const val STORAGE_INTERNAL = 0
const val STORAGE_SD_CARD = 1
const val ROOT = 2
const val NOT_KNOWN = 3
/** Retrofit of [android.os.storage.StorageVolume.getDescription] to older apis */
@DeviceDescription
fun getDeviceDescriptionLegacy(file: File): Int {
val path = file.path
return when (path) {
"/storage/emulated/legacy", "/storage/emulated/0", "/mnt/sdcard" -> STORAGE_INTERNAL
"/storage/sdcard", "/storage/sdcard1" -> STORAGE_SD_CARD
"/" -> ROOT
else -> NOT_KNOWN
}
}
@IntDef(STORAGE_INTERNAL, STORAGE_SD_CARD, ROOT, NOT_KNOWN)
annotation class DeviceDescription
}
| 0 | Kotlin | 0 | 0 | 5874b80b396bdbe9c1711bfd1effec3ef8c59c3d | 812 | UnicornFilePicker | Apache License 2.0 |
app/src/main/java/com/yoloroy/gameoflife/data/local/entity/Profile.kt | yoloroy | 464,261,245 | false | {"Kotlin": 186795} | package com.yoloroy.gameoflife.data.local.entity
import androidx.annotation.NonNull
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Profile(
@PrimaryKey
@ColumnInfo(name = "profile_id")
val profileId: Int,
@ColumnInfo(name = "image_url")
val imageUrl: String?,
@NonNull
@ColumnInfo(name = "name")
val name: String,
@NonNull
@ColumnInfo(name = "level", defaultValue = "${Default.level}")
val level: Int,
@NonNull
@ColumnInfo(name = "exp", defaultValue = "${Default.exp}")
val exp: Int,
@NonNull
@ColumnInfo(name = "max_exp", defaultValue = "${Default.maxExp}")
val maxExp: Int
) {
object Default {
const val localProfileId = -1
const val level = 1
const val exp = 0
const val maxExp = 25
val profile get() = Profile(localProfileId, null, "New Guru", level, exp, maxExp)
}
}
| 2 | Kotlin | 0 | 0 | 951ee64b5f37b53aa577fc36e740de83ca575400 | 960 | Game_Of_A_Life_A-App | MIT License |
app/src/main/java/com/serlongfellow/android/airporthangout/CandidateLineViewHolder.kt | SerLongfellow | 128,733,461 | false | null | package com.serlongfellow.android.airporthangout
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.serlongfellow.android.airporthangout.IntentExtras.Companion.INTENT_EXTRA_CANDIDATE_ID
import kotlinx.android.synthetic.main.line_view_meetup_candidates.view.*
class CandidateLineViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
var candidateId : Int = -1
val profilePictureImageView : ImageView = itemView.profilePictureImageView
val nameLabel : TextView = itemView.nameLabel
val originLocationLabel : TextView = itemView.originLocationLabel
val occupationLabel : TextView = itemView.occupationLabel
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
val intent = Intent(BaseApplication.instance, CandidateDetailActivity::class.java).apply {
putExtra(INTENT_EXTRA_CANDIDATE_ID, candidateId)
}
BaseApplication.instance.startActivity(intent)
}
} | 0 | Kotlin | 0 | 0 | ebb3916fea48c4fd59b254e480473f85e2ec9133 | 1,116 | AirportHangout | Apache License 2.0 |
src/en/arvencomics/src/eu/kanade/tachiyomi/extension/en/arvencomics/ArvenComics.kt | komikku-app | 720,497,299 | false | {"Kotlin": 6770889, "JavaScript": 2160} | package eu.kanade.tachiyomi.extension.en.arvencomics
import eu.kanade.tachiyomi.multisrc.mangathemesia.MangaThemesia
class ArvenComics : MangaThemesia(
"Arven Scans",
"https://arvencomics.com",
"en",
mangaUrlDirectory = "/series",
)
| 21 | Kotlin | 5 | 84 | e1f0e51442b67957333f3d69fab156705ebe7730 | 251 | komikku-extensions | Apache License 2.0 |
app/src/main/java/app/newproj/lbrytv/hiltmodule/LbrynetServiceModule.kt | bgshacklett | 448,629,512 | false | {"Kotlin": 220861, "Java": 4984} | package app.newproj.lbrytv.hiltmodule
import app.newproj.lbrytv.service.JsonRpcEmptyBodyInterceptor
import app.newproj.lbrytv.service.LbrynetService
import app.newproj.lbrytv.service.JsonRpcHttpBodyConverterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Qualifier
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object LbrynetServiceModule {
@Provides
@Singleton
@LbrynetServiceScope
fun lbrynetService(
jsonRpcEmptyBodyInterceptor: JsonRpcEmptyBodyInterceptor,
httpLoggingInterceptor: HttpLoggingInterceptor,
gsonConverterFactory: GsonConverterFactory,
): LbrynetService {
val client = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(jsonRpcEmptyBodyInterceptor)
.build()
return Retrofit.Builder()
.baseUrl("http://127.0.0.1:5279/")
.client(client)
.addConverterFactory(JsonRpcHttpBodyConverterFactory)
.addConverterFactory(gsonConverterFactory)
.build()
.create(LbrynetService::class.java)
}
}
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class LbrynetServiceScope
| 0 | null | 3 | 0 | 2f01cb775b821e3541e48db09cafafc4d8e5feea | 1,473 | lbry-androidtv | MIT License |
app/src/main/java/ru/igla/tfprofiler/utils/TimeWatchClockOS.kt | iglaweb | 297,256,320 | false | null | package ru.igla.tfprofiler.utils
import android.os.SystemClock
class TimeWatchClockOS {
private var timeStart = 0L
private var timeElapsed = 0L
private var isStarted = false
fun start() {
isStarted = true
timeStart = SystemClock.elapsedRealtime()
timeElapsed = 0L
}
fun stop(): Long {
if (isStarted) { //return fixed time
timeElapsed = SystemClock.elapsedRealtime() - timeStart
isStarted = false
}
return timeElapsed
}
} | 0 | Kotlin | 6 | 26 | 06b4a8265ba9209a894711398017197d1c7e1522 | 524 | TFProfiler | Apache License 2.0 |
src/main/kotlin/org/piecesapp/client/models/FlattenedDistribution.kt | pieces-app | 726,212,140 | false | null | /**
* Pieces Isomorphic OpenAPI
* Endpoints for Assets, Formats, Users, Asset, Format, User.
*
* The version of the OpenAPI document: 1.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.piecesapp.client.models
import org.piecesapp.client.models.EmbeddedModelSchema
import org.piecesapp.client.models.GitHubDistribution
import org.piecesapp.client.models.GroupedTimestamp
import org.piecesapp.client.models.MailgunDistribution
import com.squareup.moshi.Json
/**
*
* @param id
* @param share This is the UUId of the share.
* @param created
* @param updated
* @param schema
* @param deleted
* @param mailgun
* @param github
*/
data class FlattenedDistribution (
@Json(name = "id")
val id: kotlin.String,
/* This is the UUId of the share. */
@Json(name = "share")
val share: kotlin.String,
@Json(name = "created")
val created: GroupedTimestamp,
@Json(name = "updated")
val updated: GroupedTimestamp,
@Json(name = "schema")
val schema: EmbeddedModelSchema? = null,
@Json(name = "deleted")
val deleted: GroupedTimestamp? = null,
@Json(name = "mailgun")
val mailgun: MailgunDistribution? = null,
@Json(name = "github")
val github: GitHubDistribution? = null
)
| 9 | null | 2 | 6 | 9371158b0978cae518a6f2584dd452a2556b394f | 1,391 | pieces-os-client-sdk-for-kotlin | MIT License |
client/src/main/kotlin/io/titandata/models/VolumeCapabilities.kt | CloudSurgeon | 212,463,880 | true | {"Kotlin": 586314, "Shell": 46347, "Java": 9931, "Dockerfile": 904} | /*
* Copyright The Titan Project Contributors.
*/
package io.titandata.models
import com.google.gson.annotations.SerializedName
data class VolumeCapabilities(
@SerializedName("Scope")
var scope: String
)
| 0 | Kotlin | 0 | 1 | 819f7e9ea1bb0c675e0d04d61cf05302c488d74f | 217 | titan-server | Apache License 2.0 |
buildSrc/src/main/kotlin/Versions.kt | mekenzh | 224,448,142 | true | {"Kotlin": 1544897, "C++": 4992, "CMake": 1641} | object Versions {
val td = listOf(
"1.5.0",
"1.5.1"
)
const val tdLatest = "1.5.1"
const val immutableCollections = "0.3"
const val githubApi = "1.99"
const val kotlinShell = "0.2"
}
| 0 | null | 0 | 0 | 6282c87a5cd489cd762fa04f11987a66cbcf3af5 | 223 | ktd | Apache License 2.0 |
kadamy_delivery_driver_android/app/src/main/java/com/kadamy/driver/utils/SharePreference.kt | yefsoft09 | 784,271,487 | false | {"Kotlin": 885209, "PHP": 634806, "Blade": 602183, "JavaScript": 56504, "Java": 955} | package com.kadamy.driver.utils
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
class SharePreference {
companion object {
lateinit var mContext: Context
lateinit var sharedPreferences: SharedPreferences
val PREF_NAME: String = "Restaurant Driver"
val PRIVATE_MODE: Int = 0
lateinit var editor: SharedPreferences.Editor
val isLogin: String = "isLogin"
val userId: String = "userid"
val userMobile: String = "usermobile"
val userEmail: String = "useremail"
val userName: String = "userName"
val userProfile: String = "userprofile"
val isTutorial = "tutorial"
val isCurrancy = "Currancy"
val currencyPos = "CurrencyPos"
val aboutUs = "AboutUs"
var SELECTED_LANGUAGE = "selected_language"
fun getStringPref(context: Context, key: String): String? {
val pref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
return pref.getString(key, "")
}
fun setStringPref(context: Context, key: String, value: String) {
val pref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
pref.edit().putString(key, value).apply()
}
fun getBooleanPref(context: Context, key: String): Boolean {
val pref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
return pref.getBoolean(key, false)
}
fun setBooleanPref(context: Context, key: String, value: Boolean) {
val pref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
pref.edit().putBoolean(key, value).apply()
}
}
@SuppressLint("CommitPrefEdits")
constructor(mContext1: Context) {
mContext = mContext1
sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
editor = sharedPreferences.edit()
}
fun mLogout() {
editor.clear()
editor.commit()
}
} | 0 | Kotlin | 0 | 0 | 65c4e1217c87049a4cc2ac4d1fe92d0c3a467d6f | 2,117 | ProyectoProg1_AppDelivery | MIT License |
system-test/src/main/java/com/elbit/system_test/SharedPreferencesHelper.kt | getappsh | 735,551,269 | false | {"Kotlin": 781523, "Java": 7463, "Python": 589} | package com.elbit.system_test
import android.content.Context
import android.content.SharedPreferences
object SharedPreferencesHelper {
private const val PREFS_NAME = "prefs"
private const val START_TEST_TIME_KEY = "start_test_time"
fun writeStartTestTime(context: Context) {
val sharedPreferences: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
val currentTime = System.currentTimeMillis()
editor.putLong(START_TEST_TIME_KEY, currentTime)
editor.apply()
}
fun readCurrentTime(context: Context): Long {
val sharedPreferences: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
return sharedPreferences.getLong(START_TEST_TIME_KEY, 0)
}
}
| 3 | Kotlin | 1 | 1 | 6e04b980478ce672d58ad3f2d714d3355cadb3fd | 828 | getmap-android-sdk | Apache License 2.0 |
app/src/main/java/com/acxdev/poolguardapps/repository/PoolCoinList.kt | dodyac | 606,656,789 | false | null | package com.acxdev.poolguardapps.repository
import com.acxdev.commonFunction.util.ext.emptyString
import com.acxdev.poolguardapps.common.base.BaseUrl
import com.acxdev.poolguardapps.model.coin.Coin
import com.acxdev.poolguardapps.repository.Crypto
object PoolCoinList {
fun flockPoolCoin() = listOf(
Coin(Crypto.RTM, BaseUrl.URL_FLOCKPOOL),
)
fun zetPoolPpsCoin() = listOf(
Coin(Crypto.ETHW, BaseUrl.ZetPool.PPS.ETH),
)
fun minerPoolSoloCoin() = listOf(
Coin(Crypto.FLUX, BaseUrl.MinerPool.Solo.FLUX),
Coin(Crypto.RVN, BaseUrl.MinerPool.Solo.RVN),
)
fun minerPoolCoin() = listOf(
Coin(Crypto.FLUX, BaseUrl.MinerPool.FLUX),
Coin(Crypto.RVN, BaseUrl.MinerPool.RVN),
)
fun unMineableCoin() = listOf(
Coin(Crypto.SHIB, BaseUrl.URL_UNMINEABLE),
)
fun ezilCoin() = listOf(
Coin(Crypto.ETHW, BaseUrl.Ezil.STATS),
Coin(Crypto.ETC, BaseUrl.Ezil.STATS),
)
fun hiveOnCoin() = listOf(
// Coin(Crypto.ETC, BaseUrl.URL_HIVEON),
Coin(Crypto.ETHW, BaseUrl.URL_HIVEON),
)
fun coMinersCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.CoMiners.ETC),
)
fun ravenPoolCoin() = listOf(
Coin(Crypto.RVN, BaseUrl.URL_RAVEN_POOL)
)
fun myMinersCoin() = listOf(
Coin(Crypto.CLO, BaseUrl.MyMiners.CLO),
Coin(Crypto.ETC, BaseUrl.MyMiners.ETC),
Coin(Crypto.EXP, BaseUrl.MyMiners.EXP),
)
fun ravenMinerCoin() = listOf(
Coin(Crypto.RVN, BaseUrl.URL_RAVEN_MINER),
)
fun mineXmrCoin() = listOf(
Coin(Crypto.XMR, BaseUrl.URL_MINEXMR),
)
fun myMinersSoloCoin() = listOf(
Coin(Crypto.CLO, BaseUrl.MyMiners.Solo.CLO),
Coin(Crypto.ETC, BaseUrl.MyMiners.Solo.ETC),
Coin(Crypto.ETHW, BaseUrl.MyMiners.Solo.ETH),
Coin(Crypto.EXP, BaseUrl.MyMiners.Solo.EXP),
)
fun baikalMineCoin() = listOf(
Coin(Crypto.CLO, BaseUrl.BaikalMine.PPLNS.CLO),
Coin(Crypto.ETC, BaseUrl.BaikalMine.PPLNS.ETC),
Coin(Crypto.ETHW, BaseUrl.BaikalMine.PPLNS.ETHW),
)
fun baikalMineSoloCoin() = listOf(
Coin(Crypto.CLO, BaseUrl.BaikalMine.Solo.CLO),
Coin(Crypto.ETC, BaseUrl.BaikalMine.Solo.ETC),
)
fun baikalMinePpsCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.BaikalMine.PPS.ETC),
Coin(Crypto.ETHW, BaseUrl.BaikalMine.PPS.ETHW),
)
fun k1PoolCoin() = listOf(
Coin(Crypto.BTG, BaseUrl.K1Pool.BTG),
Coin(Crypto.CLO, BaseUrl.K1Pool.CLO),
Coin(Crypto.ERG, BaseUrl.K1Pool.ERG),
Coin(Crypto.KMD, BaseUrl.K1Pool.KMD),
Coin(Crypto.RVN, BaseUrl.K1Pool.RVN),
)
fun k1PoolSoloCoin() = listOf(
Coin(Crypto.BTG, BaseUrl.K1Pool.Solo.BTG),
Coin(Crypto.CLO, BaseUrl.K1Pool.Solo.CLO),
Coin(Crypto.ERG, BaseUrl.K1Pool.Solo.ERG),
Coin(Crypto.ETC, BaseUrl.K1Pool.Solo.ETC),
Coin(Crypto.ETHW, BaseUrl.K1Pool.Solo.ETHW),
Coin(Crypto.KMD, BaseUrl.K1Pool.Solo.KMD),
Coin(Crypto.RVN, BaseUrl.K1Pool.Solo.RVN),
)
fun k1PoolRbppsCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.K1Pool.Rbpps.ETC),
Coin(Crypto.ETHW, BaseUrl.K1Pool.Rbpps.ETHW)
)
fun twoMinersCoin() = listOf(
Coin(Crypto.AE, BaseUrl.TwoMiners.AE),
Coin(Crypto.BEAM, BaseUrl.TwoMiners.BEAM),
Coin(Crypto.BTG, BaseUrl.TwoMiners.BTG),
Coin(Crypto.CKB, BaseUrl.TwoMiners.CKB),
Coin(Crypto.CLO, BaseUrl.TwoMiners.CLO),
Coin(Crypto.CTXC, BaseUrl.TwoMiners.CTXC),
Coin(Crypto.ERG, BaseUrl.TwoMiners.ERG),
Coin(Crypto.ETC, BaseUrl.TwoMiners.ETC),
Coin(Crypto.ETHW, BaseUrl.TwoMiners.ETH),
Coin(Crypto.FIRO, BaseUrl.TwoMiners.FIRO),
Coin(Crypto.FLUX, BaseUrl.TwoMiners.FLUX),
Coin(Crypto.RVN, BaseUrl.TwoMiners.RVN),
Coin(Crypto.XMR, BaseUrl.TwoMiners.XMR),
Coin(Crypto.ZEC, BaseUrl.TwoMiners.ZEC),
)
fun twoMinersSoloCoin() = listOf(
Coin(Crypto.AE, BaseUrl.TwoMiners.Solo.AE),
Coin(Crypto.BEAM, BaseUrl.TwoMiners.Solo.BEAM),
Coin(Crypto.BTG, BaseUrl.TwoMiners.Solo.BTG),
Coin(Crypto.CKB, BaseUrl.TwoMiners.Solo.CKB),
Coin(Crypto.CLO, BaseUrl.TwoMiners.Solo.CLO),
Coin(Crypto.CTXC, BaseUrl.TwoMiners.Solo.CTXC),
Coin(Crypto.ERG, BaseUrl.TwoMiners.Solo.ERG),
Coin(Crypto.ETC, BaseUrl.TwoMiners.Solo.ETC),
Coin(Crypto.ETHW, BaseUrl.TwoMiners.Solo.ETH),
Coin(Crypto.FIRO, BaseUrl.TwoMiners.Solo.FIRO),
Coin(Crypto.FLUX, BaseUrl.TwoMiners.Solo.FLUX),
Coin(Crypto.RVN, BaseUrl.TwoMiners.Solo.RVN),
Coin(Crypto.XMR, BaseUrl.TwoMiners.Solo.XMR),
Coin(Crypto.ZEC, BaseUrl.TwoMiners.Solo.ZEC),
)
fun crazyPoolCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.CrazyPool.ETC),
Coin(Crypto.ETHW, BaseUrl.CrazyPool.ETHW),
Coin(Crypto.UBQ, BaseUrl.CrazyPool.UBQ),
)
fun soloPoolCoin() = listOf(
Coin(Crypto.BEAM, BaseUrl.SoloPool.BEAM),
Coin(Crypto.BTG, BaseUrl.SoloPool.BTG),
Coin(Crypto.CLO, BaseUrl.SoloPool.CLO),
Coin(Crypto.ETC, BaseUrl.SoloPool.ETC),
Coin(Crypto.ETHW, BaseUrl.SoloPool.ETHW),
Coin(Crypto.FIRO, BaseUrl.SoloPool.FIRO),
Coin(Crypto.FLUX, BaseUrl.SoloPool.FLUX),
Coin(Crypto.KMD, BaseUrl.SoloPool.KMD),
Coin(Crypto.LTC, BaseUrl.SoloPool.LTC),
Coin(Crypto.RVN, BaseUrl.SoloPool.RVN),
Coin(Crypto.UBQ, BaseUrl.SoloPool.UBQ),
Coin(Crypto.XMR, BaseUrl.SoloPool.XMR),
Coin(Crypto.ZEC, BaseUrl.SoloPool.ZEC),
Coin(Crypto.ZEN, BaseUrl.SoloPool.ZEN),
)
fun zetPoolCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.ZetPool.ETC),
Coin(Crypto.ETHW, BaseUrl.ZetPool.ETH),
)
fun luckPoolCoin() = listOf(
Coin(Crypto.VRSC, BaseUrl.LuckPool.VRSC),
)
fun woolyPoolyCoin() = listOf(
Coin(Crypto.AE, BaseUrl.WoolyPooly.AE),
Coin(Crypto.CFX, BaseUrl.WoolyPooly.CFX),
Coin(Crypto.CTXC, BaseUrl.WoolyPooly.CTXC),
Coin(Crypto.ERG, BaseUrl.WoolyPooly.ERG),
Coin(Crypto.ETC, BaseUrl.WoolyPooly.ETC),
Coin(Crypto.ETHW, BaseUrl.WoolyPooly.ETHW),
Coin(Crypto.FLUX, BaseUrl.WoolyPooly.FLUX),
Coin(Crypto.RVN, BaseUrl.WoolyPooly.RVN),
Coin(Crypto.VEIL, BaseUrl.WoolyPooly.VEIL),
Coin(Crypto.VTC, BaseUrl.WoolyPooly.VTC),
)
fun flexPoolCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.URL_FLEXPOOL),
Coin(Crypto.XCH, BaseUrl.URL_FLEXPOOL),
)
fun flyPoolCoin() = listOf(
Coin(Crypto.ERG, BaseUrl.FlyPool.ERG),
Coin(Crypto.RVN, BaseUrl.FlyPool.RVN),
)
fun etherMineCoin() = listOf(
Coin(Crypto.ETC, BaseUrl.EtherMine.ETC),
)
fun heroMinersCoin() = listOf(
Coin(Crypto.BEAM, BaseUrl.HeroMiners.BEAM),
Coin(Crypto.CCX, BaseUrl.HeroMiners.CCX),
Coin(Crypto.CFX, BaseUrl.HeroMiners.CFX),
Coin(Crypto.CTXC, BaseUrl.HeroMiners.CTXC),
Coin(Crypto.ERG, BaseUrl.HeroMiners.ERG),
Coin(Crypto.ETC, BaseUrl.HeroMiners.ETC),
Coin(Crypto.ETHW, BaseUrl.HeroMiners.ETHW),
Coin(Crypto.FLUX, BaseUrl.HeroMiners.FLUX),
Coin(Crypto.QRL, BaseUrl.HeroMiners.QRL),
Coin(Crypto.RVN, BaseUrl.HeroMiners.RVN),
Coin(Crypto.TRTL, BaseUrl.HeroMiners.TRTL),
Coin(Crypto.XHV, BaseUrl.HeroMiners.XHV),
Coin(Crypto.XMR, BaseUrl.HeroMiners.XMR),
)
fun ethoClubPoolCoin() = listOf(
Coin(Crypto.ETHO, BaseUrl.URL_ETHOCLUB),
)
fun nanoPoolCoin() = listOf(
Coin(Crypto.CFX, BaseUrl.NanoPool.CFX),
Coin(Crypto.ERG, BaseUrl.NanoPool.ERG),
Coin(Crypto.ETC, BaseUrl.NanoPool.ETC),
Coin(Crypto.ETHW, BaseUrl.NanoPool.ETHW),
Coin(Crypto.RVN, BaseUrl.NanoPool.RVN),
Coin(Crypto.XMR, BaseUrl.NanoPool.XMR),
Coin(Crypto.ZEC, BaseUrl.NanoPool.ZEC),
)
fun profitabilityCoin() = listOf(
Coin(Crypto.ETHW, emptyString()),
Coin(Crypto.AE, emptyString()),
Coin(Crypto.BEAM, emptyString()),
Coin(Crypto.CFX, emptyString()),
Coin(Crypto.CTXC, emptyString()),
Coin(Crypto.ERG, emptyString()),
Coin(Crypto.ETC, emptyString()),
Coin(Crypto.QRL, emptyString()),
Coin(Crypto.RVN, emptyString()),
Coin(Crypto.TRTL, emptyString()),
Coin(Crypto.XHV, emptyString()),
Coin(Crypto.ZEC, emptyString()),
)
} | 0 | Kotlin | 0 | 1 | effd2aa0ac41e81f8b4684c97d5e9c1f2b30542a | 8,570 | Poolguard | MIT License |
app/src/main/java/se/linerotech/myapplication/models/BusData.kt | fenkan | 567,347,086 | false | null | package se.linerotech.myapplication.models
import com.google.gson.annotations.SerializedName
data class BusData(
@SerializedName("DepartureBoard")
val departureBoard: DepartureBoard = DepartureBoard()
) | 0 | null | 0 | 0 | f780fdd998980c96230e3a8f9fdacded9bb51679 | 213 | android-vasttrafik-app-fenkan | MIT License |
core/src/main/java/com/mgws/adownkyi/core/downloader/DownloadListener.kt | 2468785842 | 780,206,932 | false | {"Kotlin": 281453} | package com.mgws.adownkyi.core.downloader
import java.io.IOException
import java.util.UUID
interface DownloadListener {
fun progress(id: UUID, current: Long, total: Long)
fun success(id: UUID)
fun error(id: UUID, exception: IOException)
fun pause(id: UUID)
fun cancel(id: UUID)
} | 0 | Kotlin | 0 | 2 | 769161517fd233d604051207556e9c2a17e3cf7c | 306 | ADownkyi | MIT License |
testing/sandboxes/src/main/kotlin/net/corda/testing/sandboxes/CpiLoader.kt | corda | 346,070,752 | false | {"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.testing.sandboxes
import net.corda.libs.packaging.core.CpiIdentifier
import net.corda.libs.packaging.core.CpiMetadata
import net.corda.libs.packaging.Cpi
import java.util.concurrent.CompletableFuture
interface CpiLoader {
companion object {
const val COMPONENT_NAME = "net.corda.testing.sandboxes.CpiLoader"
const val BASE_DIRECTORY_KEY = "baseDirectory"
const val TEST_BUNDLE_KEY = "testBundle"
}
fun loadCPI(resourceName: String): Cpi
fun unloadCPI(cpi: Cpi)
fun getAllCpiMetadata(): CompletableFuture<List<CpiMetadata>>
fun getCpiMetadata(id: CpiIdentifier): CompletableFuture<CpiMetadata?>
fun removeCpiMetadata(id: CpiIdentifier)
fun stop()
}
| 11 | Kotlin | 27 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 727 | corda-runtime-os | Apache License 2.0 |
src/main/kotlin/voidcaffelatte/itempackage/packagerequest/PackageRequest.kt | voidCaffeLatte | 632,033,839 | false | null | package voidcaffelatte.itempackage.packagerequest
interface PackageRequest
{
fun generateAsync(onSucceeded: () -> Unit, onFailed: () -> Unit)
} | 0 | Kotlin | 0 | 0 | 7b4328f4842b97902a003a7f61d079ed3a8cc978 | 148 | item-package | MIT License |
graphglue-core/src/main/kotlin/io/github/graphglue/connection/filter/model/NodeSubFilter.kt | graphglue | 436,856,727 | false | {"Kotlin": 344000, "MDX": 27617, "CSS": 3406, "JavaScript": 3225, "HTML": 3030} | package io.github.graphglue.connection.filter.model
import io.github.graphglue.connection.filter.definition.NodeSubFilterDefinition
import org.neo4j.cypherdsl.core.Node
/**
* [FilterEntry] which allows using a [Filter] to generate the condition
*
* @param definition associated definition of the entry
* @param filter the [Filter] which defines the condition
*/
class NodeSubFilter(definition: NodeSubFilterDefinition, val filter: Filter) : FilterEntry(definition) {
override fun generateCondition(node: Node) = filter.generateCondition(node)
} | 0 | Kotlin | 2 | 2 | a6bd87cda00156f489e61cbb4d1a514b8a85c3de | 555 | graph-glue | Apache License 2.0 |
kotlin/src/ticTacToe/sal/SalTrisTest.kt | intresrl | 457,786,766 | false | null | package ticTacToe.sal
import org.junit.jupiter.api.Test
import ticTacToe.sal.Location.*
class SalTrisTest {
@Test
fun `play until tied`() {
with(SalTris()) {
play(NORTHWEST)
play(NORTH)
play(NORTHEAST)
play(WEST)
play(SOUTHWEST)
play(CENTER)
play(EAST)
play(SOUTHEAST)
play(SOUTH)
println(this)
assert(isGameOver())
}
}
@Test
fun `play until X wins on first row`() {
with(SalTris()) {
play(NORTHWEST)
play(SOUTHWEST)
play(NORTH)
play(SOUTH)
play(NORTHEAST)
println(this)
assert(isGameOver())
}
}
@Test
fun `play until O wins on diagonal`() {
with(SalTris()) {
play(NORTHWEST)
play(CENTER)
play(SOUTHEAST)
play(NORTHEAST)
play(NORTH)
play(SOUTHWEST)
println(this)
assert(isGameOver())
}
}
}
| 0 | Kotlin | 0 | 1 | 05310869bbc37ae3b2edab3d62c9a9e49a785592 | 1,091 | kata-pulta | MIT License |
src/org/jetbrains/r/annotator/RAnnotator.kt | JetBrains | 214,212,060 | false | null | /*
* Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.r.annotator
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.lang.annotation.AnnotationBuilder
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
class RAnnotator : Annotator {
override fun annotate(psiElement: PsiElement, holder: AnnotationHolder) {
val infos = ArrayList<HighlightInfo>()
val visitor = RAnnotatorVisitor(infos, holder.currentAnnotationSession)
psiElement.accept(visitor)
for (info: HighlightInfo in infos) {
val builder: AnnotationBuilder
if (info.description == null) {
builder = holder.newSilentAnnotation(info.severity)
}
else {
builder = holder.newAnnotation(info.severity, info.description)
}
builder.range(TextRange.create(info))
if (info.forcedTextAttributesKey != null) {
builder.textAttributes(info.forcedTextAttributesKey)
}
if (info.forcedTextAttributes != null) {
builder.enforcedTextAttributes(info.forcedTextAttributes)
}
builder.create()
}
}
}
| 2 | null | 13 | 62 | 9225567ed712f54d019ce5ab712016acdb6fc98e | 1,327 | Rplugin | Apache License 2.0 |
src/main/kotlin/com/herolynx/service/server/WebServer.kt | herolynx | 107,650,857 | false | null | package com.herolynx.service.server
import com.herolynx.service.conversions.ObjectMapperProvider
import com.herolynx.service.monitoring.info
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.ServletContextHandler
import org.eclipse.jetty.servlet.ServletHolder
import org.glassfish.jersey.jackson.JacksonFeature
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.servlet.ServletContainer
class WebServer {
private var jettyServer: Server? = null
@Throws(Exception::class)
fun start(rootPkgName: String, port: Int = 8080) {
info("Starting web server - port: $port, root package: $rootPkgName")
val serverConfig = ResourceConfig()
.register(JacksonFeature::class.java)
.register(ObjectMapperProvider::class.java)
.packages(rootPkgName)
val servletHolder = createServletHolder(serverConfig)
jettyServer = startServer(servletHolder, port)
}
private fun startServer(servletHolder: ServletHolder, port: Int): Server {
val servletContextHandler = ServletContextHandler(ServletContextHandler.NO_SESSIONS)
servletContextHandler.addServlet(servletHolder, "/*")
val jettyServer = Server(port)
jettyServer.handler = servletContextHandler
jettyServer.start()
jettyServer.join()
return jettyServer
}
private fun createServletHolder(serverConfig: ResourceConfig): ServletHolder {
val servletContainer = ServletContainer(serverConfig)
val servletHolder = ServletHolder(servletContainer)
servletHolder.initOrder = 0
return servletHolder
}
@Throws(Exception::class)
fun stop() {
info("Stopping web server")
jettyServer?.stop()
}
}
| 0 | Kotlin | 0 | 0 | 79963c4f40f2dc71bdc7f634c7af198e4a1a7e6e | 1,797 | seed-microservice-kotlin-light | MIT License |
src/main/kotlin/dev/s7a/ktconfig/serializer/ChunkString.kt | sya-ri | 557,209,174 | false | {"Kotlin": 139689, "Java": 199} | package dev.s7a.ktconfig.serializer
import dev.s7a.ktconfig.KtConfigSerializer
import dev.s7a.ktconfig.UseSerializer
import org.bukkit.Bukkit
import org.bukkit.Chunk
import kotlin.reflect.typeOf
/**
* [Chunk] separated by commas.
*
* @since 1.0.0
* @see Chunk
*/
@Suppress("ktlint:annotation")
typealias ChunkString = @UseSerializer(ChunkStringSerializer::class) Chunk
/**
* Serializer of [Chunk] separated by commas.
*
* @since 1.0.0
*/
object ChunkStringSerializer : KtConfigSerializer {
override val type = typeOf<String>()
override fun deserialize(value: Any?): Chunk? {
require(value is String)
return runCatching {
value.split(',').let {
if (it.size != 3) return null
val world = Bukkit.getWorld(it[0].trim()) ?: return null
val x = it[1].trim().toInt()
val z = it[2].trim().toInt()
world.getChunkAt(x, z)
}
}.getOrNull()
}
override fun serialize(value: Any?): String {
require(value is Chunk)
return "${value.world.name}, ${value.x}, ${value.z}"
}
}
| 14 | Kotlin | 0 | 9 | b79e8e758d597fa61e323a970be0e17cfe89bf6c | 1,135 | ktConfig | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/FlipCameraIosRounded.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/FlipCameraIosRounded")
package mui.icons.material
@JsName("default")
external val FlipCameraIosRounded: SvgIconComponent
| 12 | null | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 204 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/pavelrekun/rekado/data/Schema.kt | Tek-God | 277,112,796 | true | {"Kotlin": 68054, "C++": 1279, "CMake": 145} | package com.pavelrekun.rekado.data
import com.google.gson.annotations.SerializedName
data class Schema(
@SerializedName("payloads")
val payloads: MutableList<Payload>,
@SerializedName("type")
val type: Int,
@SerializedName("timestamp")
val timestamp: Int
) | 0 | null | 0 | 1 | e232f43d5e149182aaf1680a114387f5530a9698 | 306 | Rekado | Apache License 2.0 |
app/src/main/java/ch/nevis/exampleapp/coroutines/ui/util/Fragment.kt | nevissecurity | 580,013,451 | false | {"Kotlin": 313088, "Ruby": 7705} | /**
* Nevis Mobile Authentication SDK Example App
*
* Copyright © 2022. Nevis Security AG. All rights reserved.
*/
package ch.nevis.exampleapp.coroutines.ui.util
import androidx.fragment.app.Fragment
/**
* Fragment argument key constant for dispatch token response.
*/
val FRAGMENT_ARGUMENT_DISPATCH_TOKEN_RESPONSE: String
get() = "dispatchTokenResponse"
/**
* Extension function for [Fragment] class that simplifies handling of dispatch token response argument of a fragment.
*
* @param block The lambda block that is called with the received dispatch token response if it exists.
*/
fun Fragment.handleDispatchTokenResponse(block: (dispatchTokenResponse: String) -> Unit) {
arguments?.getString(FRAGMENT_ARGUMENT_DISPATCH_TOKEN_RESPONSE)?.let {
block(it)
}
arguments?.remove(FRAGMENT_ARGUMENT_DISPATCH_TOKEN_RESPONSE)
}
| 1 | Kotlin | 0 | 3 | 448eb8484df9a674b19931046a398dbb6db4138b | 860 | nevis-mobile-authentication-sdk-example-app-android-coroutines | MIT License |
app/src/main/java/com/puntogris/blint/feature_store/presentation/settings/BackupPreferences.kt | puntogris | 326,269,924 | false | {"Kotlin": 408095} | package com.puntogris.blint.feature_store.presentation.settings
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.findNavController
import androidx.preference.PreferenceFragmentCompat
import com.google.android.material.appbar.MaterialToolbar
import com.puntogris.blint.R
import com.puntogris.blint.common.utils.Keys
import com.puntogris.blint.common.utils.preferenceOnClick
import com.puntogris.blint.common.utils.registerToolbarBackButton
class BackupPreferences : PreferenceFragmentCompat() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.backup_preferences)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<MaterialToolbar>(R.id.preferences_toolbar).apply {
registerToolbarBackButton(this)
setTitle(R.string.backup_pref)
}
preferenceOnClick(Keys.CREATE_BACKUP_PREF) {
findNavController().navigate(R.id.createBackupFragment)
}
preferenceOnClick(Keys.RESTORE_BACKUP_PREF) {
findNavController().navigate(R.id.restoreBackupFragment)
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) = Unit
} | 0 | Kotlin | 0 | 1 | 63dcee8de767f8632f3c8a1cf4918f98bc01644d | 1,370 | blint | MIT License |
app/src/main/java/reach52/marketplace/community/persistence/policyOwner_mapper/BenefitMapper.kt | reach52 | 422,514,975 | false | {"Kotlin": 1436380, "Java": 18303} | package reach52.marketplace.community.persistence.policyOwner_mapper
import reach52.marketplace.community.models.policy_owner.Benefit
import reach52.marketplace.community.persistence.Marshaler
import reach52.marketplace.community.persistence.Unmarshaler
class BenefitMapper : Marshaler<Benefit>, Unmarshaler<Benefit> {
companion object {
const val KEY_CATEGORY = "category"
const val KEY_AMOUNT = "amount"
const val KEY_IDENTIFIER = "identifier"
}
override fun marshal(t: Benefit): Map<String, Any> {
return mapOf(
KEY_CATEGORY to t.category,
KEY_AMOUNT to t.amount,
KEY_IDENTIFIER to t.identifier
)
}
override fun unmarshal(properties: Map<String, Any>): Benefit {
return Benefit(
category = properties[KEY_CATEGORY] as String,
amount = (properties[KEY_AMOUNT] as Number).toDouble(),
identifier = properties[KEY_IDENTIFIER] as String
)
}
} | 0 | Kotlin | 0 | 0 | 629c52368d06f978f19238d0bd865f4ef84c23d8 | 1,020 | Marketplace-Community-Edition | MIT License |
app/src/main/java/com/olutoba/simplerecyclerview/data/Movies.kt | Olutobz | 460,094,468 | false | null | package com.olutoba.simplerecyclerview.data
import android.content.res.Resources
import com.olutoba.simplerecyclerview.R
// Returns initial list of movies
fun movieList(res: Resources): List<Movie> {
return listOf(
Movie(
id = 1,
name = res.getString(R.string.movie1_name),
image = R.drawable.the_tomorrow_war,
),
Movie(
id = 2,
name = res.getString(R.string.movie2_name),
image = R.drawable.encounter
),
Movie(
id = 3,
name = res.getString(R.string.movie3_name),
image = R.drawable.cinderella_image
),
Movie(
id = 4,
name = res.getString(R.string.movie4_name),
image = R.drawable.without_remorse
),
Movie(
id = 5,
name = res.getString(R.string.movie5_name),
image = R.drawable.wildling
),
Movie(
id = 6,
name = res.getString(R.string.movie6_name),
image = R.drawable.bliss
),
Movie(
id = 7,
name = res.getString(R.string.movie7_name),
image = R.drawable.sister_bliss
),
Movie(
id = 8,
name = res.getString(R.string.movie8_name),
image = R.drawable.aeon_flux
),
Movie(
id = 9,
name = res.getString(R.string.movie9_name),
image = R.drawable.spencer
),
Movie(
id = 10,
name = res.getString(R.string.movie10_name),
image = R.drawable.a_fall_from_grace
),
Movie(
id = 11,
name = res.getString(R.string.movie11_name),
image = R.drawable.nancy_drew_and_the_hidden_staircase
),
Movie(
id = 12,
name = res.getString(R.string.movie12_name),
image = R.drawable.security
),
Movie(
id = 13,
name = res.getString(R.string.movie13_name),
image = R.drawable.till_death
),
Movie(
id = 14,
name = res.getString(R.string.movie14_name),
image = R.drawable.intrusion
),
Movie(
id = 15,
name = res.getString(R.string.movie10_name),
image = R.drawable.initiation
),
Movie(
id = 16,
name = res.getString(R.string.movie16_name),
image = R.drawable.the_tender_bar
),
Movie(
id = 17,
name = res.getString(R.string.movie17_name),
image = R.drawable.coming_to_america
),
Movie(
id = 18,
name = res.getString(R.string.movie18_name),
image = R.drawable.disney_encanto
),
Movie(
id = 19,
name = res.getString(R.string.movie19_name),
image = R.drawable.music
),
Movie(
id = 20,
name = res.getString(R.string.movie20_name),
image = R.drawable.rumble
),
Movie(
id = 21,
name = res.getString(R.string.movie21_name),
image = R.drawable.shadow_in_the_cloud
),
Movie(
id = 22,
name = res.getString(R.string.movie22_name),
image = R.drawable.the_water_man
)
)
} | 0 | Kotlin | 0 | 0 | e0baf5bcba5dbcc9d5c3580aff699673e739e1ad | 3,476 | SimpleRecyclerView | Apache License 2.0 |
app/src/main/java/com/puntogris/blint/feature_store/presentation/main/MenuCardViewHolder.kt | puntogris | 326,269,924 | false | {"Kotlin": 366904} | package com.puntogris.blint.feature_store.presentation.main
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.puntogris.blint.databinding.MenuCardVhBinding
import com.puntogris.blint.feature_store.domain.model.MenuCard
class MenuCardViewHolder private constructor(val binding: MenuCardVhBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(menuCard: MenuCard, clickListener: (MenuCard) -> Unit) {
binding.menuCard = menuCard
binding.menuCardVhCard.setOnClickListener { clickListener(menuCard) }
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): MenuCardViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = MenuCardVhBinding.inflate(layoutInflater, parent, false)
return MenuCardViewHolder(binding)
}
}
}
| 0 | Kotlin | 0 | 0 | b2eca1902215292725c4624f10bc6ea81356386f | 949 | blint | MIT License |
kimhyebeen/Mission05/CustomBurger/app/src/main/java/com/khb/customburger/util/ViewExt.kt | Yapp-17th | 285,854,858 | false | {"Swift": 256086, "Kotlin": 116710, "JavaScript": 26300, "Ruby": 3960, "Objective-C": 1731, "HTML": 1196} | package com.khb.customburger.util
import android.graphics.Color
import android.view.View
import androidx.databinding.BindingAdapter
import androidx.lifecycle.LiveData
@BindingAdapter("checkSelected")
fun View.checkSelected(value: LiveData<Boolean>) {
if (value.value!!) this.setBackgroundColor(Color.parseColor("#B2C9F6"))
else this.setBackgroundColor(Color.parseColor("#ffffff"))
} | 20 | Swift | 1 | 5 | 572983a00913bbc110ce062f26fd2cb35475186b | 392 | Study_DesignPattern | MIT License |
sampleapp/src/main/java/com/kirkbushman/sampleapp/models/SubredditModel.kt | KirkBushman | 182,531,355 | false | null | package com.kirkbushman.sampleapp.models
import android.view.View
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyAttribute.Option.DoNotHash
import com.airbnb.epoxy.EpoxyModelClass
import com.kirkbushman.sampleapp.R
import com.kirkbushman.sampleapp.databinding.ItemSubredditBinding
import com.kirkbushman.sampleapp.models.base.ViewBindingEpoxyModelWithHolder
@EpoxyModelClass
abstract class SubredditModel : ViewBindingEpoxyModelWithHolder<ItemSubredditBinding>() {
@EpoxyAttribute
lateinit var subreddit: String
@EpoxyAttribute
var subscribed: Boolean = false
@EpoxyAttribute(DoNotHash)
lateinit var subscribeClick: View.OnClickListener
override fun getDefaultLayout(): Int {
return R.layout.item_subreddit
}
override fun ItemSubredditBinding.bind() {
title.text = subreddit
subscribeButton.text = if (subscribed) "Subscribe" else "Unsubscribe"
subscribeButton.setOnClickListener(subscribeClick)
}
override fun ItemSubredditBinding.unbind() {
subscribeButton.setOnClickListener(null)
}
}
| 9 | Kotlin | 9 | 84 | aeae071fa8d2a4e378de4a71420dc2a9792591f3 | 1,107 | ARAW | MIT License |
presentation/src/main/java/org/lotka/xenonx/presentation/ui/screen/detail/compose/DetailsTopBar.kt | armanqanih | 831,384,890 | false | {"Kotlin": 182678} | package org.lotka.xenonx.presentation.ui.screen.detail.compose
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.outlined.Bookmark
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import org.lotka.xenonx.presentation.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DetailsTopBar(
onBrowsingClick: () -> Unit,
onShareClick: () -> Unit,
onBookMarkClick: () -> Unit,
onBackClick: () -> Unit,
) {
TopAppBar(
modifier = Modifier.fillMaxWidth(),
colors = TopAppBarDefaults.mediumTopAppBarColors(
containerColor = Color.Transparent,
actionIconContentColor = colorResource(id = R.color.body),
navigationIconContentColor = colorResource(id = R.color.body),
),
title = {},
navigationIcon = {
IconButton(onClick = onBackClick) {
Icon(
imageVector = Icons.Filled.ArrowBack ,
contentDescription = null
)
}
},
actions = {
IconButton(onClick = onBookMarkClick) {
Icon(
imageVector = if (onBookMarkClick != null)
Icons.Outlined.Bookmark
else
Icons.Filled.Bookmark ,
contentDescription = null
)
}
IconButton(onClick = onShareClick) {
Icon(
imageVector = Icons.Filled.Share,
contentDescription = null
)
}
IconButton(onClick = onBrowsingClick) {
Icon(
painter = painterResource(id = R.drawable.ic_network),
contentDescription = null
)
}
},
)
}
| 0 | Kotlin | 0 | 0 | 8f87507882db7b71ce17c13fdf93ce08ec60a98a | 2,626 | MyGradleLastVersion | Apache License 2.0 |
editor/src/main/java/com/miracle/view/imageeditor/view/MosaicDetailsView.kt | lauhwong | 95,762,361 | false | null | package com.miracle.view.imageeditor.view
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.miracle.view.imageeditor.R
import com.miracle.view.imageeditor.Utils
/**
* ## UI element show mosaic details view
*
* Created by lxw
*/
class MosaicDetailsView(ctx: Context, onMosaicChangeListener: OnMosaicChangeListener?) : FrameLayout(ctx) {
constructor(ctx: Context) : this(ctx, null)
var onMosaicChangeListener: OnMosaicChangeListener? = null
var onRevokeListener: OnRevokeListener? = null
init {
this.onMosaicChangeListener = onMosaicChangeListener
LayoutInflater.from(ctx).inflate(R.layout.mosaic_func_details, this, true)
val rootFunc = findViewById(R.id.llMosaicDetails) as LinearLayout
val values = MosaicMode.values()
for (index in 0 until values.size) {
val mode = values[index]
if (mode.getModeBgResource() <= 0) {
continue
}
val item = LayoutInflater.from(context).inflate(R.layout.mosaic_item_func_details, rootFunc, false)
val ivFuncDesc = item.findViewById(R.id.ivMosaicDesc) as ImageView
ivFuncDesc.setImageResource(mode.getModeBgResource())
item.tag = mode
rootFunc.addView(item)
item.setOnClickListener {
onMosaicClick(mode, index, item, rootFunc)
}
if (index == 0) {
item.isSelected = true
onMosaicClick(mode, 0, item, rootFunc)
}
}
findViewById(R.id.ivRevoke).setOnClickListener {
onRevokeListener?.revoke(EditorMode.MosaicMode)
}
}
private fun onMosaicClick(mosaicMode: MosaicMode, position: Int, clickView: View, rootView: ViewGroup) {
Utils.changeSelectedStatus(rootView, position)
onMosaicChangeListener?.onChange(mosaicMode)
}
interface OnMosaicChangeListener {
fun onChange(mosaicMode: MosaicMode)
}
} | 1 | Kotlin | 9 | 29 | 0b5a5656bcf35f11a67538fa09ebacf610014de9 | 2,158 | ImageEditor | Apache License 2.0 |
models/src/main/java/com/vimeo/networking2/BasicAccessToken.kt | Geet2312 | 261,973,040 | false | {"Java Properties": 2, "Ruby": 3, "YAML": 3, "Gradle": 11, "Shell": 2, "Markdown": 7, "Batchfile": 1, "Text": 1, "Gemfile.lock": 1, "Ignore List": 6, "Git Config": 1, "Kotlin": 258, "XML": 30, "Proguard": 3, "Java": 37} | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import java.io.Serializable
/**
* Basic authentication for client credentials. It contains an access token
* that you could use to make unauthenticated requests.
*/
@JsonClass(generateAdapter = true)
data class BasicAccessToken(
@Json(name = "access_token")
override val accessToken: String
) : AccessTokenProvider, Serializable {
companion object {
private const val serialVersionUID = -29177L
}
}
| 1 | null | 1 | 1 | d66b4cddd07ff662175488b8f26823c1fbe1bfcf | 527 | vimeo-networking-java | MIT License |
data/model/src/main/java/com/hari/tmdb/model/Keyword.kt | HariKulhari06 | 255,623,659 | false | {"Gradle Kotlin DSL": 4, "Java Properties": 2, "Gradle": 18, "Shell": 1, "Text": 1, "Ignore List": 14, "Batchfile": 1, "Markdown": 1, "INI": 13, "Proguard": 14, "Kotlin": 256, "XML": 175, "Java": 5, "JSON": 3} | package com.hari.tmdb.model
data class Keyword(
val id: Int,
val name: String
) | 0 | Kotlin | 1 | 5 | c3b94cc6e65882b23e904ba479466a6897b920cc | 88 | tmdb_app | MIT License |
module/src/main/java/com/heyongrui/module/data/dto/QDailyNewsDto.kt | HeYongRui | 192,505,459 | false | null | package com.heyongrui.module.data.dto
import android.os.Parcel
import android.os.Parcelable
import java.io.Serializable
data class QDailyNewsDto(
var banners: List<Banner>,
// var banners_ad: List<Any>,
var columns: List<Column>,
// var columns_ad: List<Any>,
// var featured_article: List<Any>,
var feeds: List<Feed>,
// var feeds_ad: List<Any>,
var has_more: Boolean,
var last_key: String
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.createTypedArrayList(Banner),
parcel.createTypedArrayList(Column),
parcel.createTypedArrayList(Feed),
parcel.readByte() != 0.toByte(),
parcel.readString()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeTypedList(banners)
parcel.writeTypedList(columns)
parcel.writeTypedList(feeds)
parcel.writeByte(if (has_more) 1 else 0)
parcel.writeString(last_key)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<QDailyNewsDto> {
private const val serialVersionUID = 592852979308925024L
override fun createFromParcel(parcel: Parcel): QDailyNewsDto {
return QDailyNewsDto(parcel)
}
override fun newArray(size: Int): Array<QDailyNewsDto?> {
return arrayOfNulls(size)
}
}
}
data class Banner(
var image: String,
var post: Post,
var type: Int
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readParcelable(Post::class.java.classLoader),
parcel.readInt()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(image)
parcel.writeParcelable(post, flags)
parcel.writeInt(type)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Banner> {
private const val serialVersionUID = 5923979793048925024L
override fun createFromParcel(parcel: Parcel): Banner {
return Banner(parcel)
}
override fun newArray(size: Int): Array<Banner?> {
return arrayOfNulls(size)
}
}
}
data class Feed(
var image: String,
var post: Post,
var type: Int//0-上图下文 1-左文右图
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readParcelable(Post::class.java.classLoader),
parcel.readInt()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(image)
parcel.writeParcelable(post, flags)
parcel.writeInt(type)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Feed> {
private const val serialVersionUID = 5128979793048925024L
override fun createFromParcel(parcel: Parcel): Feed {
return Feed(parcel)
}
override fun newArray(size: Int): Array<Feed?> {
return arrayOfNulls(size)
}
}
}
data class Post(
var appview: String,
var column: Column,
var category: Category,
var comment_count: Int,
var comment_status: Boolean,
var datatype: String,//paper article
var description: String,
var film_length: String,
var genre: Int,
var id: Int,
var image: String,
var page_style: Int,
var post_id: Int,
var praise_count: Int,
var publish_time: Int,
var start_time: Int,
var record_count: Int,
var super_tag: String,
var title: String
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readParcelable(Column::class.java.classLoader),
parcel.readParcelable(Category::class.java.classLoader),
parcel.readInt(),
parcel.readByte() != 0.toByte(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readInt(),
parcel.readInt(),
parcel.readString(),
parcel.readInt(),
parcel.readInt(),
parcel.readInt(),
parcel.readInt(),
parcel.readInt(),
parcel.readInt(),
parcel.readString(),
parcel.readString()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(appview)
parcel.writeParcelable(column, flags)
parcel.writeParcelable(category, flags)
parcel.writeInt(comment_count)
parcel.writeByte(if (comment_status) 1 else 0)
parcel.writeString(datatype)
parcel.writeString(description)
parcel.writeString(film_length)
parcel.writeInt(genre)
parcel.writeInt(id)
parcel.writeString(image)
parcel.writeInt(page_style)
parcel.writeInt(post_id)
parcel.writeInt(praise_count)
parcel.writeInt(publish_time)
parcel.writeInt(start_time)
parcel.writeInt(record_count)
parcel.writeString(super_tag)
parcel.writeString(title)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Post> {
private const val serialVersionUID = 5928979793648925024L
override fun createFromParcel(parcel: Parcel): Post {
return Post(parcel)
}
override fun newArray(size: Int): Array<Post?> {
return arrayOfNulls(size)
}
}
}
data class Column(
var column_tag: String,
var content_provider: String,
var description: String,
var genre: Int,
var icon: String,
var id: Int,
var image: String,
var image_large: String,
var location: Int,
var name: String,
var post_count: Int,
var share: Share,
var show_type: Int,
var sort_time: String,
var subscribe_status: Boolean,
var subscriber_num: Int
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readInt(),
parcel.readString(),
parcel.readInt(),
parcel.readString(),
parcel.readString(),
parcel.readInt(),
parcel.readString(),
parcel.readInt(),
parcel.readParcelable(Share::class.java.classLoader),
parcel.readInt(),
parcel.readString(),
parcel.readByte() != 0.toByte(),
parcel.readInt()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(column_tag)
parcel.writeString(content_provider)
parcel.writeString(description)
parcel.writeInt(genre)
parcel.writeString(icon)
parcel.writeInt(id)
parcel.writeString(image)
parcel.writeString(image_large)
parcel.writeInt(location)
parcel.writeString(name)
parcel.writeInt(post_count)
parcel.writeParcelable(share, flags)
parcel.writeInt(show_type)
parcel.writeString(sort_time)
parcel.writeByte(if (subscribe_status) 1 else 0)
parcel.writeInt(subscriber_num)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Column> {
private const val serialVersionUID = 5928979793048925074L
override fun createFromParcel(parcel: Parcel): Column {
return Column(parcel)
}
override fun newArray(size: Int): Array<Column?> {
return arrayOfNulls(size)
}
}
}
data class Category(
var id: Int,
var image_experiment: String,
var image_lab: String,
var normal: String,
var normal_hl: String,
var title: String
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeString(image_experiment)
parcel.writeString(image_lab)
parcel.writeString(normal)
parcel.writeString(normal_hl)
parcel.writeString(title)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Category> {
private const val serialVersionUID = 5928979793048925024L
override fun createFromParcel(parcel: Parcel): Category {
return Category(parcel)
}
override fun newArray(size: Int): Array<Category?> {
return arrayOfNulls(size)
}
}
}
data class Share(
var image: String,
var text: String,
var title: String,
var url: String
) : Parcelable, Serializable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(image)
parcel.writeString(text)
parcel.writeString(title)
parcel.writeString(url)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Share> {
private const val serialVersionUID = 5928979793048925064L
override fun createFromParcel(parcel: Parcel): Share {
return Share(parcel)
}
override fun newArray(size: Int): Array<Share?> {
return arrayOfNulls(size)
}
}
} | 1 | Java | 4 | 23 | 303f75f87d3c7a7bdac37de34519d9da6a8737f7 | 10,186 | YouJu | Apache License 2.0 |
platform/wizard/template-impl/src/main/kotlin/com/rivan/androlabs/wizard/template/impl/CommonParameters.kt | RivanParmar | 526,653,590 | false | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Modified by <NAME> on 06/05/2023
package com.rivan.androlabs.wizard.template.impl
import com.rivan.androlabs.wizard.template.api.StringParameter
import com.rivan.androlabs.wizard.template.api.stringParameter
val defaultPackageNameParameter: StringParameter
get() = stringParameter {
name = "Package name"
visible = { !isNewModule }
default = "com.mycompany.myapp"
suggest = { packageName }
} | 0 | null | 2 | 17 | a497291d77bba1aa34271808088fe1e8aab5efe2 | 1,058 | androlabs | Apache License 2.0 |
okio/src/jvmTest/kotlin/okio/JimfsOkioRoundTripTest.kt | square | 17,812,502 | false | null | /*
* Copyright (C) 2023 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import java.nio.file.StandardOpenOption
import kotlin.io.path.readText
import kotlin.io.path.writeText
import kotlin.test.BeforeTest
import kotlin.test.assertEquals
import okio.FileSystem.Companion.asOkioFileSystem
import org.junit.Test
class JimfsOkioRoundTripTest {
private val temporaryDirectory = FileSystem.SYSTEM_TEMPORARY_DIRECTORY
private val jimFs = Jimfs.newFileSystem(
when (Path.DIRECTORY_SEPARATOR == "\\") {
true -> Configuration.windows()
false -> Configuration.unix()
}.toBuilder()
.setWorkingDirectory(temporaryDirectory.toString())
.build(),
)
private val jimFsRoot = jimFs.rootDirectories.first()
private val okioFs = jimFs.asOkioFileSystem()
private val base: Path = temporaryDirectory / "${this::class.simpleName}-${randomToken(16)}"
@BeforeTest
fun setUp() {
okioFs.createDirectory(base)
}
@Test
fun writeOkioReadJim() {
val path = base / "file-handle-write-okio-and-read-jim"
okioFs.write(path) {
writeUtf8("abcdefghijklmnop")
}
assertEquals("abcdefghijklmnop", jimFsRoot.resolve(path.toString()).readText(Charsets.UTF_8))
}
@Test
fun writeJimReadOkio() {
val path = base / "file-handle-write-jim-and-read-okio"
jimFsRoot.resolve(path.toString()).writeText("abcdefghijklmnop", Charsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.WRITE)
okioFs.openReadWrite(path).use { handle ->
handle.source().buffer().use { source ->
assertEquals("abcde", source.readUtf8(5))
assertEquals("fghijklmnop", source.readUtf8())
}
}
}
}
| 89 | null | 1178 | 8,795 | 0f6c9cf31101483e6ee9602e80a10f7697c8f75a | 2,286 | okio | Apache License 2.0 |
vandadownloader/src/main/java/vanda/wzl/vandadownloader/multitask/TaskDispatherAttribute.kt | 10045125 | 144,871,412 | false | null | /*
* Copyright (c) 2018 YY Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanda.wzl.vandadownloader.multitask
interface TaskDispatherAttribute {
fun start(url: String, threadNum: Int, path: String, callbackProgressTimes: Int, callbackProgressMinIntervalMillis: Int, autoRetryTimes: Int, forceReDownload: Boolean, header: Map<String, String>, isWifiRequired: Boolean, postBody: String)
fun pause(downloadId: Int)
fun isDownloading(downloadId: Int): Boolean
fun isDownloading(url: String, path: String): Boolean
fun getStatus(downloadId: Int): Int
fun getSofar(downloadId: Int): Long
fun getTotal(downloadId: Int): Long
fun isIdle(): Boolean
fun isBreakPointContinued(downloadId: Int): Boolean
} | 1 | Kotlin | 7 | 26 | b0f6c1f5780c1eaffdc08b2a8358bd9c3f5cdc2d | 1,261 | VandaDownloader | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.